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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620
  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.1 \number\year-\number\month-\number\day}
  25. \def\years{2007--2018}
  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 QColor.
  3434. \noindent |QColor| support is limited to creating colors from strings to pass
  3435. to objects expecting a color.
  3436. @<Function prototypes for scripting@>=
  3437. QScriptValue constructQColor(QScriptContext *context, QScriptEngine *engine);
  3438. @ We must tell the script engine about the constructor. This is not done in
  3439. quite the same way as is done for |QObject| derived types.
  3440. @<Set up the scripting engine@>=
  3441. constructor = engine->newFunction(constructQColor);
  3442. engine->globalObject().setProperty("QColor", constructor);
  3443. @ The constructor is trivial.
  3444. @<Functions for scripting@>=
  3445. QScriptValue constructQColor(QScriptContext *context, QScriptEngine *engine)
  3446. {
  3447. QScriptValue object = engine->toScriptValue<QColor>(QColor(argument<QString>(0, context)));
  3448. return object;
  3449. }
  3450. @* Scripting QBrush.
  3451. \noindent |QBrush| support is limited to creating brushes from color strings to
  3452. pass to objects expecting a brush.
  3453. @<Function prototypes for scripting@>=
  3454. QScriptValue constructQBrush(QScriptContext *context, QScriptEngine *engine);
  3455. @ The script is informed of the constructor.
  3456. @<Set up the scripting engine@>=
  3457. constructor = engine->newFunction(constructQBrush);
  3458. engine->globalObject().setProperty("QBrush", constructor);
  3459. @ The constructor is trivial.
  3460. @<Functions for scripting@>=
  3461. QScriptValue constructQBrush(QScriptContext *context, QScriptEngine *engine)
  3462. {
  3463. QBrush theBrush = QBrush(QColor(argument<QString>(0, context)));
  3464. QScriptValue object = engine->toScriptValue(theBrush);
  3465. return object;
  3466. }
  3467. @* Scripting Item View Classes.
  3468. \noindent |QAbstractScrollArea| is a |QFrame| that serves as the base class for
  3469. classes such as |QGraphicsView| and |QAbstractItemView|. Objects from this class
  3470. are not created directly.
  3471. @<Function prototypes for scripting@>=
  3472. void setQAbstractScrollAreaProperties(QScriptValue value,
  3473. QScriptEngine *engine);
  3474. @ The implementation of this is simple.
  3475. @<Functions for scripting@>=
  3476. void setQAbstractScrollAreaProperties(QScriptValue value, QScriptEngine *engine)
  3477. {
  3478. setQFrameProperties(value, engine);
  3479. }
  3480. @ This class is used by the |QAbstractItemView| class. This is another class
  3481. that we do not need a script constructor for.
  3482. @<Function prototypes for scripting@>=
  3483. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine);
  3484. @ This function has another simple implementation.
  3485. @<Functions for scripting@>=
  3486. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine)
  3487. {
  3488. setQAbstractScrollAreaProperties(value, engine);
  3489. }
  3490. @ The |QGraphicsView| and |QTableView| classes form the base of \pn{} classes.
  3491. @<Function prototypes for scripting@>=
  3492. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine);
  3493. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine);
  3494. @ Again, the implementations are boring.
  3495. @<Functions for scripting@>=
  3496. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine)
  3497. {
  3498. setQAbstractScrollAreaProperties(value, engine);
  3499. }
  3500. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine)
  3501. {
  3502. setQAbstractItemViewProperties(value, engine);
  3503. }
  3504. @* Scripting Button Classes.
  3505. \noindent \pn{} provides an |AnnotationButton| class which is a special kind of
  3506. |QPushButton| which in turn comes from |QAbstractButton|. While
  3507. |AnnotationButton| can be used in exactly the same way as a |QPushButton|, if
  3508. an annotation is not needed, there is little reason not to use the base class.
  3509. @<Function prototypes for scripting@>=
  3510. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine);
  3511. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine);
  3512. QScriptValue constructQPushButton(QScriptContext *context,
  3513. QScriptEngine *engine);
  3514. @ The constructor for |QPushButton| should be passed to the scripting engine.
  3515. @<Set up the scripting engine@>=
  3516. constructor = engine->newFunction(constructQPushButton);
  3517. value = engine->newQMetaObject(&QPushButton::staticMetaObject, constructor);
  3518. engine->globalObject().setProperty("QPushButton", value);
  3519. @ The implementation should seem familiar.
  3520. @<Functions for scripting@>=
  3521. QScriptValue constructQPushButton(QScriptContext *, QScriptEngine *engine)
  3522. {
  3523. QScriptValue object = engine->newQObject(new QPushButton());
  3524. setQPushButtonProperties(object, engine);
  3525. return object;
  3526. }
  3527. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine)
  3528. {
  3529. setQAbstractButtonProperties(value, engine);
  3530. }
  3531. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine)
  3532. {
  3533. setQWidgetProperties(value, engine);
  3534. }
  3535. @* Scripting QSqlQuery.
  3536. \noindent With this class exposed to the host environment, it becomes possible
  3537. for script code to execute SQL queries and evaluate the result.
  3538. Rather than use |QSqlQuery| directly, however, we use a proxy \nfnote{Erich
  3539. Gamma, Richard Helm, Raph Johnson, and John
  3540. Vlissides,\par\indent\underbar{Design Patterns: elements of reusable
  3541. object-oriented software} (1995) pp. 207--217} class. This class obtains its own
  3542. database connection and handles properly closing and removing these connections
  3543. when the query object is destroyed.
  3544. @<Class declarations@>=
  3545. class SqlQueryConnection : public QSqlQuery@/
  3546. {
  3547. public:@/
  3548. SqlQueryConnection(const QString &query = QString());
  3549. ~SqlQueryConnection();
  3550. QSqlQuery* operator->() const;
  3551. private:@/
  3552. QString connection;
  3553. QSqlQuery *q;
  3554. };
  3555. @ The constructor can be somewhat simplified from the four forms of |QSqlQuery|.
  3556. We are not interested in creating an object from a |QSqlResult| or from another
  3557. |QSqlQuery|. The database connection is managed by the class itself so the
  3558. constructor only needs an optional string containing a query. This is used to
  3559. initialize a real |QSqlQuery| object.
  3560. @<SqlQueryConnection implementation@>=
  3561. SqlQueryConnection::SqlQueryConnection(const QString &query)
  3562. {
  3563. QSqlDatabase database = AppInstance->database();
  3564. database.open();
  3565. q = new QSqlQuery(query, database);
  3566. connection = database.connectionName();
  3567. }
  3568. @ The destructor handles removing the |QSqlQuery| and the database connection
  3569. associated with it. The extra brackets introduce a new scope for the
  3570. |QSqlDatabase| so that it is out of scope when the connection is removed.
  3571. @<SqlQueryConnection implementation@>=
  3572. SqlQueryConnection::~SqlQueryConnection()
  3573. {
  3574. delete q;
  3575. {
  3576. QSqlDatabase database = QSqlDatabase::database(connection);
  3577. database.close();
  3578. }
  3579. QSqlDatabase::removeDatabase(connection);
  3580. }
  3581. @ For all other functionality, we simply forward the request to our |QSqlQuery|
  3582. object.
  3583. @<SqlQueryConnection implementation@>=
  3584. QSqlQuery* SqlQueryConnection::operator->() const
  3585. {
  3586. return q;
  3587. }
  3588. @ In order to use this new class in the host environment, a number of functions
  3589. are needed.
  3590. @<Function prototypes for scripting@>=
  3591. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine);
  3592. QScriptValue constructQSqlQuery(QScriptContext *context, QScriptEngine *engine);
  3593. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *engine);
  3594. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  3595. QScriptEngine *engine);
  3596. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  3597. QScriptEngine *engine);
  3598. QScriptValue QSqlQuery_exec(QScriptContext *context,
  3599. QScriptEngine *engine);
  3600. QScriptValue QSqlQuery_executedQuery(QScriptContext *context,
  3601. QScriptEngine *engine);
  3602. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *engine);
  3603. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine);
  3604. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine);
  3605. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine);
  3606. @ For conceptual convenience we simply pretend that we are working with a real
  3607. |QSqlQuery| object.
  3608. @<Set up the scripting engine@>=
  3609. constructor = engine->newFunction(constructQSqlQuery);
  3610. engine->globalObject().setProperty("QSqlQuery", constructor);
  3611. @ With connection creation no longer needed in the constructor, all that is
  3612. needed is object creation and applying the appropriate properties to the script
  3613. value.
  3614. @<Functions for scripting@>=
  3615. QScriptValue constructQSqlQuery(QScriptContext *, QScriptEngine *engine)
  3616. {
  3617. SqlQueryConnection *obj = new SqlQueryConnection();
  3618. QScriptValue object =
  3619. engine->toScriptValue<void *>(obj);
  3620. setQSqlQueryProperties(object, engine);
  3621. return object;
  3622. }
  3623. @ As this class does not derive from |QObject|, we must wrap all of the methods
  3624. we might want to use.
  3625. @<Functions for scripting@>=
  3626. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine)
  3627. {
  3628. value.setProperty("bind", engine->newFunction(QSqlQuery_bind));
  3629. value.setProperty("bindFileData",
  3630. engine->newFunction(QSqlQuery_bindFileData));
  3631. value.setProperty("bindDeviceData",
  3632. engine->newFunction(QSqlQuery_bindDeviceData));
  3633. value.setProperty("exec", engine->newFunction(QSqlQuery_exec));
  3634. value.setProperty("executedQuery", engine->newFunction(QSqlQuery_executedQuery));
  3635. value.setProperty("invalidate", engine->newFunction(QSqlQuery_invalidate));
  3636. value.setProperty("next", engine->newFunction(QSqlQuery_next));
  3637. value.setProperty("prepare", engine->newFunction(QSqlQuery_prepare));
  3638. value.setProperty("value", engine->newFunction(QSqlQuery_value));
  3639. }
  3640. @ Most of these properties are wrappers around existing |QSqlQuery| functions.
  3641. @<Functions for scripting@>=
  3642. QScriptValue QSqlQuery_exec(QScriptContext *context, QScriptEngine *engine)
  3643. {
  3644. QSqlQuery *q = getself<SqlQueryConnection *>(context)->operator->();
  3645. QScriptValue retval;
  3646. if(context->argumentCount() == 1)
  3647. {
  3648. retval = QScriptValue(engine,
  3649. q->exec(argument<QString>(0, context)));
  3650. }
  3651. else
  3652. {
  3653. retval = QScriptValue(engine, q->exec());
  3654. }
  3655. if(q->lastError().isValid())
  3656. {
  3657. qDebug() << q->lastQuery();
  3658. qDebug() << q->lastError().text();
  3659. }
  3660. return retval;
  3661. }
  3662. QScriptValue QSqlQuery_executedQuery(QScriptContext *context, QScriptEngine *)
  3663. {
  3664. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3665. return QScriptValue(query->lastQuery());
  3666. }
  3667. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine)
  3668. {
  3669. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3670. return QScriptValue(engine, query->next());
  3671. }
  3672. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine)
  3673. {
  3674. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3675. return QScriptValue(engine,
  3676. query->value(argument<int>(0, context)).toString());
  3677. }
  3678. @ For prepared queries, we support binding variables available to the script,
  3679. data available in a named file, or data from any open |QIODevice|.
  3680. @<Functions for scripting@>=
  3681. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine)
  3682. {
  3683. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3684. return QScriptValue(engine, query->prepare(argument<QString>(0, context)));
  3685. }
  3686. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *)
  3687. {
  3688. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3689. query->bindValue(argument<QString>(0, context),
  3690. argument<QVariant>(1, context));
  3691. return QScriptValue();
  3692. }
  3693. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  3694. QScriptEngine *)
  3695. {
  3696. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3697. QString placeholder = argument<QString>(0, context);
  3698. QString filename = argument<QString>(1, context);
  3699. QFile file(filename);
  3700. QByteArray data;
  3701. if(file.open(QIODevice::ReadOnly))
  3702. {
  3703. data = file.readAll();
  3704. file.close();
  3705. }
  3706. query->bindValue(placeholder, data);
  3707. return QScriptValue();
  3708. }
  3709. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  3710. QScriptEngine *)
  3711. {
  3712. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3713. QString placeholder = argument<QString>(0, context);
  3714. QIODevice *device = argument<QIODevice *>(1, context);
  3715. device->reset();
  3716. QByteArray data;
  3717. data = device->readAll();
  3718. query->bindValue(placeholder, data);
  3719. return QScriptValue();
  3720. }
  3721. @ To avoid leaking database connections, we add the |invalidate()| property
  3722. which destroys our object. The object on which this method is called must not be
  3723. used after calling this method. In script code this will typically be used as in
  3724. the following example:
  3725. {\tt query = query.invalidate();}
  3726. @<Functions for scripting@>=
  3727. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *)
  3728. {
  3729. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  3730. delete query;
  3731. return QScriptValue::UndefinedValue;
  3732. }
  3733. @* Other scripting functions.
  3734. \noindent There are a few functions that are exposed to the scripting engine
  3735. that are not associated with any class. Two functions are used for extracting
  3736. information from file names. Another is used to construct array values from SQL
  3737. array values. There is also a function for setting the default font for the
  3738. application or some part of the application.
  3739. @<Function prototypes for scripting@>=
  3740. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine);
  3741. QScriptValue dir(QScriptContext *context, QScriptEngine *engine);
  3742. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine);
  3743. QScriptValue setFont(QScriptContext *context, QScriptEngine *engine);
  3744. QScriptValue annotationFromRecord(QScriptContext *context,
  3745. QScriptEngine *engine);
  3746. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *engine);
  3747. QScriptValue saveFileFromDatabase(QScriptContext *context, QScriptEngine *engine);
  3748. QScriptValue scriptTr(QScriptContext *context, QScriptEngine *engine);
  3749. @ These functions are passed to the scripting engine.
  3750. @<Set up the scripting engine@>=
  3751. engine->globalObject().setProperty("baseName", engine->newFunction(baseName));
  3752. engine->globalObject().setProperty("dir", engine->newFunction(dir));
  3753. engine->globalObject().setProperty("sqlToArray",
  3754. engine->newFunction(sqlToArray));
  3755. engine->globalObject().setProperty("setFont", engine->newFunction(setFont));
  3756. engine->globalObject().setProperty("annotationFromRecord",
  3757. engine->newFunction(annotationFromRecord));
  3758. engine->globalObject().setProperty("setTabOrder",
  3759. engine->newFunction(setTabOrder));
  3760. engine->globalObject().setProperty("saveFileFromDatabase",
  3761. engine->newFunction(saveFileFromDatabase));
  3762. engine->globalObject().setProperty("TTR", engine->newFunction(scriptTr));
  3763. @ These functions are not part of an object. They expect a string specifying
  3764. the path to a file and return a string with either the name of the file without
  3765. the path and extension or the path of the directory containing the file.
  3766. @<Functions for scripting@>=
  3767. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine)
  3768. {
  3769. QFileInfo info(argument<QString>(0, context));
  3770. QScriptValue retval(engine, info.baseName());
  3771. return retval;
  3772. }
  3773. QScriptValue dir(QScriptContext *context, QScriptEngine *engine)
  3774. {
  3775. QFileInfo info(argument<QString>(0, context));
  3776. QDir dir = info.dir();
  3777. QScriptValue retval(engine, dir.path());
  3778. return retval;
  3779. }
  3780. @ This function takes a file ID and a file name and copies file data stored in
  3781. the database out to the file system.
  3782. @<Functions for scripting@>=
  3783. QScriptValue saveFileFromDatabase(QScriptContext *context, QScriptEngine *)
  3784. {
  3785. SqlQueryConnection h;
  3786. QSqlQuery *query = h.operator->();
  3787. QString q = "SELECT file FROM files WHERE id = :file";
  3788. query->prepare(q);
  3789. query->bindValue(":file", argument<int>(0, context));
  3790. query->exec();
  3791. query->next();
  3792. QByteArray array = query->value(0).toByteArray();
  3793. QFile file(argument<QString>(1, context));
  3794. file.open(QIODevice::WriteOnly);
  3795. file.write(array);
  3796. file.close();
  3797. return QScriptValue();
  3798. }
  3799. @ This function takes a string representing a SQL array and returns an array
  3800. value.
  3801. @<Functions for scripting@>=
  3802. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine)
  3803. {
  3804. QString source = argument<QString>(0, context);
  3805. source.remove(0, 1);
  3806. source.chop(1);
  3807. QStringList elements = source.split(",");
  3808. QString element;
  3809. QScriptValue dest = engine->newArray(elements.size());
  3810. int i = 0;
  3811. foreach(element, elements)
  3812. {
  3813. if(element.startsWith("\"") && element.endsWith("\""))
  3814. {
  3815. element.chop(1);
  3816. element = element.remove(0, 1);
  3817. }
  3818. dest.setProperty(i, QScriptValue(engine, element));
  3819. i++;
  3820. }
  3821. return dest;
  3822. }
  3823. @ This function can be used to set the default font for the application or on
  3824. a per-class hierarchy basis.
  3825. @<Functions for scripting@>=
  3826. QScriptValue setFont(QScriptContext *context, QScriptEngine *)
  3827. {
  3828. QString font = argument<QString>(0, context);
  3829. QString classname;
  3830. if(context->argumentCount() > 1)
  3831. {
  3832. classname = argument<QString>(1, context);
  3833. QApplication::setFont(QFont(font), classname.toLatin1().constData());
  3834. }
  3835. else
  3836. {
  3837. QApplication::setFont(QFont(font));
  3838. }
  3839. return QScriptValue();
  3840. }
  3841. @ This function was briefly used prior to adding support for |QXmlQuery| in the
  3842. host environment. The function is now depreciated and should not be used.
  3843. @<Functions for scripting@>=
  3844. QScriptValue annotationFromRecord(QScriptContext *context, QScriptEngine *)
  3845. {
  3846. SqlQueryConnection h;
  3847. QSqlQuery *query = h.operator->();
  3848. QString q = "SELECT file FROM files WHERE id = :file";
  3849. query->prepare(q);
  3850. query->bindValue(":file", argument<int>(0, context));
  3851. query->exec();
  3852. query->next();
  3853. QByteArray array = query->value(0).toByteArray();
  3854. QBuffer buffer(&array);
  3855. buffer.open(QIODevice::ReadOnly);
  3856. QXmlQuery xquery;
  3857. xquery.bindVariable("profile", &buffer);
  3858. QString xq;
  3859. xq = "for $b in doc($profile) //tuple where exists($b/annotation) return $b";
  3860. xquery.setQuery(xq);
  3861. QString result;
  3862. xquery.evaluateTo(&result);
  3863. return QScriptValue(result);
  3864. }
  3865. @ This function can be used to change the tab order for controls in Typica.
  3866. Changes to the example configuration in \pn{} 1.4 made the default handling
  3867. of tab controls in the logging window unacceptable.
  3868. @<Functions for scripting@>=
  3869. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *)
  3870. {
  3871. QWidget::setTabOrder(argument<QWidget*>(0, context),
  3872. argument<QWidget*>(1, context));
  3873. return QScriptValue();
  3874. }
  3875. @ This function is used to allow text that must be placed in scripts to be
  3876. translated into other languages.
  3877. @<Functions for scripting@>=
  3878. QScriptValue scriptTr(QScriptContext *context, QScriptEngine *)
  3879. {
  3880. return QScriptValue(QCoreApplication::translate(
  3881. "configuration",
  3882. argument<QString>(1, context).toUtf8().data()));
  3883. }
  3884. @** Application Configuration.
  3885. \noindent While \pn{} is intended as a data logging application, the diversity
  3886. of equipment and supporting technology precludes the option of providing a
  3887. single interface for common tasks. It is important that the application can be
  3888. configured to work with different roasting equipment, databases, and the like.
  3889. To accomplish this, \pn{} utilizes an XML description of the desired application
  3890. configuration and provides an ECMA-262 host environment which allows application
  3891. dataflow to be configured.
  3892. The scripting environment provides access to elements of the XML file and also
  3893. allows access to most of the application classes. A selection of classes
  3894. provided by Qt is also available. See the section on The Scripting Engine for
  3895. more details.
  3896. \danger While the code is the ultimate documentation of what is possible with
  3897. this interface, additional documentation should be provided to document the
  3898. meaning of supported elements and the objects available through the scripting
  3899. engine.\endanger
  3900. The application configuration is loaded when the program is started.
  3901. Starting with version 1.4, we check for a command line option with the path to
  3902. the configuration file and load that instead of prompting for the information
  3903. if possible.
  3904. Starting with version 1.8, if there is not a -c argument, Typica will first
  3905. search a small number of locations relative to the executable.
  3906. @<Load the application configuration@>=
  3907. QStringList arguments = QCoreApplication::arguments();
  3908. int position = arguments.indexOf("-c");
  3909. QString filename = QString();
  3910. if(position != -1)
  3911. {
  3912. if(arguments.size() >= position + 1)
  3913. {
  3914. filename = arguments.at(position + 1);
  3915. }
  3916. } else {
  3917. QDir checkPath(QCoreApplication::applicationDirPath() + "/../config/");
  3918. if(checkPath.exists("config.xml")) {
  3919. filename = checkPath.filePath("config.xml");
  3920. } else {
  3921. checkPath = QDir(QCoreApplication::applicationDirPath() + "/config/");
  3922. if(checkPath.exists("config.xml")) {
  3923. filename = checkPath.filePath("config.xml");
  3924. }
  3925. }
  3926. }
  3927. if(filename.isEmpty())
  3928. {
  3929. filename = QFileDialog::getOpenFileName(NULL, "Open Configuration File",
  3930. settings.value("config", "").toString());
  3931. }
  3932. QDir directory;
  3933. if(!filename.isEmpty())
  3934. {
  3935. QFile file(filename);
  3936. QFileInfo info(filename);
  3937. directory = info.dir();
  3938. QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
  3939. QTranslator *configtr = new QTranslator;
  3940. if(configtr->load(QString("config.%1").arg(QLocale::system().name()),
  3941. QString("%1/Translations").arg(directory.canonicalPath())))
  3942. {
  3943. QCoreApplication::installTranslator(configtr);
  3944. }
  3945. settings.setValue("config", directory.path());
  3946. if(file.open(QIODevice::ReadOnly))
  3947. {
  3948. app.configuration()->setContent(&file, true);
  3949. }
  3950. } else {
  3951. return 1;
  3952. }
  3953. @<Substitute included fragments@>@;
  3954. @ The {\tt <application>} element can contain an arbitrary number of
  3955. {\tt <include>} elements. These elements should not appear in the DOM. Instead,
  3956. the element should be replaced by the content of the specified document.
  3957. @<Substitute included fragments@>=
  3958. QDomElement root = app.configuration()->documentElement();
  3959. QDomNodeList children = root.childNodes();
  3960. QString replacementDoc;
  3961. QDomDocument includedDoc;
  3962. QDomDocumentFragment fragment;
  3963. for(int i = 0; i < children.size(); i++)
  3964. {
  3965. QDomNode currentNode = children.at(i);
  3966. QDomElement currentElement;
  3967. if(currentNode.nodeName() == "include")
  3968. {
  3969. currentElement = currentNode.toElement();
  3970. if(currentElement.hasAttribute("src"))
  3971. {
  3972. replacementDoc = directory.path();
  3973. replacementDoc.append('/');
  3974. replacementDoc.append(currentElement.attribute("src"));
  3975. QFile doc(replacementDoc);
  3976. if(doc.open(QIODevice::ReadOnly))
  3977. {
  3978. includedDoc.setContent(&doc, true);
  3979. fragment = includedDoc.createDocumentFragment();
  3980. fragment.appendChild(includedDoc.documentElement());
  3981. root.replaceChild(fragment, currentNode);
  3982. doc.close();
  3983. }
  3984. }
  3985. }
  3986. }
  3987. @ Simply loading the configuration document does not display a user interface or
  3988. set up any objects that allow the program to do anything. To do this, a script
  3989. obtained from the configuration document is run. The root element of the
  3990. document should be {\tt <application>}. This element should have a number of
  3991. child elements including {\tt <window>} elements which describe the various
  3992. windows that can be opened in the application and {\tt <program>} elements
  3993. containing script code. These {\tt <program>} elements can occur in a number of
  3994. different contexts including within {\tt <window>} elements which would indicate
  3995. that such scripts should be evaluated when the window being described is
  3996. created. After the configuration document is loaded, all {\tt <program>}
  3997. elements that are direct children of the {\tt <application>} element are
  3998. concatenated and the script is run.
  3999. Before the script is run and user interface elements are drawn, we also check
  4000. for {\tt <style>} elements which can be used to set up a stylesheet for the
  4001. application.
  4002. @<Find and evaluate starting script@>=
  4003. QString styleText;
  4004. QString programText;
  4005. QDomElement currentElement;
  4006. for(int i = 0; i < children.size(); i++)
  4007. {
  4008. QDomNode currentNode = children.at(i);
  4009. if(currentNode.nodeName() == "style")
  4010. {
  4011. currentElement = currentNode.toElement();
  4012. styleText.append(currentElement.text());
  4013. }
  4014. else if(currentNode.nodeName() == "program")
  4015. {
  4016. currentElement = currentNode.toElement();
  4017. programText.append(currentElement.text());
  4018. }
  4019. }
  4020. app.setStyleSheet(styleText);
  4021. QScriptValue result = engine->evaluate(programText);
  4022. @<Report scripting errors@>
  4023. @ When a script is evaluated, there is a chance that there will be some error in
  4024. the execution of that script. If this occurs, we want to report that.
  4025. @<Report scripting errors@>=
  4026. if(engine->hasUncaughtException())
  4027. {
  4028. int line = engine->uncaughtExceptionLineNumber();
  4029. qDebug() << "Uncaught excpetion at line " << line << " : " <<
  4030. result.toString();
  4031. QString trace;
  4032. foreach(trace, engine->uncaughtExceptionBacktrace())
  4033. {
  4034. qDebug() << trace;
  4035. }
  4036. }
  4037. @* Creating a window.
  4038. \noindent When a configuration document is loaded, none of the {\tt <window>}
  4039. elements are interpreted or used to create a graphical user interface. Instead,
  4040. any {\tt <program>} elements that are immediate children of the
  4041. {\tt <application>} element are interpreted. In order to convert a
  4042. {\tt <window>} element into a window displayed on screen, the script in the
  4043. {\tt <program>} elements must call a function to display a specified window.
  4044. Report windows can be produced by scripts in a similar, but slightly different
  4045. manner.
  4046. \danger This design works, but it'@q'@>s not particularly good design. It was written
  4047. under severe time constraints and should be redesigned or at least cleaned up
  4048. and reorganized.\endanger
  4049. @<Function prototypes for scripting@>=
  4050. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine);
  4051. QScriptValue createReport(QScriptContext *context, QScriptEngine *engine);
  4052. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  4053. QStack<QLayout*> *layoutStack);
  4054. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4055. QStack<QLayout *> *layoutStack);
  4056. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4057. QStack<QLayout *> *layoutStack);
  4058. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4059. QStack<QLayout *> *layoutStack);
  4060. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4061. QStack<QLayout *> *layoutStack);
  4062. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4063. QStack<QLayout *> *layoutStack);
  4064. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4065. QStack<QLayout *> *layoutStack);
  4066. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4067. QStack<QLayout *> *layoutStack);
  4068. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4069. QStack<QLayout *> *layoutStack);
  4070. void addTemperatureDisplayToSplitter(QDomElement element,@|
  4071. QStack<QWidget *> *widgetStack,
  4072. QStack<QLayout *> *layoutStack);
  4073. void addTemperatureDisplayToLayout(QDomElement element,@|
  4074. QStack<QWidget *> *widgetStack,
  4075. QStack<QLayout *> *layoutStack);
  4076. void addTimerDisplayToSplitter(QDomElement element,@|
  4077. QStack<QWidget *> *widgetStack,
  4078. QStack<QLayout *> *layoutStack);
  4079. void addTimerDisplayToLayout(QDomElement element,@|
  4080. QStack<QWidget *> *widgetStack,
  4081. QStack<QLayout *> *layoutStack);
  4082. void addDecorationToSplitter(QDomElement element,@|
  4083. QStack<QWidget *> *widgetStack,
  4084. QStack<QLayout *> *layoutStack);
  4085. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4086. QStack<QLayout *> *layoutStack);
  4087. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4088. QStack<QLayout *> *layoutStack);
  4089. void addButtonToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4090. QStack<QLayout *> *layoutStack);
  4091. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4092. QStack<QLayout *> *layoutStack);
  4093. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4094. QStack<QLayout *> *layoutStack);
  4095. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4096. QStack<QLayout *> *layoutStack);
  4097. void addSaltToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4098. QStack<QLayout *> *layoutStack);
  4099. void addLineToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4100. QStack<QLayout *> *layoutStack);
  4101. void addTextToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4102. QStack<QLayout *> *layoutStack);
  4103. void addSqlQueryViewToLayout(QDomElement element,
  4104. QStack<QWidget *> *widgetStack,
  4105. QStack<QLayout *> *layoutStack);
  4106. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4107. QStack<QLayout *> *layoutStack);
  4108. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4109. QStack<QLayout *> *layoutStack);
  4110. void addTimeEditToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4111. QStack<QLayout *> *layoutStack);
  4112. @ The functions for creating windows must be made available to the scripting
  4113. engine.
  4114. @<Set up the scripting engine@>=
  4115. engine->globalObject().setProperty("createWindow",
  4116. engine->newFunction(createWindow));
  4117. engine->globalObject().setProperty("createReport",
  4118. engine->newFunction(createReport));
  4119. @ This function must examine the configuration document in search of the
  4120. appropriate window element, parse the contents of that element, and create a
  4121. multitude of objects, all of which must be passed to the scripting engine.
  4122. @<Functions for scripting@>=
  4123. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine)@/
  4124. {
  4125. QString targetID = argument<QString>(0, context);
  4126. QDomNode element;
  4127. QScriptValue object;
  4128. @<Find the window element@>@;
  4129. if(!element.isNull())
  4130. {
  4131. @<Display the window@>@;
  4132. }
  4133. return object;
  4134. }
  4135. @ Report files are not part of the configuration document and must be created
  4136. differently. While there is a special menu type that handles all of this
  4137. without involving the host environment, scripted generation and manipulation of
  4138. report windows requires another function. This function will only work after a
  4139. window with a reports menu has been created.
  4140. @<Functions for scripting@>=
  4141. QScriptValue createReport(QScriptContext *context, QScriptEngine *engine)
  4142. {
  4143. QString targetID = argument<QString>(0, context);
  4144. QFile file(QString("reports:%1").arg(targetID));
  4145. QScriptValue object;
  4146. if(file.open(QIODevice::ReadOnly))
  4147. {
  4148. QDomDocument document;
  4149. document.setContent(&file, true);
  4150. QDomElement element = document.documentElement();
  4151. if(!element.isNull())
  4152. {
  4153. @<Display the window@>@;
  4154. }
  4155. file.close();
  4156. }
  4157. return object;
  4158. }
  4159. @ First we must locate the {\tt <window>} element. The most sensible way to do
  4160. this would require that each {\tt <window>} element has an ID attribute and
  4161. search the DOM tree for that ID. Unfortunately, as of this writing,
  4162. |QDomDocument::elementByID()| always returns a null element, so that won'@q'@>t work.
  4163. Instead, we search the tree for all {\tt <window>} elements and then examine
  4164. the resulting list to find the element with the appropriate ID.
  4165. @<Find the window element@>=
  4166. QDomNodeList windows =
  4167. AppInstance->configuration()->documentElement().elementsByTagName("window");
  4168. QDomNode nullNode;
  4169. int i = 0;
  4170. element = nullNode;
  4171. while(i < windows.count())
  4172. {
  4173. element = windows.at(i);
  4174. QDomNamedNodeMap attributes = element.attributes();
  4175. if(attributes.contains("id"))
  4176. {
  4177. if(attributes.namedItem("id").toAttr().value() == targetID)
  4178. {
  4179. break;
  4180. }
  4181. }
  4182. element = nullNode;
  4183. i++;
  4184. }
  4185. @ In order to display a window, we start by creating a new |ScriptQMainWindow|
  4186. and set the central widget of that window to a new |QWidget|. After this, we see
  4187. if the window element has any children and proceed to populate the window.
  4188. When creating child elements, care must be taken that all objects are descended
  4189. from the window. If an object is descended from the window and has an object
  4190. name, it will be possible for script code to recover the created object.
  4191. As of version 1.4, the window itself is given the value of its {\tt id}
  4192. attribute as an object name to facilitate automatic window geometry management.
  4193. @<Display the window@>=
  4194. ScriptQMainWindow *window = new ScriptQMainWindow;
  4195. window->setObjectName(targetID);
  4196. object = engine->newQObject(window);
  4197. setQMainWindowProperties(object, engine);
  4198. QWidget *central = new(QWidget);
  4199. central->setParent(window);
  4200. central->setObjectName("centralWidget");
  4201. window->setCentralWidget(central);
  4202. if(element.hasChildNodes())
  4203. {
  4204. @<Process window children@>@;
  4205. }
  4206. @<Insert help menu@>@;
  4207. window->show();
  4208. window->setupFinished();
  4209. @ Three element types make sense as top level children of a {\tt <window>}
  4210. element. An element representing a layout element can be used to apply that
  4211. layout to the central widget. An element representing a menu can be used to add
  4212. a menu to the window. A {\tt <program>} element can be used to specify a script
  4213. to be run after the window has been assembled.
  4214. \danger As the window comes with a blank central widget, elements representing
  4215. a widget to be used as the central widget of the window cannot be used directly
  4216. here. If only one widget is needed in the window, there is a need to create a
  4217. layout element and place that widget in the layout. Also note that there is not
  4218. enough error checking in the following code. Provide invalid input at your
  4219. peril.\endanger
  4220. Program fragments pulled from the window description are executed with the
  4221. newly created window available as {\tt this}. When such a fragment is run, the
  4222. entire description of the window will have already been evaluated and any
  4223. necessary objects created. Obtaining a child object of the window can be done
  4224. by calling |findChildObject()|.
  4225. @<Process window children@>=
  4226. QStack<QWidget*> widgetStack;
  4227. QStack<QLayout*> layoutStack;
  4228. QString windowScript;
  4229. widgetStack.push(central);
  4230. QDomNodeList windowChildren = element.childNodes();
  4231. int i = 0;
  4232. while(i < windowChildren.count())
  4233. {
  4234. QDomNode current;
  4235. QDomElement element;
  4236. current = windowChildren.at(i);
  4237. if(current.isElement())
  4238. {
  4239. element = current.toElement();
  4240. if(element.tagName() == "program")
  4241. {
  4242. windowScript.append(element.text());
  4243. }
  4244. else if(element.tagName() == "layout")
  4245. {
  4246. element.setAttribute("trcontext", "configuration");
  4247. addLayoutToWidget(element, &widgetStack, &layoutStack);
  4248. }
  4249. else if(element.tagName() == "menu")
  4250. {
  4251. @<Process menus@>@;
  4252. }
  4253. }
  4254. i++;
  4255. }
  4256. QScriptValue oldThis = context->thisObject();
  4257. context->setThisObject(object);
  4258. QScriptValue result = engine->evaluate(windowScript);
  4259. @<Report scripting errors@>@;
  4260. context->setThisObject(oldThis);
  4261. @ Elements representing menus may provide a number of child elements
  4262. representing the items in that menu. The XML portion of the configuration will
  4263. not provide any information on what these menu items do. The contents of the
  4264. {\tt <program>} element for the window will need to request the |QAction|
  4265. objects and connect a signal from that object to the desired functionality.
  4266. One special consideration is the Reports menu. This menu will populate itself
  4267. according to its own logic and will have a {\tt type} property of
  4268. {\tt "reports"} and a {\tt src} property indicating the directory where reports
  4269. can be found.
  4270. @<Process menus@>=
  4271. QMenuBar *bar = window->menuBar();
  4272. bar->setParent(window);
  4273. bar->setObjectName("menuBar");
  4274. if(element.hasAttribute("name"))
  4275. {
  4276. QMenu *menu = bar->addMenu(QCoreApplication::translate("configuration",
  4277. element.attribute("name").toUtf8().data()));
  4278. menu->setParent(bar);
  4279. if(element.hasAttribute("type"))
  4280. {
  4281. if(element.attribute("type") == "reports")
  4282. {
  4283. if(element.hasAttribute("src"))
  4284. {
  4285. @<Populate reports menu@>@;
  4286. }
  4287. }
  4288. }
  4289. if(element.hasChildNodes())
  4290. {
  4291. @<Process menu items@>@;
  4292. }
  4293. }
  4294. @ To add items to a menu, we check for {\tt <item>} elements under the
  4295. {\tt <menu>} element and create a |QAction| for each item.
  4296. @<Process menu items@>=
  4297. QDomNodeList menuItems = element.childNodes();
  4298. int j = 0;
  4299. while(j < menuItems.count())
  4300. {
  4301. QDomNode item = menuItems.at(j);
  4302. if(item.isElement())
  4303. {
  4304. QDomElement itemElement = item.toElement();
  4305. if(itemElement.tagName() == "item")
  4306. {
  4307. QAction *itemAction = new QAction(QCoreApplication::translate("configuration",
  4308. itemElement.text().toUtf8().data()), menu);
  4309. if(itemElement.hasAttribute("id"))
  4310. {
  4311. itemAction->setObjectName(itemElement.attribute("id"));
  4312. }
  4313. if(itemElement.hasAttribute("shortcut"))
  4314. {
  4315. itemAction->setShortcut(itemElement.attribute("shortcut"));
  4316. }
  4317. menu->addAction(itemAction);
  4318. }
  4319. else if(itemElement.tagName() == "separator")
  4320. {
  4321. menu->addSeparator();
  4322. }
  4323. else if(itemElement.tagName() == "plugins")
  4324. {
  4325. @<Process plugin item@>@;
  4326. }
  4327. }
  4328. j++;
  4329. }
  4330. @i helpmenu.w
  4331. @i licensewindow.w
  4332. @ A layout can contain a number of different elements including a variety of
  4333. widget types and other layouts. This function is responsible for applying any
  4334. layout class to the widget currently being populated and processing children of
  4335. the {\tt <layout>} element to populate that layout. External stacks are used to
  4336. keep track of which widgets and layouts are currently being populated. The
  4337. {\tt type} attribute is used to determine what sort of layout should be created.
  4338. Currently, {\tt horizontal}, {\tt vertical}, {\tt grid}, and {\tt stack} types
  4339. are supported. The first two resolve to |QBoxLayout| layouts, {\tt grid}
  4340. resolves to a |QGridLayout|, and {\tt stack} resolves to a |QStackedLayout|.
  4341. @<Functions for scripting@>=
  4342. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  4343. QStack<QLayout*> *layoutStack)
  4344. {
  4345. if(element.hasAttribute("type"))
  4346. {
  4347. @<Create and populate layout@>@;
  4348. QWidget *widget = widgetStack->top();
  4349. if(layout)
  4350. {
  4351. widget->setLayout(layout);
  4352. }
  4353. layoutStack->pop();
  4354. }
  4355. }
  4356. @ As there are multiple places where a {\tt <layout>} element is parsed with
  4357. slightly different semantics, the code for creating and populating the layout is
  4358. broken out so that code written to support additional layout types only needs to
  4359. be written once.
  4360. @<Create and populate layout@>=
  4361. QLayout *layout;
  4362. QString layoutType = element.attribute("type");
  4363. if(layoutType == "horizontal")
  4364. {
  4365. layout = new QHBoxLayout;
  4366. layoutStack->push(layout);
  4367. populateBoxLayout(element, widgetStack, layoutStack);
  4368. }
  4369. else if(layoutType == "vertical")
  4370. {
  4371. layout = new QVBoxLayout;
  4372. layoutStack->push(layout);
  4373. populateBoxLayout(element, widgetStack, layoutStack);
  4374. }
  4375. else if(layoutType == "grid")
  4376. {
  4377. layout = new QGridLayout;
  4378. layoutStack->push(layout);
  4379. populateGridLayout(element, widgetStack, layoutStack);
  4380. }
  4381. else if(layoutType == "stack")
  4382. {
  4383. layout = new QStackedLayout;
  4384. layoutStack->push(layout);
  4385. populateStackedLayout(element, widgetStack, layoutStack);
  4386. }
  4387. if(element.hasAttribute("id"))
  4388. {
  4389. layout->setObjectName(element.attribute("id"));
  4390. }
  4391. if(element.hasAttribute("spacing"))
  4392. {
  4393. layout->setSpacing(element.attribute("spacing").toInt());
  4394. }
  4395. if(element.hasAttribute("margin"))
  4396. {
  4397. int m = element.attribute("margin").toInt();
  4398. layout->setContentsMargins(m, m, m, m);
  4399. }
  4400. @ Stacked layouts are a bit different from the other types. A stacked layout has
  4401. an arbitrary number of {\tt <page>} children which are just a |QWidget| which
  4402. can have the same child elements as {\tt <widget>} elements elsewhere. Only the
  4403. first page will be visible initially, however it is possible to use script code
  4404. to set the currently visible page provided that an ID is set for the layout.
  4405. @<Functions for scripting@>=
  4406. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4407. QStack<QLayout *> *layoutStack)
  4408. {
  4409. QDomNodeList children = element.childNodes();
  4410. QStackedLayout *layout = qobject_cast<QStackedLayout *>(layoutStack->top());
  4411. for(int i = 0; i < children.count(); i++)
  4412. {
  4413. QDomNode current;
  4414. QDomElement currentElement;
  4415. current = children.at(i);
  4416. if(current.isElement())
  4417. {
  4418. currentElement = current.toElement();
  4419. if(currentElement.tagName() == "page")
  4420. {
  4421. QWidget *widget = new QWidget;
  4422. layout->addWidget(widget);
  4423. widgetStack->push(widget);
  4424. currentElement.setAttribute("trcontext", "configuration");
  4425. populateWidget(currentElement, widgetStack, layoutStack);
  4426. widgetStack->pop();
  4427. }
  4428. }
  4429. }
  4430. }
  4431. @ A common use of stacked layouts is in the creation of tabbed interfaces, but
  4432. there are also many uses in \pn{} where the tabs are not required. Therefore,
  4433. tab bar creation requires a separate XML element.
  4434. @<Additional box layout elements@>=
  4435. else if(currentElement.tagName() == "tabbar")
  4436. {
  4437. addTabBarToLayout(currentElement, widgetStack, layoutStack);
  4438. }
  4439. @ The function used to create this follows the usual pattern.
  4440. @<Functions for scripting@>=
  4441. void addTabBarToLayout(QDomElement element, QStack<QWidget*> *, QStack<QLayout*> *layoutStack)
  4442. {
  4443. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4444. QTabBar *widget = new QTabBar;
  4445. layout->addWidget(widget);
  4446. if(!element.attribute("id").isEmpty())
  4447. {
  4448. widget->setObjectName(element.attribute("id"));
  4449. }
  4450. }
  4451. @ Rather than define the tab set in XML, this is left to the host environment.
  4452. This means that some additional scripting support is required.
  4453. @<Set up the scripting engine@>=
  4454. constructor = engine->newFunction(constructQTabBar);
  4455. value = engine->newQMetaObject(&QTabBar::staticMetaObject, constructor);
  4456. engine->globalObject().setProperty("QTabBar", value);
  4457. @ The constructor is trivial.
  4458. @<Functions for scripting@>=
  4459. QScriptValue constructQTabBar(QScriptContext *, QScriptEngine *engine)
  4460. {
  4461. QScriptValue object = engine->newQObject(new QTabBar);
  4462. setQTabBarProperties(object, engine);
  4463. return object;
  4464. }
  4465. @ There are many functions that I might want to some day add support for, but
  4466. the immediate need is just creating the tabs in the first place.
  4467. @<Functions for scripting@>=
  4468. void setQTabBarProperties(QScriptValue value, QScriptEngine *engine)
  4469. {
  4470. setQWidgetProperties(value, engine);
  4471. value.setProperty("addTab", engine->newFunction(QTabBar_addTab));
  4472. }
  4473. QScriptValue QTabBar_addTab(QScriptContext *context, QScriptEngine *)
  4474. {
  4475. QTabBar *self = getself<QTabBar *>(context);
  4476. if(context->argumentCount() > 0)
  4477. {
  4478. self->addTab(argument<QString>(0, context));
  4479. }
  4480. else
  4481. {
  4482. context->throwError("Incorrect number of arguments passed to "@|
  4483. "QTabBar::addTab().");
  4484. }
  4485. return QScriptValue();
  4486. }
  4487. @ Function prototypes are needed.
  4488. @<Function prototypes for scripting@>=
  4489. QScriptValue constructQTabBar(QScriptContext *context, QScriptEngine *engine);
  4490. void setQTabBarProperties(QScriptValue value, QScriptEngine *engine);
  4491. QScriptValue QTabBar_addTab(QScriptContext *context, QScriptEngine *engine);
  4492. @ Using a grid layout is a bit different from using a box layout. Child elements
  4493. with various attributes are required to take full advantage of this layout type.
  4494. All direct children of a grid layout element should be {\tt <row>} elements
  4495. which may have optional {\tt height} and {\tt stretch} attributes which apply to
  4496. that row.
  4497. @<Functions for scripting@>=
  4498. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4499. QStack<QLayout *> *layoutStack)
  4500. {
  4501. QDomNodeList children = element.childNodes();
  4502. int row = -1;
  4503. QGridLayout *layout = qobject_cast<QGridLayout *>(layoutStack->top());
  4504. for(int i = 0; i < children.count(); i++)
  4505. {
  4506. QDomNode current;
  4507. QDomElement currentElement;
  4508. current = children.at(i);
  4509. if(current.isElement())
  4510. {
  4511. currentElement = current.toElement();
  4512. if(currentElement.tagName() == "row")
  4513. {
  4514. row++;
  4515. if(currentElement.hasAttribute("height"))
  4516. {
  4517. layout->setRowMinimumHeight(row,
  4518. currentElement.attribute("height").toInt());
  4519. }
  4520. if(currentElement.hasAttribute("stretch"))
  4521. {
  4522. layout->setRowStretch(row,
  4523. currentElement.attribute("stretch").toInt());
  4524. }
  4525. @<Populate grid layout row@>@;
  4526. }
  4527. }
  4528. }
  4529. }
  4530. @ Each {\tt <row>} may have arbitrarily many {\tt <column>} children. A row with
  4531. nothing in it or that is entirely populated by spanning cells from previous rows
  4532. might have no children.
  4533. The {\tt <column>} element supports several optional attributes. The
  4534. {\tt column} attribute can be used to specify which column the element refers
  4535. to. Sibling {\tt <column>} elements will refer to columns farther right unless
  4536. a lower column number is specified. This does mean that it is possible to
  4537. specify the same column more than once, however actually doing so is not
  4538. recommended. The {\tt width} attribute specifies the minimum width of the
  4539. column. If multiple cells in a column specify this attribute, the last one takes
  4540. priority. Similarly, the {\tt stretch} attribute specifies the column stretch.
  4541. The {\tt rowspan} and {\tt colspan} attributes can be used for cells that span
  4542. more than one row or column. A value of |-1| can be used to have the cell span
  4543. to the last row or column in the layout.
  4544. Once the attributes of the cell are known, a |QHBoxLayout| is added to the
  4545. layout at the appropriate location in the grid and it is this layout which is
  4546. further populated by child elements. Anything that can be placed under a
  4547. {\tt <layout>} element with {\tt "horizontal"} or {\tt "vertical"} {\tt type}
  4548. attribute can be a child of a {\tt <column>} element in this context.
  4549. @<Populate grid layout row@>=
  4550. int column = -1;
  4551. QDomNodeList rowChildren = currentElement.childNodes();
  4552. for(int j = 0; j < rowChildren.count(); j++)
  4553. {
  4554. QDomNode columnNode;
  4555. QDomElement columnElement;
  4556. columnNode = rowChildren.at(j);
  4557. if(columnNode.isElement())
  4558. {
  4559. columnElement = columnNode.toElement();
  4560. if(columnElement.tagName() == "column")
  4561. {
  4562. column++;
  4563. if(columnElement.hasAttribute("column"))
  4564. {
  4565. column = columnElement.attribute("column").toInt();
  4566. }
  4567. if(columnElement.hasAttribute("width"))
  4568. {
  4569. layout->setColumnMinimumWidth(column,
  4570. columnElement.attribute("width").toInt());
  4571. }
  4572. if(columnElement.hasAttribute("stretch"))
  4573. {
  4574. layout->setColumnStretch(column,
  4575. columnElement.attribute("stretch").toInt());
  4576. }
  4577. int hspan = 1;
  4578. int vspan = 1;
  4579. if(columnElement.hasAttribute("rowspan"))
  4580. {
  4581. vspan = columnElement.attribute("rowspan").toInt();
  4582. }
  4583. if(columnElement.hasAttribute("colspan"))
  4584. {
  4585. hspan = columnElement.attribute("colspan").toInt();
  4586. }
  4587. QHBoxLayout *cell = new QHBoxLayout;
  4588. layout->addLayout(cell, row, column, vspan, hspan);
  4589. layoutStack->push(cell);
  4590. columnElement.setAttribute("trcontext", "configuration");
  4591. populateBoxLayout(columnElement, widgetStack, layoutStack);
  4592. layoutStack->pop();
  4593. }
  4594. }
  4595. }
  4596. @ Box layouts are populated by checking for child elements representing
  4597. supported widget types and layouts and adding these to the current layout.
  4598. @<Functions for scripting@>=
  4599. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4600. QStack<QLayout *> *layoutStack)
  4601. {
  4602. QDomNodeList children = element.childNodes();
  4603. for(int i = 0; i < children.count(); i++)
  4604. {
  4605. QDomNode current;
  4606. QDomElement currentElement;
  4607. current = children.at(i);
  4608. if(current.isElement())
  4609. {
  4610. currentElement = current.toElement();
  4611. currentElement.setAttribute("trcontext", "configuration");
  4612. if(currentElement.tagName() == "button")
  4613. {
  4614. addButtonToLayout(currentElement, widgetStack, layoutStack);
  4615. }
  4616. else if(currentElement.tagName() == "calendar")
  4617. {
  4618. addCalendarToLayout(currentElement, widgetStack, layoutStack);
  4619. }
  4620. else if(currentElement.tagName() == "timeedit")
  4621. {
  4622. addTimeEditToLayout(currentElement, widgetStack, layoutStack);
  4623. }
  4624. else if(currentElement.tagName() == "decoration")
  4625. {
  4626. addDecorationToLayout(currentElement, widgetStack,
  4627. layoutStack);
  4628. }
  4629. else if(currentElement.tagName() == "layout")
  4630. {
  4631. addLayoutToLayout(currentElement, widgetStack, layoutStack);
  4632. }
  4633. else if(currentElement.tagName() == "splitter")
  4634. {
  4635. addSplitterToLayout(currentElement, widgetStack, layoutStack);
  4636. }
  4637. else if(currentElement.tagName() == "label")
  4638. {
  4639. QBoxLayout *layout =
  4640. qobject_cast<QBoxLayout *>(layoutStack->top());
  4641. QLabel *label = new QLabel(QCoreApplication::translate(
  4642. "configuration",
  4643. currentElement.text().toUtf8().data()));
  4644. if(currentElement.hasAttribute("id"))
  4645. {
  4646. label->setObjectName(currentElement.attribute("id"));
  4647. }
  4648. layout->addWidget(label);
  4649. }
  4650. else if(currentElement.tagName() == "lcdtemperature")
  4651. {
  4652. addTemperatureDisplayToLayout(currentElement, widgetStack,
  4653. layoutStack);
  4654. }
  4655. else if(currentElement.tagName() == "lcdtimer")
  4656. {
  4657. addTimerDisplayToLayout(currentElement, widgetStack,
  4658. layoutStack);
  4659. }
  4660. else if(currentElement.tagName() == "line")
  4661. {
  4662. addLineToLayout(currentElement, widgetStack, layoutStack);
  4663. }
  4664. else if(currentElement.tagName() == "report")
  4665. {
  4666. addReportToLayout(currentElement, widgetStack, layoutStack);
  4667. }
  4668. else if(currentElement.tagName() == "sqldrop")
  4669. {
  4670. addSqlDropToLayout(currentElement, widgetStack, layoutStack);
  4671. }
  4672. else if(currentElement.tagName() == "sqltablearray")
  4673. {
  4674. addSaltToLayout(currentElement, widgetStack, layoutStack);
  4675. }
  4676. else if(currentElement.tagName() == "sqlview")
  4677. {
  4678. addSqlQueryViewToLayout(currentElement, widgetStack,
  4679. layoutStack);
  4680. }
  4681. else if(currentElement.tagName() == "textarea")
  4682. {
  4683. addTextToLayout(currentElement, widgetStack, layoutStack);
  4684. }
  4685. else if(currentElement.tagName() == "spinbox")
  4686. {
  4687. addSpinBoxToLayout(currentElement, widgetStack, layoutStack);
  4688. }
  4689. else if(currentElement.tagName() == "formarray")
  4690. {
  4691. addFormArrayToLayout(currentElement, widgetStack, layoutStack);
  4692. }
  4693. else if(currentElement.tagName() =="hscale")
  4694. {
  4695. addScaleControlToLayout(currentElement, widgetStack,
  4696. layoutStack);
  4697. }
  4698. else if(currentElement.tagName() == "vscale")
  4699. {
  4700. addIntensityControlToLayout(currentElement, widgetStack,
  4701. layoutStack);
  4702. }
  4703. else if(currentElement.tagName() == "webview")
  4704. {
  4705. addWebViewToLayout(currentElement, widgetStack, layoutStack);
  4706. }
  4707. else if(currentElement.tagName() == "stretch")
  4708. {
  4709. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4710. layout->addStretch();
  4711. }
  4712. @<Additional box layout elements@>@;
  4713. }
  4714. }
  4715. }
  4716. @ Box layouts support adding additional layouts to the layout. The form of the
  4717. function is very similar to |addLayoutToWidget()|.
  4718. @<Functions for scripting@>=
  4719. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4720. QStack<QLayout *> *layoutStack)
  4721. {
  4722. QLayout *targetLayout = layoutStack->pop();
  4723. QBoxLayout *boxLayout = qobject_cast<QBoxLayout *>(targetLayout);
  4724. if(element.hasAttribute("type"))
  4725. {
  4726. @<Create and populate layout@>@;
  4727. boxLayout->addLayout(layout);
  4728. layoutStack->pop();
  4729. }
  4730. layoutStack->push(targetLayout);
  4731. }
  4732. @ A splitter is similar to a layout in that it manages the size and position of
  4733. one or more widgets, however it is not a layout and therefore needs to be
  4734. handled separately.
  4735. @<Functions for scripting@>=
  4736. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4737. QStack<QLayout *> *layoutStack)
  4738. {
  4739. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4740. QSplitter *splitter = new(QSplitter);
  4741. layout->addWidget(splitter);
  4742. @<Set up splitter@>@;
  4743. }
  4744. @ As there are multiple places where a splitter element must be examined, the
  4745. common code is set aside.
  4746. @<Set up splitter@>=
  4747. QString orientation = element.attribute("type");
  4748. if(orientation == "horizontal")
  4749. {
  4750. splitter->setOrientation(Qt::Horizontal);
  4751. }
  4752. else if(orientation == "vertical")
  4753. {
  4754. splitter->setOrientation(Qt::Vertical);
  4755. }
  4756. QString id = element.attribute("id");
  4757. if(!id.isEmpty())
  4758. {
  4759. splitter->setObjectName(id);
  4760. }
  4761. if(element.hasChildNodes())
  4762. {
  4763. widgetStack->push(splitter);
  4764. populateSplitter(element, widgetStack, layoutStack);
  4765. widgetStack->pop();
  4766. }
  4767. @ When populating a splitter, it is important to note that only widgets can be
  4768. added. If a layout is needed, this can be handled by adding a |QWidget| and
  4769. applying the layout to that widget.
  4770. @<Functions for scripting@>=
  4771. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4772. QStack<QLayout *> *layoutStack)
  4773. {
  4774. QDomNodeList children = element.childNodes();
  4775. for(int i = 0; i < children.count(); i++)
  4776. {
  4777. QDomNode current;
  4778. QDomElement currentElement;
  4779. current = children.at(i);
  4780. if(current.isElement())
  4781. {
  4782. currentElement = current.toElement();
  4783. currentElement.setAttribute("trcontext", "configuration");
  4784. if(currentElement.tagName() == "decoration")
  4785. {
  4786. addDecorationToSplitter(currentElement, widgetStack,
  4787. layoutStack);
  4788. }
  4789. else if(currentElement.tagName() == "graph")
  4790. {
  4791. addGraphToSplitter(currentElement, widgetStack, layoutStack);
  4792. }
  4793. else if(currentElement.tagName() == "splitter")
  4794. {
  4795. addSplitterToSplitter(currentElement, widgetStack, layoutStack);
  4796. }
  4797. else if(currentElement.tagName() == "lcdtemperature")
  4798. {
  4799. addTemperatureDisplayToSplitter(currentElement, widgetStack,
  4800. layoutStack);
  4801. }
  4802. else if(currentElement.tagName() == "lcdtimer")
  4803. {
  4804. addTimerDisplayToSplitter(currentElement, widgetStack,
  4805. layoutStack);
  4806. }
  4807. else if(currentElement.tagName() == "measurementtable")
  4808. {
  4809. addZoomLogToSplitter(currentElement, widgetStack, layoutStack);
  4810. }
  4811. else if(currentElement.tagName() == "widget")
  4812. {
  4813. addWidgetToSplitter(currentElement, widgetStack, layoutStack);
  4814. }
  4815. }
  4816. }
  4817. }
  4818. @ Adding a splitter to a splitter is similar to adding it to a layout.
  4819. @<Functions for scripting@>=
  4820. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4821. QStack<QLayout *> *layoutStack)
  4822. {
  4823. QSplitter *parent = qobject_cast<QSplitter *>(widgetStack->top());
  4824. QSplitter *splitter = new(QSplitter);
  4825. splitter->setParent(parent);
  4826. parent->addWidget(splitter);
  4827. @<Set up splitter@>@;
  4828. }
  4829. @ Temperature displays are useful to have in an application such as this. At
  4830. present, this code only supports the {\tt id} attribute. It may be useful in the
  4831. future to allow other attributes for changing default attributes of the
  4832. indicator rather than needing to pull the object from script code and set
  4833. changes there.
  4834. @<Functions for scripting@>=
  4835. void addTemperatureDisplayToSplitter(QDomElement element,@|
  4836. QStack<QWidget *> *widgetStack,
  4837. QStack<QLayout *> *)
  4838. {
  4839. TemperatureDisplay *display = new(TemperatureDisplay);
  4840. if(element.hasAttribute("id"))
  4841. {
  4842. display->setObjectName(element.attribute("id"));
  4843. }
  4844. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4845. splitter->addWidget(display);
  4846. }
  4847. void addTemperatureDisplayToLayout(QDomElement element,@|
  4848. QStack<QWidget *> *,
  4849. QStack<QLayout *> *layoutStack)
  4850. {
  4851. TemperatureDisplay *display = new(TemperatureDisplay);
  4852. if(element.hasAttribute("id"))
  4853. {
  4854. display->setObjectName(element.attribute("id"));
  4855. }
  4856. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4857. layout->addWidget(display);
  4858. }
  4859. @ Timer displays are similarly useful to have. The default format for a timer
  4860. display is {\tt hh:mm:ss}, but this can be changed through the {\tt format}
  4861. attribute of an {\tt <lcdtimer>} element.
  4862. @<Functions for scripting@>=
  4863. void addTimerDisplayToSplitter(QDomElement element,@|
  4864. QStack<QWidget *> *widgetStack,
  4865. QStack<QLayout *> *)
  4866. {
  4867. TimerDisplay *display = new(TimerDisplay);
  4868. if(element.hasAttribute("id"))
  4869. {
  4870. display->setObjectName(element.attribute("id"));
  4871. }
  4872. if(element.hasAttribute("format"))
  4873. {
  4874. display->setDisplayFormat(element.attribute("format"));
  4875. }
  4876. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4877. splitter->addWidget(display);
  4878. }
  4879. void addTimerDisplayToLayout(QDomElement element,@|
  4880. QStack<QWidget *> *,
  4881. QStack<QLayout *> *layoutStack)
  4882. {
  4883. TimerDisplay *display = new(TimerDisplay);
  4884. if(element.hasAttribute("id"))
  4885. {
  4886. display->setObjectName(element.attribute("id"));
  4887. }
  4888. if(element.hasAttribute("format"))
  4889. {
  4890. display->setDisplayFormat(element.attribute("format"));
  4891. }
  4892. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4893. layout->addWidget(display);
  4894. }
  4895. @ When multiple timer or temperature displays are required, it can be useful to
  4896. provide a label to indicate just what is being measured.
  4897. @<Functions for scripting@>=
  4898. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *,@|
  4899. QStack<QLayout *> *layoutStack)
  4900. {
  4901. @<Set up decoration@>@;
  4902. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4903. layout->addWidget(decoration);
  4904. }
  4905. void addDecorationToSplitter(QDomElement element,
  4906. QStack<QWidget *> *widgetStack,
  4907. QStack<QLayout *> *)
  4908. {
  4909. @<Set up decoration@>@;
  4910. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4911. splitter->addWidget(decoration);
  4912. }
  4913. @ The decoration needs a label text, an orientation, and the widget to be
  4914. labeled.
  4915. @<Set up decoration@>=
  4916. QString labelText =
  4917. QCoreApplication::translate("configuration",
  4918. element.attribute("name").toUtf8().data());
  4919. Qt::Orientations@, orientation = Qt::Horizontal;
  4920. if(element.hasAttribute("type"))
  4921. {
  4922. if(element.attribute("type") == "horizontal")
  4923. {
  4924. orientation = Qt::Horizontal;
  4925. }
  4926. else if(element.attribute("type") == "vertical")
  4927. {
  4928. orientation = Qt::Vertical;
  4929. }
  4930. }
  4931. @<Find widget to decorate@>@;
  4932. WidgetDecorator *decoration = new WidgetDecorator(theWidget, labelText,
  4933. orientation);
  4934. if(element.hasAttribute("id"))
  4935. {
  4936. decoration->setObjectName(element.attribute("id"));
  4937. }
  4938. @ The widget to decorate should be found as a child of the {\tt <decoration>}
  4939. element.
  4940. @<Find widget to decorate@>=
  4941. QWidget *theWidget = NULL;
  4942. QDomNodeList children = element.childNodes();
  4943. for(int i = 0; i < children.count(); i++)
  4944. {
  4945. QDomNode item = children.at(i);
  4946. if(item.isElement())
  4947. {
  4948. QDomElement itemElement = item.toElement();
  4949. if(itemElement.tagName() == "lcdtemperature")
  4950. {
  4951. TemperatureDisplay *display = new TemperatureDisplay;
  4952. if(itemElement.hasAttribute("id"))
  4953. {
  4954. display->setObjectName(itemElement.attribute("id"));
  4955. }
  4956. theWidget = display;
  4957. }
  4958. else if(itemElement.tagName() == "lcdtimer")
  4959. {
  4960. TimerDisplay *display = new TimerDisplay;
  4961. if(itemElement.hasAttribute("id"))
  4962. {
  4963. display->setObjectName(itemElement.attribute("id"));
  4964. }
  4965. if(itemElement.hasAttribute("format"))
  4966. {
  4967. display->setDisplayFormat(itemElement.attribute("format"));
  4968. }
  4969. theWidget = display;
  4970. }
  4971. }
  4972. }
  4973. @ As splitters cannot contain layouts directly, there is a need to allow
  4974. otherwise empty widgets to be included in a splitter for cases where a splitter
  4975. should manage several widgets together as a group. A row of annotation buttons
  4976. is an example of such a layout.
  4977. When splitters are used as a way to hide optional features it sometimes has the
  4978. effect of forcing a window to stay larger than should be required. To fix this,
  4979. it is possible to set the \tt{ignoreSizePolicy} attribute to true. While this
  4980. does solve the window size issue, this technique is inconsistent with generally
  4981. expected behavior and its use should generally be discouraged.
  4982. @<Functions for scripting@>=
  4983. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4984. QStack<QLayout *> *layoutStack)
  4985. {
  4986. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4987. QWidget *widget = new QWidget;
  4988. if(element.hasAttribute("id"))
  4989. {
  4990. widget->setObjectName(element.attribute("id"));
  4991. }
  4992. if(element.hasAttribute("ignoreSizePolicy"))
  4993. {
  4994. if(element.attribute("ignoreSizePolicy") == "true")
  4995. {
  4996. widget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
  4997. }
  4998. }
  4999. splitter->addWidget(widget);
  5000. if(element.hasChildNodes())
  5001. {
  5002. widgetStack->push(widget);
  5003. populateWidget(element, widgetStack, layoutStack);
  5004. widgetStack->pop();
  5005. }
  5006. }
  5007. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  5008. QStack<QLayout *> *layoutStack)
  5009. {
  5010. QDomNodeList children = element.childNodes();
  5011. for(int i = 0; i < children.count(); i++)
  5012. {
  5013. QDomNode current;
  5014. QDomElement currentElement;
  5015. current = children.at(i);
  5016. if(current.isElement())
  5017. {
  5018. currentElement = current.toElement();
  5019. if(currentElement.tagName() == "layout")
  5020. {
  5021. currentElement.setAttribute("trcontext", "configuration");
  5022. addLayoutToWidget(currentElement, widgetStack, layoutStack);
  5023. }
  5024. }
  5025. }
  5026. }
  5027. @ There are two types of buttons that can be added to a layout. There are normal
  5028. push buttons and there are annotation buttons. Other button types may be added
  5029. in the future.
  5030. @<Functions for scripting@>=
  5031. void addButtonToLayout(QDomElement element, QStack<QWidget *> *,@|
  5032. QStack<QLayout *> *layoutStack)
  5033. {
  5034. QAbstractButton *button = NULL;
  5035. QString text =
  5036. QCoreApplication::translate("configuration",
  5037. element.attribute("name").toUtf8().data());
  5038. if(element.hasAttribute("type"))
  5039. {
  5040. QString type = element.attribute("type");
  5041. if(type == "annotation")
  5042. {
  5043. AnnotationButton *abutton = new AnnotationButton(text);
  5044. if(element.hasAttribute("annotation"))
  5045. {
  5046. abutton->setAnnotation(element.attribute("annotation"));
  5047. }
  5048. if(element.hasAttribute("series"))
  5049. {
  5050. abutton->setTemperatureColumn(element.attribute("series").
  5051. toInt());
  5052. }
  5053. if(element.hasAttribute("column"))
  5054. {
  5055. abutton->setAnnotationColumn(element.attribute("column").
  5056. toInt());
  5057. }
  5058. button = abutton;
  5059. }
  5060. else if(type == "check")
  5061. {
  5062. button = new QCheckBox(text);
  5063. }
  5064. else if(type == "push")
  5065. {
  5066. button = new QPushButton(text);
  5067. }
  5068. }
  5069. if(element.hasAttribute("id"))
  5070. {
  5071. button->setObjectName(element.attribute("id"));
  5072. }
  5073. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5074. layout->addWidget(button);
  5075. }
  5076. @ While annotation buttons are useful for many batch notes, a spin box is
  5077. sometimes a better input choice. There are several attributes that can be set on
  5078. a spin box. These include text to be included in the annotation before and after
  5079. the value of the spin box, the temperature and annotation columns, the range of
  5080. values available in the spin box, the precision of allowed values, and the
  5081. amount by which increment and decrement operations change the value.
  5082. @<Functions for scripting@>=
  5083. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *,@|
  5084. QStack<QLayout *> *layoutStack)
  5085. {
  5086. AnnotationSpinBox *box = new AnnotationSpinBox("", "", NULL);
  5087. if(element.hasAttribute("pretext"))
  5088. {
  5089. box->setPretext(QCoreApplication::translate(
  5090. "configuration",
  5091. element.attribute("pretext").toUtf8().data()));
  5092. }
  5093. if(element.hasAttribute("posttext"))
  5094. {
  5095. box->setPosttext(QCoreApplication::translate(
  5096. "configuration",
  5097. element.attribute("posttext").toUtf8().data()));
  5098. }
  5099. if(element.hasAttribute("series"))
  5100. {
  5101. box->setTemperatureColumn(element.attribute("series").toInt());
  5102. }
  5103. if(element.hasAttribute("column"))
  5104. {
  5105. box->setAnnotationColumn(element.attribute("column").toInt());
  5106. }
  5107. if(element.hasAttribute("min"))
  5108. {
  5109. box->setMinimum(element.attribute("min").toDouble());
  5110. }
  5111. if(element.hasAttribute("max"))
  5112. {
  5113. box->setMaximum(element.attribute("max").toDouble());
  5114. }
  5115. if(element.hasAttribute("decimals"))
  5116. {
  5117. box->setDecimals(element.attribute("decimals").toInt());
  5118. }
  5119. if(element.hasAttribute("step"))
  5120. {
  5121. box->setSingleStep(element.attribute("step").toDouble());
  5122. }
  5123. if(element.hasAttribute("id"))
  5124. {
  5125. box->setObjectName(element.attribute("id"));
  5126. }
  5127. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5128. layout->addWidget(box);
  5129. }
  5130. @ Previously, in order to change a |ZoomLog| from the default set of columns,
  5131. script code would need to alter the column set. While this works fine on a Mac,
  5132. this did not work very well under Windows. For the current version, I would like
  5133. to remove the need to deal with table columns from the host environment. The
  5134. first step for this is allowing column descriptions in XML. After this, I'@q'@>d like
  5135. to remove the default column set from the widget code and provide some better
  5136. functionality for dealing with additional data sets.
  5137. When creating the |ZoomLog| here, we check for {\tt <column>} child elements
  5138. which specify the names of the columns.
  5139. @<Functions for scripting@>=
  5140. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  5141. QStack<QLayout *> *)
  5142. {
  5143. ZoomLog *widget = new ZoomLog;
  5144. if(element.hasAttribute("id"))
  5145. {
  5146. widget->setObjectName(element.attribute("id"));
  5147. }
  5148. if(element.hasChildNodes())
  5149. {
  5150. QDomNodeList children = element.childNodes();
  5151. int column = 0;
  5152. for(int i = 0; i < children.count(); i++)
  5153. {
  5154. QDomNode current;
  5155. QDomElement currentElement;
  5156. current = children.at(i);
  5157. if(current.isElement())
  5158. {
  5159. currentElement = current.toElement();
  5160. if(currentElement.tagName() == "column")
  5161. {
  5162. QString text =
  5163. QCoreApplication::translate(
  5164. "configuration",
  5165. currentElement.text().toUtf8().data());
  5166. widget->setHeaderData(column, text);
  5167. column++;
  5168. }
  5169. }
  5170. }
  5171. }
  5172. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  5173. if(splitter)
  5174. {
  5175. splitter->addWidget(widget);
  5176. }
  5177. else
  5178. {
  5179. qDebug() << "Splitter not found at top of widget stack!";
  5180. }
  5181. }
  5182. @ The last of the widgets needed to duplicate the window provided in previous
  5183. versions of \pn{} is the |GraphView|.
  5184. @<Functions for scripting@>=
  5185. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  5186. QStack<QLayout *> *)
  5187. {
  5188. GraphView *view = new GraphView;
  5189. if(element.hasAttribute("id"))
  5190. {
  5191. view->setObjectName(element.attribute("id"));
  5192. }
  5193. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  5194. splitter->addWidget(view);
  5195. }
  5196. @ When interacting with a database, it can be useful to provide a combo box
  5197. populated by the results of a database query. One way to do this is through a
  5198. |SqlComboBox| widget.
  5199. @<Functions for scripting@>=
  5200. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *,@|
  5201. QStack<QLayout *> *layoutStack)
  5202. {
  5203. SqlComboBox *box = new SqlComboBox();
  5204. if(element.hasAttribute("data"))
  5205. {
  5206. box->setDataColumn(element.attribute("data").toInt());
  5207. }
  5208. if(element.hasAttribute("display"))
  5209. {
  5210. box->setDisplayColumn(element.attribute("display").toInt());
  5211. }
  5212. if(element.hasAttribute("showdata"))
  5213. {
  5214. if(element.attribute("showdata") == "true")
  5215. {
  5216. box->showData(true);
  5217. }
  5218. }
  5219. if(element.hasAttribute("editable"))
  5220. {
  5221. if(element.attribute("editable") == "true")
  5222. {
  5223. box->setEditable(true);
  5224. }
  5225. }
  5226. if(element.hasChildNodes())
  5227. {
  5228. QDomNodeList children = element.childNodes();
  5229. for(int i = 0; i < children.count(); i++)
  5230. {
  5231. QDomNode current;
  5232. QDomElement currentElement;
  5233. current = children.at(i);
  5234. if(current.isElement())
  5235. {
  5236. currentElement = current.toElement();
  5237. if(currentElement.tagName() == "null")
  5238. {
  5239. box->addNullOption();
  5240. }
  5241. else if(currentElement.tagName() == "query")
  5242. {
  5243. box->addSqlOptions(currentElement.text());
  5244. }
  5245. }
  5246. }
  5247. }
  5248. if(element.hasAttribute("id"))
  5249. {
  5250. box->setObjectName(element.attribute("id"));
  5251. }
  5252. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5253. layout->addWidget(box);
  5254. }
  5255. @ The next database aware widget that can be useful to have in \pn{} is a
  5256. {\bf S}QL {\bf A}rray {\bf L}iteral {\bf T}able. As might be apparent from the
  5257. name, this is a table view with an associated model and delegates appropriate
  5258. for creating ordered arrays to pass into a database. Each column represents an
  5259. array of values. The most common use of this is in cases where it is important
  5260. to produce multiple arrays of the same size in which each element of one array
  5261. is related to the element in the same position of another array. For example,
  5262. when roasting coffee there are times when some may want to add more than one
  5263. coffee to the roaster at a time. In order to correctly track the green coffee
  5264. inventory and so that the roasting log may have an accurate record of what is
  5265. really happening, insertions on the roasting log provide two arrays, one
  5266. representing all of the coffees being added to the roaster, the other the amount
  5267. of each of these coffees. The database can then use a trigger function to
  5268. examine these arrays and produce the necessary entries in the use table which in
  5269. turn update the record containing the amount of each green coffee currently in
  5270. stock.
  5271. While a generic |QTableView| is used here, there is a need to add functionality
  5272. specific to using this table with a |SaltModel| when obtaining this widget from
  5273. the host environment. In order to accomodate this, we add a dynamic property to
  5274. the view to identify the type of table in the absense of a unique class name.
  5275. @<Functions for scripting@>=
  5276. void addSaltToLayout(QDomElement element, QStack<QWidget *> *,@|
  5277. QStack<QLayout *> *layoutStack)
  5278. {
  5279. QTableView *view = new QTableView;
  5280. view->setProperty("tabletype", QVariant(QString("SaltTable")));
  5281. SaltModel *model = new SaltModel(element.childNodes().count());
  5282. if(element.hasAttribute("id"))
  5283. {
  5284. view->setObjectName(element.attribute("id"));
  5285. }
  5286. if(element.hasChildNodes())
  5287. {
  5288. QDomNodeList children = element.childNodes();
  5289. int currentColumn = 0;
  5290. for(int i = 0; i < children.count(); i++)
  5291. {
  5292. QDomNode current;
  5293. QDomElement currentElement;
  5294. current = children.at(i);
  5295. if(current.isElement())
  5296. {
  5297. currentElement = current.toElement();
  5298. if(currentElement.tagName() == "column")
  5299. {
  5300. if(currentElement.hasAttribute("name"))
  5301. {
  5302. model->setHeaderData(currentColumn,
  5303. Qt::Horizontal,
  5304. QCoreApplication::translate(
  5305. "configuration",
  5306. currentElement.attribute("name").toUtf8().data()));
  5307. }
  5308. if(currentElement.hasAttribute("delegate"))
  5309. {
  5310. @<Set column delegate from XML attribute@>@;
  5311. }
  5312. currentColumn++;
  5313. }
  5314. }
  5315. }
  5316. }
  5317. view->setModel(model);
  5318. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5319. layout->addWidget(view);
  5320. }
  5321. @ It is often desirable to restrict the allowed values in an entry to either a
  5322. set of specific values or to a particular type of value. Delegates can be set
  5323. on a column to enforce such restrictions.
  5324. @<Set column delegate from XML attribute@>=
  5325. if(currentElement.attribute("delegate") == "sql")
  5326. {
  5327. @<Assign column delegate from SQL@>@;
  5328. }
  5329. else if(currentElement.attribute("delegate") == "numeric")
  5330. {
  5331. @<Assign numeric column delegate@>@;
  5332. }
  5333. else if(currentElement.attribute("delegate") == "positivenumeric")
  5334. {
  5335. @<Assign positive numeric column delegate@>@;
  5336. }
  5337. @ When using a |SaltModel|, there are times where the array values being
  5338. inserted are identification numbers representing some record that already exists
  5339. in the database. For example, the id number representing a green coffee in the
  5340. table of items. In such a case, it is beneficial to provide a delegate capable
  5341. of presenting a human readable list of choices.
  5342. @<Assign column delegate from SQL@>=
  5343. SqlComboBoxDelegate *delegate = new SqlComboBoxDelegate;
  5344. SqlComboBox *widget = new SqlComboBox();
  5345. if(currentElement.hasAttribute("nulltext"))
  5346. {
  5347. widget->setNullText(currentElement.attribute("nulltext"));
  5348. }
  5349. if(currentElement.hasAttribute("nulldata"))
  5350. {
  5351. widget->setNullData(QVariant(currentElement.attribute("nulldata")));
  5352. }
  5353. if(currentElement.hasAttribute("null"))
  5354. {
  5355. if(currentElement.attribute("null") == "true")
  5356. {
  5357. widget->addNullOption();
  5358. }
  5359. }
  5360. if(currentElement.hasAttribute("showdata"))
  5361. {
  5362. if(currentElement.attribute("showdata") == "true")
  5363. {
  5364. widget->showData(true);
  5365. }
  5366. }
  5367. if(currentElement.hasAttribute("data"))
  5368. {
  5369. widget->setDataColumn(currentElement.attribute("data").toInt());
  5370. }
  5371. if(currentElement.hasAttribute("display"))
  5372. {
  5373. widget->setDisplayColumn(currentElement.attribute("display").toInt());
  5374. }
  5375. widget->addSqlOptions(currentElement.text());
  5376. delegate->setWidget(widget);
  5377. view->setItemDelegateForColumn(currentColumn, delegate);
  5378. @ Another common use is allowing numeric values.
  5379. @<Assign numeric column delegate@>=
  5380. NumericDelegate *delegate = new NumericDelegate;
  5381. view->setItemDelegateForColumn(currentColumn, delegate);
  5382. @ It is also possible to restrict allowed numeric values to non-negative
  5383. values.
  5384. @<Assign positive numeric column delegate@>=
  5385. NumericDelegate *delegate = new NumericDelegate(true);
  5386. view->setItemDelegateForColumn(currentColumn, delegate);
  5387. @ The |NumericDelegate| will only set the display value to a number, but it
  5388. will perform mathematical calculations that are entered into the editor as
  5389. well. This allows a person to type something like $13.26+5.06$ with the result
  5390. of the expression ($18.32$) appearing in the table.
  5391. @<Class declarations@>=
  5392. class NumericDelegate : public QItemDelegate@/
  5393. {
  5394. @[Q_OBJECT@]@;
  5395. public:@/
  5396. NumericDelegate(bool positiveOnly = false, QObject *parent = NULL);
  5397. QWidget *createEditor(QWidget *parent,
  5398. const QStyleOptionViewItem &option,@|
  5399. const QModelIndex &index) const;
  5400. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  5401. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  5402. const QModelIndex &index) const;
  5403. void updateEditorGeometry(QWidget *editor,
  5404. const QStyleOptionViewItem &option,@|
  5405. const QModelIndex &index) const;
  5406. private:
  5407. bool m_positiveOnly;
  5408. };
  5409. @ There is nothing special about the constructor.
  5410. @<NumericDelegate implementation@>=
  5411. NumericDelegate::NumericDelegate(bool positiveOnly, QObject *parent) :
  5412. QItemDelegate(parent), m_positiveOnly(positiveOnly)
  5413. {
  5414. /* Nothing needs to be done here. */
  5415. }
  5416. @ Two roles are used by this delegate. The edit role should contain whatever
  5417. text has been entered in the editor while the display role contain the numeric
  5418. result of any expression that has been entered. Our editor only requires the
  5419. first of these.
  5420. @<NumericDelegate implementation@>=
  5421. void NumericDelegate::setEditorData(QWidget *editor,
  5422. const QModelIndex &index) const
  5423. {
  5424. QString value = index.model()->data(index, Qt::EditRole).toString();
  5425. QLineEdit *line = static_cast<QLineEdit*>(editor);
  5426. line->setText(value);
  5427. }
  5428. @ When editing is finished, the expression text must be saved back to the
  5429. model and the expression should be evaluated to set the display role. We make
  5430. use of the existing scripting engine to evaluate the expression, but only
  5431. preserve the result in the display role if the result of that expression is
  5432. numeric.
  5433. @<NumericDelegate implementation@>=
  5434. void NumericDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
  5435. const QModelIndex &index) const
  5436. {
  5437. QLineEdit *line = static_cast<QLineEdit*>(editor);
  5438. model->setData(index, line->text(), Qt::EditRole);
  5439. QScriptEngine *engine = AppInstance->engine;
  5440. engine->pushContext();
  5441. QString script = QString("Number(%1)").arg(line->text());
  5442. QScriptValue result = engine->evaluate(line->text());
  5443. if(result.isNumber())
  5444. {
  5445. if(m_positiveOnly)
  5446. {
  5447. if(result.toNumber() < 0)
  5448. {
  5449. model->setData(index, QVariant(), Qt::DisplayRole);
  5450. }
  5451. else
  5452. {
  5453. model->setData(index, result.toVariant(), Qt::DisplayRole);
  5454. }
  5455. }
  5456. else
  5457. {
  5458. model->setData(index, result.toVariant(), Qt::DisplayRole);
  5459. }
  5460. }
  5461. else
  5462. {
  5463. model->setData(index, QVariant(), Qt::DisplayRole);
  5464. }
  5465. engine->popContext();
  5466. }
  5467. @ There is nothing special about the line edit used for this.
  5468. @<NumericDelegate implementation@>=
  5469. QWidget* NumericDelegate::createEditor(QWidget *parent,
  5470. const QStyleOptionViewItem &,
  5471. const QModelIndex &) const
  5472. {
  5473. return (new QLineEdit(parent));
  5474. }
  5475. @ To ensure that the editor is displayed appropriately, we must pass the
  5476. geometry data to our editor.
  5477. @<NumericDelegate implementation@>=
  5478. void NumericDelegate::updateEditorGeometry(QWidget *editor,
  5479. const QStyleOptionViewItem &option,
  5480. const QModelIndex &) const
  5481. {
  5482. editor->setGeometry(option.rect);
  5483. }
  5484. @ The same general technique is useful for input to a |QLineEdit|, but there is
  5485. no model backing that widget to preserve multiple data roles. One way to get
  5486. this functionality without too much effort is to abuse |QValidator| to evaluate
  5487. expressions.
  5488. @<Class declarations@>=
  5489. class ScriptValidator : public QValidator
  5490. {
  5491. Q_OBJECT
  5492. public:
  5493. ScriptValidator(QValidator *validator, QObject *parent = NULL);
  5494. void fixup(QString &input) const;
  5495. QValidator::State validate(QString &input, int &pos) const;
  5496. private:
  5497. QValidator *v;
  5498. };
  5499. @ The key to this is in the |fixup()| method. Here we over-write input with the
  5500. result of the script evaluation.
  5501. @<ScriptValidator implementation@>=
  5502. void ScriptValidator::fixup(QString &input) const
  5503. {
  5504. QScriptEngine *engine = AppInstance->engine;
  5505. engine->pushContext();
  5506. input = engine->evaluate(input).toString();
  5507. engine->popContext();
  5508. }
  5509. @ This validator is intended to be used in conjunction with another one which
  5510. determines if the result of the expression is acceptable. In this case
  5511. |Invalid| is never returned.
  5512. @<ScriptValidator implementation@>=
  5513. QValidator::State ScriptValidator::validate(QString &input, int &pos) const
  5514. {
  5515. if(v)
  5516. {
  5517. if(v->validate(input, pos) == QValidator::Acceptable)
  5518. {
  5519. return QValidator::Acceptable;
  5520. }
  5521. }
  5522. return QValidator::Intermediate;
  5523. }
  5524. @ The constructor is trivial.
  5525. @<ScriptValidator implementation@>=
  5526. ScriptValidator::ScriptValidator(QValidator *validator, QObject *parent)
  5527. : QValidator(parent), v(validator)
  5528. {
  5529. /* Nothing needs to be done here. */
  5530. }
  5531. @ This is included in typica.cpp.
  5532. @<Class implementations@>=
  5533. @<ScriptValidator implementation@>
  5534. @ Line edits are useful when the user is expected to enter text without a
  5535. predetermined set of values.
  5536. Several attributes are supported on line edits. In addition to the usual
  5537. {\tt id} attribute, there is also a {\tt writable} attribute which, if
  5538. {\tt false}, can be used to create read only text areas which can only be edited
  5539. from script code. A {\tt validator} attribute allows entered text to be
  5540. restricted. This can take one of three values. If the value is {\tt "numeric"},
  5541. input is restricted to numeric values. If the value is {\tt "integer"}, input is
  5542. restricted to integer values. Finally, if the value is {\tt "expression"}, input
  5543. is restricted to text which matches a regular expression specified as the value
  5544. of the {\tt expression} attribute.
  5545. Note that when integer and numeric validators are specified, these are set for
  5546. a |ScriptValidator| to enable some basic expression evaluation.
  5547. @<Functions for scripting@>=
  5548. void addLineToLayout(QDomElement element, QStack<QWidget *> *,@|
  5549. QStack<QLayout *> *layoutStack)
  5550. {
  5551. QLineEdit *widget = new QLineEdit(element.text());
  5552. if(element.hasAttribute("id"))
  5553. {
  5554. widget->setObjectName(element.attribute("id"));
  5555. }
  5556. if(element.hasAttribute("writable"))
  5557. {
  5558. if(element.attribute("writable") == "false")
  5559. {
  5560. widget->setReadOnly(true);
  5561. }
  5562. }
  5563. if(element.hasAttribute("validator"))
  5564. {
  5565. if(element.attribute("validator") == "numeric")
  5566. {
  5567. widget->setValidator(new ScriptValidator(new QDoubleValidator));
  5568. }
  5569. else if(element.attribute("validator") == "integer")
  5570. {
  5571. widget->setValidator(new ScriptValidator(new QIntValidator));
  5572. }
  5573. else if(element.attribute("validator") == "expression" &&
  5574. element.hasAttribute("expression"))
  5575. {
  5576. widget->setValidator(new QRegExpValidator(
  5577. QRegExp(element.attribute("expression")),
  5578. NULL));
  5579. }
  5580. }
  5581. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5582. layout->addWidget(widget);
  5583. }
  5584. @ It is natural for certain database fields to enter potentially large amounts
  5585. of free form text, for example, notes and annotations.
  5586. @<Functions for scripting@>=
  5587. void addTextToLayout(QDomElement element, QStack<QWidget *> *,@|
  5588. QStack<QLayout *> *layoutStack)
  5589. {
  5590. QTextEdit *widget = new QTextEdit;
  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. @ The common use of |SqlQueryView| calls for the possibility of changing the
  5599. query during use. As such, there is little reason to accept attributes other
  5600. than an id for obtaining the view in a script.
  5601. @<Functions for scripting@>=
  5602. void addSqlQueryViewToLayout(QDomElement element,
  5603. QStack<QWidget *> *,@|
  5604. QStack<QLayout *> *layoutStack)
  5605. {
  5606. SqlQueryView *view = new SqlQueryView;
  5607. if(element.hasAttribute("id"))
  5608. {
  5609. view->setObjectName(element.attribute("id"));
  5610. }
  5611. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5612. layout->addWidget(view);
  5613. }
  5614. @ When the user is expected to enter a date, it is appropriate to use a date
  5615. editor. This one provides a calendar.
  5616. @<Functions for scripting@>=
  5617. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *,@|
  5618. QStack<QLayout *> *layoutStack)
  5619. {
  5620. QWidget *widget;
  5621. if(element.hasAttribute("time"))
  5622. {
  5623. if(element.attribute("time") == "true")
  5624. {
  5625. QDateTimeEdit *edit = new QDateTimeEdit;
  5626. edit->setDateTime(QDateTime::currentDateTime());
  5627. edit->setCalendarPopup(true);
  5628. edit->setDisplayFormat("yyyy-MM-dd hh:mm:ss");
  5629. widget = qobject_cast<QWidget *>(edit);
  5630. }
  5631. else
  5632. {
  5633. QDateEdit *edit = new QDateEdit;
  5634. edit->setDate(QDate::currentDate());
  5635. edit->setCalendarPopup(true);
  5636. edit->setDisplayFormat("yyyy-MM-dd");
  5637. widget = qobject_cast<QWidget *>(edit);
  5638. }
  5639. }
  5640. else
  5641. {
  5642. QDateEdit *edit = new QDateEdit;
  5643. edit->setDate(QDate::currentDate());
  5644. edit->setCalendarPopup(true);
  5645. edit->setDisplayFormat("yyyy-MM-dd");
  5646. widget = qobject_cast<QWidget *>(edit);
  5647. }
  5648. if(element.hasAttribute("id"))
  5649. {
  5650. widget->setObjectName(element.attribute("id"));
  5651. }
  5652. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5653. layout->addWidget(widget);
  5654. }
  5655. @ Some additional properties are added to this object when it is retrieved by
  5656. the host environment.
  5657. @<Functions for scripting@>=
  5658. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine)
  5659. {
  5660. setQDateTimeEditProperties(value, engine);
  5661. }
  5662. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine)
  5663. {
  5664. setQAbstractSpinBoxProperties(value, engine);
  5665. value.setProperty("setDate", engine->newFunction(QDateTimeEdit_setDate));
  5666. value.setProperty("day", engine->newFunction(QDateTimeEdit_day));
  5667. value.setProperty("month", engine->newFunction(QDateTimeEdit_month));
  5668. value.setProperty("year", engine->newFunction(QDateTimeEdit_year));
  5669. value.setProperty("setToCurrentTime",
  5670. engine->newFunction(QDateTimeEdit_setToCurrentTime));
  5671. }
  5672. @ Certain operations on a |QDateEdit| are easier with a few convenience
  5673. properties that bypass the need to use the built in |date| property. For
  5674. example, an editor that should be set to 1 January of the current year can
  5675. obtain the year and set the date without directly using a |QDate| object.
  5676. @<Functions for scripting@>=
  5677. QScriptValue QDateTimeEdit_setDate(QScriptContext *context, QScriptEngine *)
  5678. {
  5679. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5680. if(context->argumentCount() == 3)
  5681. {
  5682. self->setDate(QDate(argument<int>(0, context),
  5683. argument<int>(1, context),
  5684. argument<int>(2, context)));
  5685. }
  5686. else
  5687. {
  5688. context->throwError("Incorrect number of arguments passed to "
  5689. "QDateTimeEdit::setDate(). This method takes three integer arguments "
  5690. "specifying the year, month, and day.");
  5691. }
  5692. return QScriptValue();
  5693. }
  5694. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *)
  5695. {
  5696. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5697. return QScriptValue(self->date().day());
  5698. }
  5699. QScriptValue QDateTimeEdit_month(QScriptContext *context, QScriptEngine *)
  5700. {
  5701. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5702. return QScriptValue(self->date().month());
  5703. }
  5704. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *)
  5705. {
  5706. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5707. return QScriptValue(self->date().year());
  5708. }
  5709. QScriptValue QDateTimeEdit_setToCurrentTime(QScriptContext *context, QScriptEngine *)
  5710. {
  5711. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5712. self->setDateTime(QDateTime::currentDateTime());
  5713. return QScriptValue();
  5714. }
  5715. @ A few function prototypes are needed for this.
  5716. @<Function prototypes for scripting@>=
  5717. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine);
  5718. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine);
  5719. QScriptValue QDateTimeEdit_setDate(QScriptContext *context,
  5720. QScriptEngine *engine);
  5721. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *engine);
  5722. QScriptValue QDateTimeEdit_month(QScriptContext *context,
  5723. QScriptEngine *engine);
  5724. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *engine);
  5725. QScriptValue QDateTimeEdit_setToCurrentTime(QScriptContext *context, QScriptEngine *engine);
  5726. @ Sometimes it can be useful to allow editing a time or duration value without
  5727. a date field. For this, a |QTimeEdit| can be used.
  5728. @<Functions for scripting@>=
  5729. void addTimeEditToLayout(QDomElement element, QStack<QWidget *> *,@|
  5730. QStack<QLayout *> *layoutStack)
  5731. {
  5732. QTimeEdit *edit = new QTimeEdit;
  5733. if(element.hasAttribute("displayFormat"))
  5734. {
  5735. edit->setDisplayFormat(element.attribute("displayFormat"));
  5736. }
  5737. else
  5738. {
  5739. edit->setDisplayFormat("mm:ss.zzz");
  5740. }
  5741. if(element.hasAttribute("id"))
  5742. {
  5743. edit->setObjectName(element.attribute("id"));
  5744. }
  5745. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5746. layout->addWidget(edit);
  5747. }
  5748. @ Additional properties are added as a |QTimeEdit| is a |QDateTimeEdit|.
  5749. @<Functions for scripting@>=
  5750. void setQTimeEditProperties(QScriptValue value, QScriptEngine *engine)
  5751. {
  5752. setQDateTimeEditProperties(value, engine);
  5753. }
  5754. @ A function prototype is needed.
  5755. @<Function prototypes for scripting@>=
  5756. void setQTimeEditProperties(QScriptValue value, QScriptEngine *engine);
  5757. @ In order to get to objects created from the XML description, it is necessary
  5758. to provide a function that can be called to retrieve children of a given widget.
  5759. When providing such an object to the script, it is necessary to determine the
  5760. type of that object and add the appropriate properties.
  5761. @<Function prototypes for scripting@>=
  5762. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine);
  5763. @ This function must be made available to the scripting engine.
  5764. @<Set up the scripting engine@>=
  5765. engine->globalObject().setProperty("findChildObject",
  5766. engine->newFunction(findChildObject));
  5767. @ This function takes a script value representing some object which may have
  5768. been created from an XML description and a string containing the name of the
  5769. requested child element.
  5770. @<Functions for scripting@>=
  5771. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine)
  5772. {
  5773. QObject *parent = argument<QObject *>(0, context);
  5774. QString name = argument<QString>(1, context);
  5775. QObject *object = parent->findChild<QObject *>(name);
  5776. QScriptValue value;
  5777. if(object)
  5778. {
  5779. value = engine->newQObject(object);
  5780. QString className = object->metaObject()->className();
  5781. @<Set object properties based on class name@>@;
  5782. }
  5783. return value;
  5784. }
  5785. @ Properties are added for a large number of class types.
  5786. @<Set object properties based on class name@>=
  5787. if(className == "TemperatureDisplay")
  5788. {
  5789. setTemperatureDisplayProperties(value, engine);
  5790. }
  5791. else if(className == "TimerDisplay")
  5792. {
  5793. setTimerDisplayProperties(value, engine);
  5794. }
  5795. else if(className == "QAction")
  5796. {
  5797. setQActionProperties(value, engine);
  5798. }
  5799. else if(className == "QBoxLayout")
  5800. {
  5801. setQBoxLayoutProperties(value, engine);
  5802. }
  5803. else if(className == "QDateEdit")
  5804. {
  5805. setQDateEditProperties(value, engine);
  5806. }
  5807. else if(className == "QDateTimeEdit")
  5808. {
  5809. setQDateTimeEditProperties(value, engine);
  5810. }
  5811. else if(className == "QFrame")
  5812. {
  5813. setQFrameProperties(value, engine);
  5814. }
  5815. else if(className == "QHBoxLayout")
  5816. {
  5817. setQBoxLayoutProperties(value, engine);
  5818. }
  5819. else if(className == "QLCDNumber")
  5820. {
  5821. setQLCDNumberProperties(value, engine);
  5822. }
  5823. else if(className == "QMenu")
  5824. {
  5825. setQMenuProperties(value, engine);
  5826. }
  5827. else if(className == "QMenuBar")
  5828. {
  5829. setQMenuBarProperties(value, engine);
  5830. }
  5831. else if(className == "QPushButton")
  5832. {
  5833. setQPushButtonProperties(value, engine);
  5834. }
  5835. else if(className == "QSplitter")
  5836. {
  5837. setQSplitterProperties(value, engine);
  5838. }
  5839. else if(className == "QTableView")
  5840. {
  5841. if(object->property("tabletype").isValid())
  5842. {
  5843. if(object->property("tabletype").toString() == "SaltTable")
  5844. {
  5845. setSaltTableProperties(value, engine);
  5846. }
  5847. }
  5848. }
  5849. else if(className == "QVBoxLayout")
  5850. {
  5851. setQBoxLayoutProperties(value, engine);
  5852. }
  5853. else if(className == "QWidget")
  5854. {
  5855. setQWidgetProperties(value, engine);
  5856. }
  5857. else if(className == "ScriptQMainWindow")
  5858. {
  5859. setQMainWindowProperties(value, engine);
  5860. }
  5861. else if(className == "SqlComboBox")
  5862. {
  5863. setSqlComboBoxProperties(value, engine);
  5864. }
  5865. else if(className == "SqlQueryView")
  5866. {
  5867. setSqlQueryViewProperties(value, engine);
  5868. }
  5869. else if(className == "ZoomLog")
  5870. {
  5871. setZoomLogProperties(value, engine);
  5872. }
  5873. else if(className == "QTextEdit")
  5874. {
  5875. setQTextEditProperties(value, engine);
  5876. }
  5877. else if(className == "QWebView")
  5878. {
  5879. setQWebViewProperties(value, engine);
  5880. }
  5881. else if(className == "QLineEdit")
  5882. {
  5883. setQLineEditProperties(value, engine);
  5884. }
  5885. else if(className == "QSvgWidget")
  5886. {
  5887. setQSvgWidgetProperties(value, engine);
  5888. }
  5889. else if(className == "QTabBar")
  5890. {
  5891. setQTabBarProperties(value, engine);
  5892. }
  5893. else if(className == "PrinterSelector")
  5894. {
  5895. setQComboBoxProperties(value, engine);
  5896. }
  5897. @ In the list of classes, the SaltTable entry is for a class which does not
  5898. strictly exist on its own. It is, however, useful to provide some custom
  5899. properties when passing such an object to the host environment.
  5900. @<Function prototypes for scripting@>=
  5901. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine);
  5902. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  5903. QScriptEngine *engine);
  5904. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  5905. QScriptEngine *engine);
  5906. QScriptValue SaltTable_columnSum(QScriptContext *context,
  5907. QScriptEngine *engine);
  5908. QScriptValue SaltTable_columnArray(QScriptContext *context,
  5909. QScriptEngine *engine);
  5910. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine);
  5911. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine);
  5912. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  5913. QScriptEngine *engine);
  5914. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *engine);
  5915. QScriptValue SaltTable_clear(QScriptContext *context, QScriptEngine *engine);
  5916. QScriptValue SaltTable_removeRow(QScriptContext *context, QScriptEngine *engine);
  5917. QScriptValue SaltTable_findData(QScriptContext *context, QScriptEngine *engine);
  5918. @ There are times when it is useful to obtain the sum of values in a column of
  5919. a SaltTable object. For example, when a column represents the weight of the
  5920. green coffee used in a batch, a sum of that column provides the total weight of
  5921. the batch which, when presented to the user, can be used to catch errors in
  5922. measuring batches or entering data.
  5923. @<Functions for scripting@>=
  5924. QScriptValue SaltTable_columnSum(QScriptContext *context, QScriptEngine *engine)
  5925. {
  5926. QTableView *self = getself<QTableView *>(context);
  5927. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5928. QString datum;
  5929. double total = 0.0;
  5930. int column = argument<int>(0, context);
  5931. int role = argument<int>(1, context);
  5932. for(int i = 0; i < model->rowCount(); i++)
  5933. {
  5934. datum = model->data(model->index(i, column), role).toString();
  5935. if(!datum.isEmpty())
  5936. {
  5937. total += datum.toDouble();
  5938. }
  5939. }
  5940. return QScriptValue(engine, total);
  5941. }
  5942. @ Another common use of the SaltTable is producing the text for an array literal
  5943. to pass into a SQL query. The |SaltModel| used by this table makes this simple.
  5944. There are four functions for this functionality for different use cases.
  5945. @<Functions for scripting@>=
  5946. QScriptValue SaltTable_columnArray(QScriptContext *context,
  5947. QScriptEngine *engine)
  5948. {
  5949. QTableView *self = getself<QTableView *>(context);
  5950. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5951. int column = argument<int>(0, context);
  5952. int role = argument<int>(1, context);
  5953. QString literal = model->arrayLiteral(column, role);
  5954. return QScriptValue(engine, literal);
  5955. }
  5956. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  5957. QScriptEngine *engine)
  5958. {
  5959. QTableView *self = getself<QTableView *>(context);
  5960. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5961. int column = argument<int>(0, context);
  5962. int role = argument<int>(1, context);
  5963. QString literal = model->quotedArrayLiteral(column, role);
  5964. return QScriptValue(engine, literal);
  5965. }
  5966. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  5967. QScriptEngine *engine)
  5968. {
  5969. QTableView *self = getself<QTableView *>(context);
  5970. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5971. int column = argument<int>(0, context);
  5972. int role = argument<int>(1, context);
  5973. QString literal = model->arrayLiteral(column, role);
  5974. literal.chop(1);
  5975. literal = literal.remove(0, 1);
  5976. return QScriptValue(engine, literal);
  5977. }
  5978. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  5979. QScriptEngine *engine)
  5980. {
  5981. QTableView *self = getself<QTableView *>(context);
  5982. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5983. int column = argument<int>(0, context);
  5984. int role = argument<int>(1, context);
  5985. QString literal = model->quotedArrayLiteral(column, role);
  5986. literal.chop(1);
  5987. literal = literal.remove(0, 1);
  5988. return QScriptValue(engine, literal);
  5989. }
  5990. @ In order to obtain signals related to changes in the model, we need a way to
  5991. get to the model from the host environment.
  5992. @<Functions for scripting@>=
  5993. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine)
  5994. {
  5995. QTableView *self = getself<QTableView *>(context);
  5996. QScriptValue value = engine->newQObject(self->model());
  5997. return value;
  5998. }
  5999. @ While this table was originally intended strictly for user input, there are a
  6000. few use cases in which it is useful to allow scripts to set the values in the
  6001. table. This can be done with |setData|. This method takes four arguments: the
  6002. row and column of the table being set, the value to set, and the role of the
  6003. data being set.
  6004. @<Functions for scripting@>=
  6005. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *)
  6006. {
  6007. QTableView *self = getself<QTableView *>(context);
  6008. int row = argument<int>(0, context);
  6009. int column = argument<int>(1, context);
  6010. QVariant value = argument<QVariant>(2, context);
  6011. int role = argument<int>(3, context);
  6012. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  6013. QModelIndex cell = model->index(row, column);
  6014. model->setData(cell, value, role);
  6015. self->update(cell);
  6016. return QScriptValue();
  6017. }
  6018. @ It is sometimes useful to obtain the data from a single cell of the table.
  6019. This can be done with the |data()| property.
  6020. @<Functions for scripting@>=
  6021. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine)
  6022. {
  6023. QTableView *self = getself<QTableView *>(context);
  6024. int row = argument<int>(0, context);
  6025. int column = argument<int>(1, context);
  6026. int role = argument<int>(2, context);
  6027. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  6028. QModelIndex cell = model->index(row, column);
  6029. QVariant value = model->data(cell, role);
  6030. QScriptValue retval = engine->newVariant(value);
  6031. retval.setProperty("value", QScriptValue(value.toString()));
  6032. return retval;
  6033. }
  6034. @ There are times when it is useful to clear the content of a table. This is
  6035. used, for example, in the green coffees table after changing the roasted coffee
  6036. item to eliminate excess rows in the case where the previously selected item
  6037. was a pre-roast blend.
  6038. @<Functions for scripting@>=
  6039. QScriptValue SaltTable_clear(QScriptContext *context, QScriptEngine *)
  6040. {
  6041. QTableView *self = getself<QTableView *>(context);
  6042. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  6043. model->clear();
  6044. return QScriptValue();
  6045. }
  6046. @ It is sometimes useful to remove a row from a table. This is done in the new
  6047. batch window when the coffee for a row is set to a NULL item.
  6048. @<Functions for scripting@>=
  6049. QScriptValue SaltTable_removeRow(QScriptContext *context, QScriptEngine *engine)
  6050. {
  6051. QTableView *self = getself<QTableView *>(context);
  6052. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  6053. int row = argument<int>(0, context);
  6054. return engine->newVariant(model->removeRow(row));
  6055. }
  6056. @ To remove the correct row, it is sometimes useful to query the table for
  6057. special values. This is done with the |findData()| method on the underlying
  6058. model.
  6059. @<Functions for scripting@>=
  6060. QScriptValue SaltTable_findData(QScriptContext *context, QScriptEngine *engine)
  6061. {
  6062. QTableView *self = getself<QTableView *>(context);
  6063. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  6064. QVariant value = argument<QVariant>(0, context);
  6065. int column = argument<int>(1, context);
  6066. return engine->newVariant(model->findData(value, column));
  6067. }
  6068. @ These functions need to be added as properties of the table when it is passed
  6069. to the host environment.
  6070. @<Functions for scripting@>=
  6071. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine)
  6072. {
  6073. setQWidgetProperties(value, engine);
  6074. value.setProperty("columnArray",
  6075. engine->newFunction(SaltTable_columnArray));
  6076. value.setProperty("quotedColumnArray",
  6077. engine->newFunction(SaltTable_quotedColumnArray));
  6078. value.setProperty("bindableColumnArray",
  6079. engine->newFunction(SaltTable_bindableColumnArray));
  6080. value.setProperty("bindableQuotedColumnArray",
  6081. engine->newFunction(SaltTable_bindableQuotedColumnArray));
  6082. value.setProperty("columnSum", engine->newFunction(SaltTable_columnSum));
  6083. value.setProperty("data", engine->newFunction(SaltTable_data));
  6084. value.setProperty("model", engine->newFunction(SaltTable_model));
  6085. value.setProperty("setData", engine->newFunction(SaltTable_setData));
  6086. value.setProperty("clear", engine->newFunction(SaltTable_clear));
  6087. value.setProperty("removeRow", engine->newFunction(SaltTable_removeRow));
  6088. value.setProperty("findData", engine->newFunction(SaltTable_findData));
  6089. }
  6090. @ The |SqlComboBox| is another class that is not constructed from scripts but is
  6091. useful to access from them. A property is added to obtain the current user data
  6092. from the widget.
  6093. @<Function prototypes for scripting@>=
  6094. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  6095. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  6096. QScriptValue QComboBox_currentData(QScriptContext *context,
  6097. QScriptEngine *engine);
  6098. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *engine);
  6099. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *engine);
  6100. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine);
  6101. QScriptValue QComboBox_findData(QScriptContext *context, QScriptEngine *engine);
  6102. @ These functions should seem familiar by now.
  6103. @<Functions for scripting@>=
  6104. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  6105. {
  6106. setQComboBoxProperties(value, engine);
  6107. }
  6108. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  6109. {
  6110. setQWidgetProperties(value, engine);
  6111. value.setProperty("currentData",
  6112. engine->newFunction(QComboBox_currentData));
  6113. value.setProperty("addItem", engine->newFunction(QComboBox_addItem));
  6114. value.setProperty("setModel", engine->newFunction(QComboBox_setModel));
  6115. value.setProperty("findText", engine->newFunction(QComboBox_findText));
  6116. value.setProperty("findData", engine->newFunction(QComboBox_findData));
  6117. }
  6118. QScriptValue QComboBox_currentData(QScriptContext *context,
  6119. QScriptEngine *engine)
  6120. {
  6121. QComboBox *self = getself<QComboBox *>(context);
  6122. return QScriptValue(engine,
  6123. self->itemData(self->currentIndex()).toString());
  6124. }
  6125. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *)
  6126. {
  6127. QComboBox *self = getself<QComboBox *>(context);
  6128. self->addItem(argument<QString>(0, context));
  6129. return QScriptValue();
  6130. }
  6131. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *)
  6132. {
  6133. QComboBox *self = getself<QComboBox *>(context);
  6134. self->setModel(argument<QAbstractItemModel *>(0, context));
  6135. return QScriptValue();
  6136. }
  6137. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine)
  6138. {
  6139. QComboBox *self = getself<QComboBox *>(context);
  6140. return QScriptValue(engine, self->findText(argument<QString>(0, context)));
  6141. }
  6142. QScriptValue QComboBox_findData(QScriptContext *context, QScriptEngine *engine)
  6143. {
  6144. QComboBox *self = getself<QComboBox *>(context);
  6145. return QScriptValue(engine, self->findData(argument<QVariant>(0, context)));
  6146. }
  6147. @i abouttypica.w
  6148. @** A representation of temperature measurements.
  6149. \noindent Most of the information in a roast log will be temperature
  6150. measurements. These measurements are made of two components: the measured
  6151. temperature and the time at which that measurement was taken.
  6152. Measurement times are represented as instances of |QTime|.
  6153. @i units.w
  6154. @ We will require the |units.h| header.
  6155. @<Header files to include@>=
  6156. #include "units.h"
  6157. @i measurement.w
  6158. @** The Main Measurement Pipeline.
  6159. \noindent Measurements are sent through \pn{} in a way similar to liquid moving
  6160. through a series of connected pipes. \pn{} is not something that you just dump
  6161. measurements on. It'@q'@>s not a big truck\nfnote{Senator Ted Stevens (R-Alaska) on
  6162. network neutrality, June 28, 2006\par
  6163. \hbox{\indent\pdfURL{http://media.publicknowledge.org/stevens-on-nn.mp3}%
  6164. {http://media.publicknowledge.org/stevens-on-nn.mp3}}}. In most cases the
  6165. connections between classes (represented by arrows in Figure \secno) are made
  6166. with Qt'@q'@>s signals and slots mechanism\nfnote{Qt 4.4.3: Signals and Slots\par
  6167. \hbox{\indent\pdfURL{http://doc.trolltech.com/4.4/signalsandslots.html}%
  6168. {http://doc.trolltech.com/4.4/signalsandslots.html}}}, but
  6169. these
  6170. connections can
  6171. also be made through direct function calls as is the case with the connection
  6172. between |ZoomLog| and |MeasurementModel|.
  6173. \medskip
  6174. \includegraphics{pipes}
  6175. \smallskip
  6176. \centerline{Figure \secno: Example Flow of Measurement objects in \pn}
  6177. \medskip
  6178. Please note that Figure \secno~is representative of a typical configuration. Now
  6179. that the flow of measurements through \pn{} is determined by a script specified
  6180. by the user, whatever pipeline is needed can be specified at run time.
  6181. @* The DAQ class.
  6182. \noindent The |DAQ| class represents a piece of hardware that allows the
  6183. computer to read measurements from one or more thermocouples. Presently this
  6184. class is only handles continuous sampling on devices from National Instruments.
  6185. It should be simple to modify this class to handle similar devices from other
  6186. vendors.
  6187. Each device is represented by a single instance of this class. Multiple channels
  6188. can be used on a device if the device supports it.
  6189. Two enumerations are declared in this class to be used as arguments to
  6190. |newChannel()|. The first is used to set the measurement unit for the channel.
  6191. As the measurements themselves do not carry this information, it is important to
  6192. keep track of this information. The values come from {\tt nidaqmxbase.h} and can
  6193. be used to select among Fahrenheit, Celsius, Kelvin, and Rankine. The
  6194. second enumeration, |ThermocoupleType|, should be used to specify the type of
  6195. thermocouple connected to the device. If this does not match reality, the
  6196. measurements will not be correct. The meanings of the values should be obvious
  6197. from the names.
  6198. \danger When this class was originally written the method of thread handling
  6199. used was considered appropriate. New functionality in |QThread| has made this
  6200. no longer the case. This class is currently planned for depreciation once a
  6201. replacement class hierarchy more suited to multiple hardware types is available
  6202. however if this is not ready soon it may be beneficial to rewrite this class to
  6203. conform to current best practices.\endanger
  6204. @<Class declarations@>=
  6205. class Channel;
  6206. class DAQImplementation;@/
  6207. class DAQ : public QObject@;@/
  6208. {@t\1@>@/
  6209. Q_OBJECT@/
  6210. Q_ENUMS(ThermocoupleType)@;@/
  6211. DAQImplementation *imp;@/
  6212. @t\4@>private slots@t\kern-3pt@>:@/
  6213. void threadFinished();
  6214. public:@;
  6215. DAQ(QString device, const QString &driver = QString("nidaqmxbase"));
  6216. ~DAQ();@/
  6217. Channel* newChannel(int units, int thermocouple);@/
  6218. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  6219. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  6220. @[Q_INVOKABLE@,@, void@]@, stop();@t\2\2@>@/
  6221. enum ThermocoupleType@/
  6222. {
  6223. @!TypeJ = 10072,
  6224. @!TypeK = 10073,
  6225. @!TypeN = 10077,
  6226. @!TypeR = 10082,
  6227. @!TypeS = 10085,
  6228. @!TypeT = 10086,
  6229. @!TypeB = 10047,
  6230. @!TypeE = 10055
  6231. };@t\2@>@/
  6232. }@t\kern-3pt@>;
  6233. @ The |DAQ| class has as a private member an instance of a class called
  6234. |DAQImplementation|. The two classes together create and run a new thread of
  6235. execution. This thread spends most of its time blocking while waiting for a new
  6236. measurement to become available. When a new measurement is available, that
  6237. measurement is passed to the appropriate channel which in turn passes it to any
  6238. interested object.
  6239. @<Class declarations@>=
  6240. class DAQImplementation : public QThread@;@/
  6241. {@;
  6242. Q_OBJECT@;@/
  6243. public:@;
  6244. DAQImplementation(const QString &driverinfo);
  6245. ~DAQImplementation();
  6246. void run();
  6247. void measure();
  6248. @<Library function pointers@>@;
  6249. @<DAQImplementation member data@>@;
  6250. }@+@t\kern-3pt@>;
  6251. @ In order to solve some minor problems, NI-DAQmxBase is no longer linked at
  6252. compile time. Rather, this is now linked at runtime through a |QLibrary| object.
  6253. In order to use functions from this library, these functions must be stored in
  6254. function pointers. Fortunately, all of these functions can be expressed with the
  6255. same pointer type. Unfortunately, this way of doing things offers very little
  6256. debugging information in the event that something is not quite right.
  6257. @<Library function pointers@>=
  6258. typedef int (*daqfp)(...);
  6259. daqfp read;
  6260. daqfp errorInfo;
  6261. daqfp startTask;
  6262. daqfp createTask;
  6263. daqfp createChannel;
  6264. daqfp setClock;
  6265. daqfp stopTask;
  6266. daqfp clearTask;
  6267. daqfp resetDevice;
  6268. daqfp waitForMeasurement;
  6269. @ |DAQImplementation| also maintains information about the device and the
  6270. channels the measurements are sent to.
  6271. @<DAQImplementation member data@>=
  6272. bool useBase;
  6273. QString device;
  6274. QVector<Channel*> channelMap;
  6275. unsigned int handle;@/
  6276. int error;
  6277. int channels;
  6278. bool ready;
  6279. QLibrary driver;
  6280. QVector<Units::Unit> unitMap;
  6281. @ Most of the interesting work associated with the |DAQ| class is handled in
  6282. the |measure()| method of |DAQImplementation|. This function will block until a
  6283. measurement is available. Once |buffer| is filled by |DAQmxBaseReadAnalogF64()|
  6284. that function returns and new |Measurement| objects are created based on the
  6285. information in the buffer. These measurements are sent to |Channel| objects
  6286. tracked by |channelMap|.
  6287. Up until version 1.0.7 there was a bug in this code that would prevent the code
  6288. from working when more than one channel is requested. This has been corrected.
  6289. With version 1.0.9, time measurement is moved out of the loop, reducing the
  6290. number of calls in cases of more than 1 measurement and ensuring that all
  6291. simultaneously obtained measurements have the same time stamp.
  6292. @<DAQ Implementation@>=
  6293. void DAQImplementation::measure()@t\2@>@/
  6294. @t\4@>{@/
  6295. int samplesRead = 0;
  6296. double buffer[channels];
  6297. error = read((unsigned int)(handle), (signed long)(1), (double)(10.0),@|
  6298. (unsigned long)(0), buffer, (unsigned long)(channels),@|
  6299. &samplesRead, (signed long)(0));@/
  6300. if(error)@/
  6301. @t\1@>{@/
  6302. ready = false;@t\2@>@/
  6303. }
  6304. else@/
  6305. {
  6306. if(samplesRead)@/
  6307. {
  6308. QTime time = QTime::currentTime();@/
  6309. for(int i = 0; i < samplesRead; i++)@/
  6310. {
  6311. for(int j = 0; j < channels; j++)@/
  6312. {
  6313. double measuredValue = buffer[j+(i*channels)];
  6314. Measurement measure(measuredValue, time,
  6315. unitMap[j]);
  6316. channelMap[@,j]->input(measure);
  6317. }
  6318. }
  6319. }
  6320. }
  6321. @t\4@>}
  6322. @ It was noted that |DAQmxBaseReadAnalogF64()| blocks until it is able to fill
  6323. the |buffer| passed to it. To prevent this behavior from having adverse effects
  6324. on the rest of the program, measure is called from a loop running in its own
  6325. thread of execution. When the thread is started, it begins its execution from
  6326. the |run()| method of |DAQImplementation| which overrides the |run()| method of
  6327. |QThread|. Here the priority of the thread is set in an attempt to cut down on
  6328. the variation in time between recorded measurements.
  6329. The while loop is controlled by |ready| which is set to |false| when there is an
  6330. error in collecting a measurement or when the user wants to exit the program. It
  6331. could also be set to |false| when the |DAQ| is reconfigured.
  6332. @<DAQ Implementation@>=
  6333. void DAQImplementation::run()
  6334. {
  6335. setPriority(QThread::TimeCriticalPriority);
  6336. while(ready)
  6337. {
  6338. measure();
  6339. }
  6340. }
  6341. @ When this loop exits, |DAQImplementation| emits a finished signal to indicate
  6342. that the thread is no longer running. This could be due to perfectly normal
  6343. conditions, but there could also be a problem that the user must be informed of.
  6344. That signal is connected to a function that checks for error conditions and
  6345. reports them if needed.
  6346. @<DAQ Implementation@>=
  6347. void DAQ::threadFinished()
  6348. {
  6349. if(imp->error)
  6350. {
  6351. @<Display DAQ Error@>@;
  6352. }
  6353. }
  6354. @ Errors are displayed with a |QMessageBox|. NIDAQmxBase provides the message
  6355. strings for these errors, but this should probably change as these error strings
  6356. are generally completely unrelated to what the problem really is. For example,
  6357. ``Error: -1'' usually means that the device is not plugged in.
  6358. ``Error: -200170'' usually means that \pn{} or another program using the device
  6359. did not exit cleanly. A table of replacement warning messages should be added to
  6360. this program.
  6361. \bigskip
  6362. \settabs 5 \columns
  6363. \+Error Code & NIDAQmxBase Text & & Likely Cause\cr
  6364. \+\hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill\cr
  6365. \+ -1 & Not implemented for this device & & The device is not plugged in.\cr
  6366. \+ & type. & \cr
  6367. \+ -200170 & Physical channel specified & & The program did not exit cleanly\cr
  6368. \+ & does not exist on this device. & & or another program is using the\cr
  6369. \+ & Refer to the documentation for & & device.\cr
  6370. \+ & channels available on this device.\cr
  6371. \+ -1073807194 & {\it{(No text)}} & & The device has been unplugged.\cr
  6372. \medskip
  6373. \centerline{Table \secno: Error codes, text, and what they really mean.}
  6374. \bigskip
  6375. There are two calls to |DAQmxBaseGetExtendedErrorInfo()| to obtain the error
  6376. messages. The first is used just to obtain the length of the error string. That
  6377. length is then used to allocate space for the error message. The second call
  6378. fills that string. This isn'@q'@>t allowed by ISO \CPLUSPLUS/\nfnote{%
  6379. \CPLUSPLUS/Dynamic Arrays (Crowl and Austern, May 16, 2008)\par
  6380. \hbox{\indent\pdfURL{%
  6381. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}{%
  6382. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}}} but it
  6383. works with gcc. If this is a problem, the first call can be
  6384. removed and the buffer can be set large enough to fit the largest error message
  6385. that will be produced. Heap allocation could be used, but then we need to
  6386. remember to free the memory allocated to the string. Alternately, we can get rid
  6387. of \CEE/ style strings and write our own error messages. This would be the
  6388. preferred correction.
  6389. @<Display DAQ Error@>=
  6390. imp->ready = false;
  6391. QMessageBox warning;
  6392. warning.setStandardButtons(QMessageBox::Cancel);
  6393. warning.setIcon(QMessageBox::Warning);
  6394. warning.setText(QString(tr("Error: %1")).arg(imp->error));
  6395. unsigned long bytes = imp->errorInfo(NULL, 0);
  6396. char string[bytes];
  6397. imp->errorInfo(string, bytes);
  6398. warning.setInformativeText(QString(string));
  6399. warning.setWindowTitle(QString(PROGRAM_NAME));
  6400. warning.exec();
  6401. @ Starting the thread is almost as simple as ending it. The hardware is
  6402. instructed to begin taking measurements. If there is an error, this is handled.
  6403. Otherwise, the finished signal from |DAQImplementation| is connected to
  6404. |threadFinished()| and the new thread is started. The call to |imp->start()|
  6405. starts a new thread and passes control of that thread to |imp->run()|. The main
  6406. thread of execution returns without waiting for the new thread to do anything.
  6407. The call to |DAQmxBaseStartTask()| requires some time before the first
  6408. measurement is available. This is one of the reasons we start gathering
  6409. measurements before we really need them and continue to collect them until it is
  6410. time to exit the program.
  6411. @<DAQ Implementation@>=
  6412. void DAQ::start()
  6413. {
  6414. if(imp->ready)
  6415. {
  6416. imp->error = imp->startTask(imp->handle);
  6417. if(imp->error)
  6418. {
  6419. @<Display DAQ Error@>@;
  6420. }
  6421. else
  6422. {
  6423. connect(imp, SIGNAL(finished()), this, SLOT(threadFinished()));
  6424. imp->start();
  6425. }
  6426. }
  6427. }
  6428. void DAQ::stop()
  6429. {
  6430. if(imp->useBase)
  6431. {
  6432. imp->ready = @[false@];
  6433. imp->wait(ULONG_MAX);
  6434. imp->stopTask(imp->handle);
  6435. }
  6436. else
  6437. {
  6438. imp->ready = @[false@];
  6439. imp->error = imp->stopTask(imp->handle);
  6440. if(imp->error)
  6441. {
  6442. @<Display DAQ Error@>@;
  6443. }
  6444. imp->error = imp->clearTask(imp->handle);
  6445. if(imp->error)
  6446. {
  6447. @<Display DAQ Error@>@;
  6448. }
  6449. }
  6450. }
  6451. @ Setting up the DAQ begins by constructing a new |DAQ| object. The constructor
  6452. takes as its argument a string indicating the name of the device and will
  6453. typically be something like |"Dev1"|. This creates a new task which is required
  6454. for the setup that follows once a new |DAQ| is created.
  6455. @<DAQ Implementation@>=
  6456. DAQ::DAQ(QString device, const QString &driver) : imp(new DAQImplementation(driver))@/
  6457. @t\4\4@>{@/
  6458. imp->device = device;
  6459. imp->error = imp->createTask(device.toAscii().data(), &(imp->handle));
  6460. if(imp->error)@/
  6461. {
  6462. @<Display DAQ Error@>@;
  6463. }
  6464. else@/
  6465. @t\1@>{@/
  6466. imp->ready = true;@t\2@>@/
  6467. }@/
  6468. @t\4\4@>}
  6469. @ Once the |DAQ| is created, one or more channels can be added to that |DAQ|.
  6470. All |Channel| objects are created by the |DAQ| class and are managed by the
  6471. |DAQ| class. When a new channel is created, a pointer is passed back allowing
  6472. other classes to connect to the channel. Measurements cannot be read from the
  6473. |DAQ| directly. They must at some point pass through a channel.
  6474. @<DAQ Implementation@>=
  6475. Channel* DAQ::newChannel(int units, int thermocouple)
  6476. {
  6477. Channel *retval = new Channel();
  6478. imp->channelMap[imp->channels] = retval;
  6479. imp->unitMap[imp->channels] = (Units::Unit)units;
  6480. imp->channels++;
  6481. if(imp->ready)
  6482. {
  6483. if(imp->useBase)
  6484. {
  6485. imp->error = imp->createChannel(imp->handle,
  6486. QString("%1/ai%2").arg(imp->device).
  6487. arg(imp->channels - 1).
  6488. toAscii().data(),
  6489. "", (double)(-1.0), (double)(100.0),
  6490. (signed long)(units),
  6491. (signed long)(thermocouple),
  6492. (signed long)(10200), (double)(0),
  6493. "");
  6494. }
  6495. else
  6496. {
  6497. imp->error = imp->createChannel(imp->handle,
  6498. QString("%1/ai%2").arg(imp->device).
  6499. arg(imp->channels - 1).
  6500. toAscii().data(),
  6501. "", (double)(50.0), (double)(500.0),
  6502. (signed long)(units),
  6503. (signed long)(thermocouple),
  6504. (signed long)(10200), (double)(0),
  6505. "");
  6506. }
  6507. if(imp->error)
  6508. {
  6509. @<Display DAQ Error@>@;
  6510. }
  6511. }
  6512. return retval;
  6513. }
  6514. @ Once the channels are created, it is necessary to set the clock rate of the
  6515. DAQ. The clock rate chosen must be supported by the hardware. The clock rates
  6516. supported by the hardware may be altered by the number of channels in use.
  6517. The amount of time between measurements may vary slightly. A test configuration
  6518. at Wilson's Coffee \char'046~Tea used a 4Hz clock rate and provides measurements
  6519. every 251$\pm$1ms with 80\% of measurements spaced 251ms apart.
  6520. @<DAQ Implementation@>=
  6521. void DAQ::setClockRate(double Hz)
  6522. {
  6523. if(imp->ready)
  6524. {
  6525. imp->error = imp->setClock(imp->handle, "OnboardClock", Hz,
  6526. (signed long)(10280), (signed long)(10123),
  6527. (unsigned long long)(1));
  6528. if(imp->error)
  6529. {
  6530. @<Display DAQ Error@>@;
  6531. }
  6532. }
  6533. }
  6534. @ Before the program exits, the |DAQ| should be deleted. The destructor
  6535. instructs the measurement thread to stop, waits for it to finish, and resets the
  6536. device. If this is not done, an error would be issued the next time a program
  6537. attempted to use the device.
  6538. @<DAQ Implementation@>=
  6539. DAQ::~DAQ()@/
  6540. {
  6541. if(imp->useBase)
  6542. {
  6543. imp->resetDevice(imp->device.toAscii().data());
  6544. imp->clearTask(imp->handle);
  6545. }
  6546. else
  6547. {
  6548. if(imp->ready)
  6549. {
  6550. imp->ready = @[false@];
  6551. imp->wait(ULONG_MAX);
  6552. imp->stopTask(imp->handle);
  6553. imp->resetDevice(imp->device.toAscii().data());
  6554. imp->clearTask(imp->handle);
  6555. }
  6556. }
  6557. delete imp;
  6558. }
  6559. @ This just leaves the constructor and destructor for |DAQImplementation|. The
  6560. way the program is currently written, the number of channels available on the
  6561. |DAQ| is limited to 4. If a known larger number is required, the value here can
  6562. simply be set larger, however the best long term solution would be to modify
  6563. |newChannel()| to resize |channelMap| as more channels are added.
  6564. The constructor handles loading NI-DAQmxBase and preparing function pointers for
  6565. the symbols used in \pn{}.
  6566. @<DAQ Implementation@>=
  6567. DAQImplementation::DAQImplementation(const QString &driverinfo)
  6568. : QThread(NULL), channelMap(4), handle(0), error(0), channels(0), ready(false),
  6569. unitMap(4)@/
  6570. {
  6571. if(driverinfo == "nidaqmxbase")
  6572. {
  6573. useBase = true;
  6574. }
  6575. else
  6576. {
  6577. useBase = false;
  6578. }
  6579. if(useBase)
  6580. {
  6581. driver.setFileName("nidaqmxbase.framework/nidaqmxbase");
  6582. if(!driver.load())
  6583. {
  6584. driver.setFileName("nidaqmxbase");
  6585. if(!driver.load())
  6586. {
  6587. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  6588. tr("Failed to find nidaqmxbase. Please install it."));
  6589. QApplication::quit();
  6590. }
  6591. }
  6592. }
  6593. else
  6594. {
  6595. driver.setFileName("nicaiu");
  6596. if(!driver.load())
  6597. {
  6598. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  6599. tr("Failed to find nidaqmx. Please install it."));
  6600. QApplication::quit();
  6601. }
  6602. }
  6603. if(useBase)
  6604. {
  6605. if((createTask = (daqfp) driver.resolve("DAQmxBaseCreateTask")) == 0 || @|
  6606. (startTask = (daqfp) driver.resolve("DAQmxBaseStartTask")) == 0 || @|
  6607. (stopTask = (daqfp) driver.resolve("DAQmxBaseStopTask")) == 0 || @|
  6608. (clearTask = (daqfp) driver.resolve("DAQmxBaseClearTask")) == 0 || @|
  6609. (createChannel = (daqfp) driver.resolve("DAQmxBaseCreateAIThrmcplChan"))
  6610. == 0 || @|
  6611. (setClock = (daqfp) driver.resolve("DAQmxBaseCfgSampClkTiming")) ==
  6612. 0 || @|
  6613. (read = (daqfp) driver.resolve("DAQmxBaseReadAnalogF64")) == 0 || @|
  6614. (errorInfo = (daqfp) driver.resolve("DAQmxBaseGetExtendedErrorInfo")) ==
  6615. 0 || @|
  6616. (resetDevice = (daqfp) driver.resolve("DAQmxBaseResetDevice")) == 0)@/
  6617. {
  6618. waitForMeasurement = NULL;
  6619. QMessageBox::critical(NULL, tr("Typica: Link error"),
  6620. tr("Failed to link a required symbol in NI-DAQmxBase."));
  6621. QApplication::quit();
  6622. }
  6623. }
  6624. else
  6625. {
  6626. if((createTask = (daqfp)driver.resolve("DAQmxCreateTask")) == 0 || @|
  6627. (startTask = (daqfp)driver.resolve("DAQmxStartTask")) == 0 || @|
  6628. (stopTask = (daqfp)driver.resolve("DAQmxStopTask")) == 0 || @|
  6629. (clearTask = (daqfp)driver.resolve("DAQmxClearTask")) == 0 || @|
  6630. (createChannel = (daqfp)driver.resolve("DAQmxCreateAIThrmcplChan"))
  6631. == 0 || @|
  6632. (setClock = (daqfp)driver.resolve("DAQmxCfgSampClkTiming")) == 0 || @|
  6633. (read = (daqfp)driver.resolve("DAQmxReadAnalogF64")) == 0 || @|
  6634. (errorInfo = (daqfp)driver.resolve("DAQmxGetExtendedErrorInfo")) ==
  6635. 0 || @|
  6636. (resetDevice = (daqfp)driver.resolve("DAQmxResetDevice")) == 0 ||
  6637. (waitForMeasurement = (daqfp)driver.resolve("DAQmxWaitUntilTaskDone")) == 0)
  6638. {
  6639. QMessageBox::critical(NULL, tr("Typica: Link error"),
  6640. tr("Failed to link a required symbol in NI-DAQmx."));
  6641. QApplication::quit();
  6642. }
  6643. }
  6644. }
  6645. DAQImplementation::~DAQImplementation()
  6646. {
  6647. driver.unload();
  6648. }
  6649. @ When exposing the |DAQ| class to the scripting engine, we need to provide a
  6650. constructor that can be called from a script and we need a way to call
  6651. |DAQ::newChannel()|. Other methods that are useful when called from a script are
  6652. made available automatically with the |Q_INVOKABLE| macro, however this does not
  6653. work for methods such as |newChannel()| which return a pointer to a |Channel|
  6654. object.
  6655. @<Function prototypes for scripting@>=
  6656. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine);
  6657. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  6658. void setDAQProperties(QScriptValue value, QScriptEngine *engine);
  6659. @ These functions and the values from |Units::Unit| must be made available to
  6660. the host environment. The latter because this was widely used in configurations
  6661. before this enumeration was removed from the |DAQ| class. As these properties
  6662. must be available without an instance, the properties must be added here.
  6663. @<Set up the scripting engine@>=
  6664. constructor = engine->newFunction(constructDAQ);
  6665. value = engine->newQMetaObject(&DAQ::staticMetaObject, constructor);
  6666. value.setProperty("Fahrenheit", Units::Fahrenheit);
  6667. value.setProperty("Celsius", Units::Celsius);
  6668. value.setProperty("Kelvin", Units::Kelvin);
  6669. value.setProperty("Rankine", Units::Rankine);
  6670. engine->globalObject().setProperty("DAQ", value);
  6671. @ When creating a new |DAQ|, we make sure that it is owned by the script engine.
  6672. This is necessary to ensure that the destructor is called before \pn{} exits.
  6673. Just as the constructor requires an argument that specifies the device name, the
  6674. constructor available from a script also requires this argument.
  6675. @<Functions for scripting@>=
  6676. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine)
  6677. {
  6678. QScriptValue object;
  6679. if(context->argumentCount() == 1)
  6680. {
  6681. object = engine->newQObject(new DAQ(argument<QString>(0, context)),
  6682. QScriptEngine::ScriptOwnership);
  6683. setDAQProperties(object, engine);
  6684. }
  6685. else if(context->argumentCount() == 2)
  6686. {
  6687. object = engine->newQObject(new DAQ(argument<QString>(0, context),
  6688. argument<QString>(1, context)),
  6689. QScriptEngine::ScriptOwnership);
  6690. setDAQProperties(object, engine);
  6691. }
  6692. else
  6693. {
  6694. context->throwError("Incorrect number of arguments passed to DAQ"@|
  6695. "constructor. The DAQ constructor takes one"@|
  6696. "string as an argument specifying a device name."@|
  6697. "Example: Dev1");
  6698. }
  6699. return object;
  6700. }
  6701. @ As |DAQ| inherits |QObject|, we add the |newChannel()| property after adding
  6702. any |QObject| properties.
  6703. @<Functions for scripting@>=
  6704. void setDAQProperties(QScriptValue value, QScriptEngine *engine)
  6705. {
  6706. setQObjectProperties(value, engine);
  6707. value.setProperty("newChannel", engine->newFunction(DAQ_newChannel));
  6708. }
  6709. @ The |newChannel()| method method also requires that two arguments are provided
  6710. by the script.
  6711. @<Functions for scripting@>=
  6712. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  6713. {
  6714. DAQ *self = getself<@[DAQ *@]>(context);
  6715. QScriptValue object;
  6716. if(self)
  6717. {
  6718. object =
  6719. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  6720. argument<int>(1, context)));
  6721. setChannelProperties(object, engine);
  6722. }
  6723. return object;
  6724. }
  6725. @ Sometimes it can be useful to test other parts of the program (for example,
  6726. when developing new scripts) when the DAQ hardware is not available. In these
  6727. cases, it is possible to temporarily use the |FakeDAQ| class. This class mimics
  6728. the |DAQ| class, but just makes up the measurements sent to the rest of the
  6729. program.
  6730. @<Class declarations@>=
  6731. class FakeDAQImplementation : public QThread@/
  6732. {@/
  6733. Q_OBJECT@;
  6734. public:@/
  6735. FakeDAQImplementation();
  6736. ~FakeDAQImplementation();
  6737. void run();
  6738. void measure();
  6739. QVector<Channel *> channelMap;
  6740. int channels;
  6741. bool ready;
  6742. double clockRate;
  6743. };@/
  6744. class FakeDAQ : public QObject@/
  6745. {@/
  6746. Q_OBJECT@;
  6747. FakeDAQImplementation *imp;
  6748. public:@/
  6749. FakeDAQ(QString device);
  6750. ~FakeDAQ();
  6751. Channel *newChannel(int units, int thermocouple);@/
  6752. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  6753. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  6754. };
  6755. @ Just as in the |DAQ| class, most of the interesting stuff happens in
  6756. |measure()|. For each invokation of the method, we sleep for some amount of time
  6757. based on the clock rate then create a |Measurement| object at random for each
  6758. |Channel| that has been created.
  6759. @<FakeDAQ Implementation@>=
  6760. void FakeDAQImplementation::measure()
  6761. {
  6762. msleep((int)(1000/clockRate));
  6763. QTime time = QTime::currentTime();
  6764. for(int i = 0; i < channels; i++)
  6765. {
  6766. Measurement measure(qrand() % 500, time);
  6767. channelMap[i]->input(measure);
  6768. }
  6769. }
  6770. @ To call |measure|, we need to flesh out the rest of |FakeDAQImplementation|.
  6771. @<FakeDAQ Implementation@>=
  6772. void FakeDAQImplementation::run()
  6773. {
  6774. setPriority(QThread::TimeCriticalPriority);
  6775. while(ready)
  6776. {
  6777. measure();
  6778. }
  6779. }
  6780. FakeDAQImplementation::FakeDAQImplementation() : QThread(NULL), channelMap(4),
  6781. channels(0), ready(false), clockRate(1)@/
  6782. {
  6783. /* Nothing has to be done here. */
  6784. }
  6785. FakeDAQImplementation::~FakeDAQImplementation()
  6786. {
  6787. /* Nothing has to be done here. */
  6788. }
  6789. @ Next we need an implementation for the |FakeDAQ| class. This is simplified by
  6790. the fact that we are just using a random number generator to generate
  6791. measurements rather than special hardware for obtaining measurements.
  6792. @<FakeDAQ Implementation@>=
  6793. void FakeDAQ::start()
  6794. {
  6795. if(imp->ready)
  6796. {
  6797. imp->start();
  6798. }
  6799. }@#
  6800. FakeDAQ::FakeDAQ(QString) : imp(new FakeDAQImplementation())@t\2\2@>@/
  6801. {@t\1@>@/
  6802. imp->ready = true;@t\2@>@/
  6803. }@#
  6804. Channel* FakeDAQ::newChannel(int, int)
  6805. {
  6806. Channel *retval;
  6807. if(imp->ready)
  6808. {
  6809. retval = new Channel();
  6810. imp->channelMap[imp->channels] = retval;
  6811. imp->channels++;
  6812. }
  6813. else
  6814. {
  6815. return NULL;
  6816. }
  6817. return retval;
  6818. }
  6819. void FakeDAQ::setClockRate(double Hz)
  6820. {
  6821. if(imp->ready)
  6822. {
  6823. imp->clockRate = Hz;
  6824. }
  6825. }@#
  6826. FakeDAQ::~FakeDAQ()@t\2\2@>@/
  6827. {@t\1@>@/
  6828. imp->ready = false;
  6829. imp->wait(ULONG_MAX);
  6830. delete imp;@t\2@>@/
  6831. }
  6832. @ As the entire purpose of the |FakeDAQ| class is for testing purposes from
  6833. within the scripting engine, we need to make it available to the scripting
  6834. engine. This is done in a manner very similar to how the |DAQ| class is handled.
  6835. @<Function prototypes for scripting@>=
  6836. QScriptValue constructFakeDAQ(QScriptContext *context, QScriptEngine *engine);
  6837. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  6838. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine);
  6839. @ The scripting engine is informed of the constructor.
  6840. @<Set up the scripting engine@>=
  6841. constructor = engine->newFunction(constructFakeDAQ);
  6842. value = engine->newQMetaObject(&FakeDAQ::staticMetaObject, constructor);
  6843. engine->globalObject().setProperty("FakeDAQ", value);
  6844. @ The constructor sets a property to allow calling |newChannel()| on a |FakeDAQ|
  6845. created from a script.
  6846. @<Functions for scripting@>=
  6847. QScriptValue constructFakeDAQ(QScriptContext *context,
  6848. QScriptEngine *engine)
  6849. {
  6850. QScriptValue object;
  6851. if(context->argumentCount() == 1)
  6852. {
  6853. object =
  6854. engine->newQObject(new FakeDAQ(argument<QString>(0, context)),
  6855. QScriptEngine::ScriptOwnership);
  6856. setFakeDAQProperties(object, engine);
  6857. }
  6858. else
  6859. {
  6860. context->throwError("Incorrect number of arguments passed to DAQ"@|
  6861. "constructor. The DAQ constructor takes one"@|
  6862. "string as an argument specifying a device name."@|
  6863. "Example: Dev1");
  6864. }
  6865. return object;
  6866. }
  6867. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine)
  6868. {
  6869. setQObjectProperties(value, engine);
  6870. value.setProperty("newChannel", engine->newFunction(FakeDAQ_newChannel));
  6871. }
  6872. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  6873. {
  6874. FakeDAQ *self = getself<@[FakeDAQ *@]>(context);
  6875. QScriptValue object;
  6876. if(self)
  6877. {
  6878. object =
  6879. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  6880. argument<int>(1, context)));
  6881. setChannelProperties(object, engine);
  6882. }
  6883. return object;
  6884. }
  6885. @* The Channel class.
  6886. \noindent |Channel| is a simple class. It is a subclass of |QObject| so it can
  6887. use Qt'@q'@>s signals and slots mechanism. Any object that is interested in
  6888. measurements from a channel can connect to the |newData| signal the channel
  6889. emits. Any number of objects can make this connection and each will receive a
  6890. copy of the measurement.
  6891. |Channel| objects should only be created by the |DAQ| class.
  6892. @<Class declarations@>=
  6893. class Channel : public QObject@;@/
  6894. {@t\1@>@/
  6895. Q_OBJECT@/
  6896. public:@;
  6897. Channel();
  6898. ~Channel();@/
  6899. @t\4@>public slots@t\kern-3pt@>:@;
  6900. void input(Measurement measurement);@/
  6901. signals:@;
  6902. void newData(Measurement);@t\2@>@/
  6903. };
  6904. @ The implementation of this class is trivial.
  6905. @<Channel Implementation@>=
  6906. Channel::Channel() : QObject(NULL)@/
  6907. {
  6908. /* Nothing has to be done here. */
  6909. }
  6910. Channel::~Channel()
  6911. {
  6912. /* Nothing has to be done here. */
  6913. }
  6914. void Channel::input(Measurement measurement)
  6915. {
  6916. emit newData(measurement);
  6917. }
  6918. @ A function is provided for use when a channel is created by a DAQ from a
  6919. script.
  6920. @<Function prototypes for scripting@>=
  6921. void setChannelProperties(QScriptValue value, QScriptEngine *engine);
  6922. @ The implementation is trivial.
  6923. @<Functions for scripting@>=
  6924. void setChannelProperties(QScriptValue value, QScriptEngine *engine)
  6925. {
  6926. setQObjectProperties(value, engine);
  6927. }
  6928. @* Calibration and Unit Conversion.
  6929. \noindent One of the planned features for \pn{} is support for hardware that
  6930. collects non-temperature measurements. This is frequently handled with analog
  6931. voltage signals which are proportional to some range in a meaningful unit. Some
  6932. hardware also requires calibration in software. In many cases both of these can
  6933. be handled at the same time with a single mapping in the form:
  6934. $$f(x) = L_1 + (x - L_2){U_1 - L_1\over{U_2 - L_2}}$$
  6935. \noindent where $L_1$ is the logical lower bound, $L_2$ is the measured lower
  6936. bound, $U_1$ is the logical upper bound, $U_2$ is the measured upper bound, and
  6937. $x$ is the value we wish to map from the range $\lbrack L_2, U_2 \rbrack$ to
  6938. the range $\lbrack L_1, U_1 \rbrack$.
  6939. Some use cases require a closed range but others require that this constraint
  6940. is loosened to allow extrapolation. Both are provided by this class.
  6941. Starting in \pn{} 1.6 this class has both the |measurement| and the
  6942. |newData| signals. This allows a |LinearCalibrator| to be treated like a
  6943. |Channel| when used with a |DataqSdkDevice|.
  6944. @<Class declarations@>=
  6945. class LinearCalibrator : public QObject@/
  6946. {@/
  6947. @[Q_OBJECT@]@;
  6948. @[Q_PROPERTY(double measuredLower READ measuredLower
  6949. WRITE setMeasuredLower)@]@;
  6950. @[Q_PROPERTY(double measuredUpper READ measuredUpper
  6951. WRITE setMeasuredUpper)@]@;
  6952. @[Q_PROPERTY(double mappedLower READ mappedLower WRITE setMappedLower)@]@;
  6953. @[Q_PROPERTY(double mappedUpper READ mappedUpper WRITE setMappedUpper)@]@;
  6954. @[Q_PROPERTY(bool closedRange READ isClosedRange WRITE setClosedRange)@]@;
  6955. @[Q_PROPERTY(double sensitivity READ sensitivity WRITE setSensitivity)@]@;
  6956. public:@/
  6957. LinearCalibrator(QObject *parent = NULL);
  6958. double measuredLower();
  6959. double measuredUpper();
  6960. double mappedLower();
  6961. double mappedUpper();
  6962. bool isClosedRange();
  6963. double sensitivity();
  6964. @t\4@>@[public slots@t\kern-3pt@>:@]@;
  6965. void setMeasuredLower(double lower);
  6966. void setMeasuredUpper(double upper);
  6967. void setMappedLower(double lower);
  6968. void setMappedUpper(double upper);
  6969. void setClosedRange(bool closed);
  6970. void setSensitivity(double sensitivity);
  6971. Measurement newMeasurement(Measurement measure);
  6972. @t\4@>@[signals:@]@;
  6973. void measurement(Measurement measure);
  6974. void newData(Measurement measure);
  6975. private:@/
  6976. double Lo1;
  6977. double Lo2;
  6978. double Up1;
  6979. double Up2;
  6980. double sensitivitySetting;
  6981. bool clamp;
  6982. };
  6983. @ When the measured range and the mapped range are identical and the range is
  6984. open, we have an identity mapping. This is the default state in a newly
  6985. constructed |LinearCalibrator| which should quickly be changed.
  6986. @<LinearCalibrator Implementation@>=
  6987. LinearCalibrator::LinearCalibrator(QObject *parent) :
  6988. QObject(parent), Lo1(0), Lo2(0), Up1(1), Up2(1), sensitivitySetting(0.0), clamp(false)@/
  6989. {
  6990. connect(this, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  6991. }
  6992. @ The functional portion of the class is in the |newMeasurement()| slot. This
  6993. will receive measurements as they come in and emit a |measurement()| signal for
  6994. each with the calibration and unit adjustment performed.
  6995. This method also handles any rounding needed if there has been a call to
  6996. |setSensitivity()|.
  6997. @<LinearCalibrator Implementation@>=
  6998. Measurement LinearCalibrator::newMeasurement(Measurement measure)
  6999. {
  7000. double outval = Lo1 + (measure.temperature() - Lo2) * (Up1 - Lo1)/(Up2 - Lo2);
  7001. if(clamp)
  7002. {
  7003. if(outval < Lo1)
  7004. {
  7005. outval = Lo1;
  7006. }
  7007. else if(outval > Up1)
  7008. {
  7009. outval = Up1;
  7010. }
  7011. }
  7012. if(sensitivitySetting >= 0.05)
  7013. {
  7014. int temp = qRound(outval/sensitivitySetting);
  7015. outval = temp * sensitivitySetting;
  7016. }
  7017. Measurement adjusted(outval, measure.time(), measure.scale());
  7018. emit measurement(adjusted);
  7019. return adjusted;
  7020. }
  7021. @ The rest of the class consists of trivial accessor methods.
  7022. @<LinearCalibrator Implementation@>=
  7023. double LinearCalibrator::measuredLower()
  7024. {
  7025. return Lo2;
  7026. }
  7027. double LinearCalibrator::measuredUpper()
  7028. {
  7029. return Up2;
  7030. }
  7031. double LinearCalibrator::mappedLower()
  7032. {
  7033. return Lo1;
  7034. }
  7035. double LinearCalibrator::mappedUpper()
  7036. {
  7037. return Up1;
  7038. }
  7039. bool LinearCalibrator::isClosedRange()
  7040. {
  7041. return clamp;
  7042. }
  7043. void LinearCalibrator::setMeasuredLower(double lower)
  7044. {
  7045. Lo2 = lower;
  7046. }
  7047. void LinearCalibrator::setMeasuredUpper(double upper)
  7048. {
  7049. Up2 = upper;
  7050. }
  7051. void LinearCalibrator::setMappedLower(double lower)
  7052. {
  7053. Lo1 = lower;
  7054. }
  7055. void LinearCalibrator::setMappedUpper(double upper)
  7056. {
  7057. Up1 = upper;
  7058. }
  7059. void LinearCalibrator::setClosedRange(bool closed)
  7060. {
  7061. clamp = closed;
  7062. }
  7063. void LinearCalibrator::setSensitivity(double sensitivity)
  7064. {
  7065. sensitivitySetting = sensitivity;
  7066. }
  7067. double LinearCalibrator::sensitivity()
  7068. {
  7069. return sensitivitySetting;
  7070. }
  7071. @ Finally, we make this class available to the scripting engine. Two functions
  7072. are required for this.
  7073. @<Function prototypes for scripting@>=
  7074. QScriptValue constructLinearCalibrator(QScriptContext *context,
  7075. QScriptEngine *engine);
  7076. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine);
  7077. @ The scripting engine is informed of the constructor.
  7078. @<Set up the scripting engine@>=
  7079. constructor = engine->newFunction(constructLinearCalibrator);
  7080. value = engine->newQMetaObject(&LinearCalibrator::staticMetaObject,
  7081. constructor);
  7082. engine->globalObject().setProperty("LinearCalibrator", value);
  7083. @ The implementation of these functions is typical for this application.
  7084. @<Functions for scripting@>=
  7085. QScriptValue constructLinearCalibrator(QScriptContext *, QScriptEngine *engine)
  7086. {
  7087. QScriptValue object = engine->newQObject(new LinearCalibrator(NULL));
  7088. setLinearCalibratorProperties(object, engine);
  7089. return object;
  7090. }
  7091. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine)
  7092. {
  7093. setQObjectProperties(value, engine);
  7094. }
  7095. @* Linear Spline Interpolation.
  7096. \noindent While linear interpolation is adequate for many purposes, it fails
  7097. when a nonlinear mapping is required. The primary use case is to calibrate
  7098. multiple coffee roasters so that roast profiles can be shared among coffee
  7099. roasters with sufficiently similar heat transfer characteristics even if
  7100. differences in the measurement hardware result in different measured values.
  7101. By recording measured values at several points known to be equivalent due to
  7102. easily observable physical changes in the coffee it is possible to use linear
  7103. spline interpolation to produce a data series that approximates on one machine
  7104. the measurements that would have been produced at another. Acceptable results
  7105. may be available with surprisingly few data points.
  7106. It was originally suspected that cubic spline interpolation would produce a
  7107. more accurate mapping, but testing with linear spline interpolation produced
  7108. results good enough that more complex mappings were not needed. Cubic spline
  7109. interpolation may still be implemented in the future, but it is a low
  7110. priority.
  7111. @<Class declarations@>=
  7112. class LinearSplineInterpolator : public QObject@/
  7113. {@/
  7114. @[Q_OBJECT@]@;@/
  7115. public:@/
  7116. LinearSplineInterpolator(QObject *parent = NULL);
  7117. @[Q_INVOKABLE@,@, void@]@, add_pair(double source, double destination);@t\2\2@>@/
  7118. @[public slots@]:@/
  7119. Measurement newMeasurement(Measurement measure);
  7120. @[signals@]:@/
  7121. void newData(Measurement measure);
  7122. private:@/
  7123. void make_interpolators();
  7124. QMap<double, double> *pairs;
  7125. QList<LinearCalibrator *> *interpolators;@/
  7126. };
  7127. @ We take advantage of the fact that iterating over a QMap always returns
  7128. entries in key order. When new measurement pairs are specified, the
  7129. interpolators are regenerated. There is significant room for performance
  7130. improvement.
  7131. @<LinearSplineInterpolator Implementation@>=
  7132. void LinearSplineInterpolator::add_pair(double source, double destination)
  7133. {
  7134. pairs->insert(source, destination);
  7135. make_interpolators();
  7136. }
  7137. void LinearSplineInterpolator::make_interpolators()
  7138. {
  7139. if(pairs->size() > 1)
  7140. {
  7141. while(interpolators->size() > 0)
  7142. {
  7143. LinearCalibrator *removed = interpolators->takeFirst();
  7144. removed->deleteLater();
  7145. }
  7146. QMap<double, double>::const_iterator i = pairs->constBegin();
  7147. QMap<double, double>::const_iterator j = i + 1;
  7148. while(j != pairs->constEnd())
  7149. {
  7150. LinearCalibrator *segment = new LinearCalibrator();
  7151. segment->setMeasuredLower(i.key());
  7152. segment->setMappedLower(i.value());
  7153. segment->setMeasuredUpper(j.key());
  7154. segment->setMappedUpper(j.value());
  7155. segment->setClosedRange(false);
  7156. interpolators->append(segment);
  7157. connect(segment, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  7158. i++;
  7159. j++;
  7160. }
  7161. }
  7162. }
  7163. LinearSplineInterpolator::LinearSplineInterpolator(QObject *parent) :
  7164. QObject(parent), pairs(new QMap<double, double>),
  7165. interpolators(new QList<LinearCalibrator *>)
  7166. {
  7167. /* Nothing needs to be done here. */
  7168. }
  7169. Measurement LinearSplineInterpolator::newMeasurement(Measurement measure)
  7170. {
  7171. QMap<double, double>::const_iterator i = pairs->constBegin();
  7172. int index = -1;
  7173. while(i != pairs->constEnd())
  7174. {
  7175. if(measure.temperature() <= i.key())
  7176. {
  7177. break;
  7178. }
  7179. i++;
  7180. index++;
  7181. }
  7182. if(index < 0)
  7183. {
  7184. index = 0;
  7185. }
  7186. if(index >= interpolators->size())
  7187. {
  7188. index = interpolators->size() - 1;
  7189. }
  7190. if(interpolators->at(index) != NULL)
  7191. {
  7192. return interpolators->at(index)->newMeasurement(measure);
  7193. }
  7194. return Measurement();
  7195. }
  7196. @ This is exposed to the scripting environment as usual.
  7197. @<Function prototypes for scripting@>=
  7198. QScriptValue constructLinearSplineInterpolator(QScriptContext *context, QScriptEngine *engine);
  7199. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine);
  7200. @ As usual.
  7201. @<Set up the scripting engine@>=
  7202. constructor = engine->newFunction(constructLinearSplineInterpolator);
  7203. value = engine->newQMetaObject(&LinearSplineInterpolator::staticMetaObject, constructor);
  7204. engine->globalObject().setProperty("LinearSplineInterpolator", value);
  7205. @ And again as usual.
  7206. @<Functions for scripting@>=
  7207. QScriptValue constructLinearSplineInterpolator(QScriptContext *, QScriptEngine *engine)
  7208. {
  7209. QScriptValue object = engine->newQObject(new LinearSplineInterpolator(NULL));
  7210. setLinearSplineInterpolatorProperties(object, engine);
  7211. return object;
  7212. }
  7213. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine)
  7214. {
  7215. setQObjectProperties(value, engine);
  7216. }
  7217. @* The TemperatureDisplay class.
  7218. Now that measurements have been generated by the |DAQ| and passed to a
  7219. |Channel|, any object that is interested in these measurements can connect to
  7220. the channel and use the measurements it sends out. So far, the time on each
  7221. measurement is the time at which it was collected. Unfortunately, this is often
  7222. not what we want. It is more useful to have the time relative to some other
  7223. point in time such as the start of the batch.
  7224. Until the measurement time is adjusted, the measurements are really only useful
  7225. to classes that do not care about the measurement time. The |TemperatureDisplay|
  7226. class is such a class. It receives measurements and displays the most recently
  7227. measured temperature.
  7228. This is a specialization of |QLCDNumber|.
  7229. @<Class declarations@>=
  7230. class TemperatureDisplay : public QLCDNumber@/
  7231. {@t\1@>@/
  7232. Q_OBJECT@;
  7233. int unit;
  7234. bool r;
  7235. public:@/
  7236. TemperatureDisplay(QWidget *parent = NULL);
  7237. ~TemperatureDisplay();@/
  7238. @t\4@>public slots@t\kern-3pt@>:@/
  7239. void setValue(Measurement temperature);
  7240. void invalidate();
  7241. void setDisplayUnits(Units::Unit scale);
  7242. void setRelativeMode(bool relative);@t\2@>@/
  7243. };
  7244. @ Starting in version 1.6 this widget is also used for displaying a relative
  7245. temperature value in the form of the rate of change indicator. To calculate
  7246. this correctly in Celsius or Kelvin we must have a way to bypass the
  7247. conversions for absolute measures.
  7248. @<TemperatureDisplay Implementation@>=
  7249. void TemperatureDisplay::setRelativeMode(bool relative)
  7250. {
  7251. r = relative;
  7252. }
  7253. @ Displaying a temperature is a simple matter of taking the temperature
  7254. component from the measurement and converting it to a string. Presently, this
  7255. code assumes that the measurements are in degrees Fahrenheit. If the code
  7256. becomes smarter about measurement units it might be a good idea to change this.
  7257. |QLCDNumber| is capable of displaying more than just numbers, so the call to
  7258. display takes a string which in this case consists of the temperature to the
  7259. $1\over100$th of a degree and might be followed by '@q'@> which will be
  7260. converted to $^\circ$ and the letter F, C, or r to indicate the unit. This
  7261. class should be mofified to allow a user specified precision.
  7262. @<TemperatureDisplay Implementation@>=
  7263. void TemperatureDisplay::setValue(Measurement temperature)
  7264. {
  7265. QString number;
  7266. switch(unit)
  7267. {
  7268. case Units::Fahrenheit:
  7269. display(QString("%1'F").
  7270. arg(number.setNum(temperature.toFahrenheit().temperature(), 'f',
  7271. 2)));
  7272. break;
  7273. case Units::Celsius:
  7274. if(!r) {
  7275. display(QString("%1'C").
  7276. arg(number.setNum(temperature.toCelsius().temperature(), 'f',
  7277. 2)));
  7278. } else {
  7279. number.setNum(temperature.temperature() * (5.0/9.0), 'f', 2);
  7280. display(QString("%1'C").arg(number));
  7281. }
  7282. break;
  7283. case Units::Kelvin:
  7284. if(!r) {
  7285. display(QString("%1").
  7286. arg(number.setNum(temperature.toKelvin().temperature(), 'f',
  7287. 2)));
  7288. } else {
  7289. number.setNum(temperature.temperature() * (5.0/9.0), 'f', 2);
  7290. display(QString("%1").arg(number));
  7291. }
  7292. break;
  7293. case Units::Rankine:
  7294. display(QString("%1'r").
  7295. arg(number.setNum(temperature.toRankine().temperature(), 'f',
  7296. 2)));
  7297. break;
  7298. case Units::Unitless:
  7299. display(QString("%1").arg(number.setNum(temperature.temperature(), 'f', 0)));
  7300. break;
  7301. default:
  7302. switch(temperature.scale())
  7303. {
  7304. case Units::Fahrenheit:
  7305. display(QString("%1'F").
  7306. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7307. break;
  7308. case Units::Celsius:
  7309. display(QString("%1'C").
  7310. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7311. break;
  7312. case Units::Kelvin:
  7313. display(QString("%1").
  7314. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7315. break;
  7316. case Units::Rankine:
  7317. display(QString("%1'r").
  7318. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7319. break;
  7320. case Units::Unitless:
  7321. display(QString("%1").arg(number.setNum(temperature.temperature(), 'f', 0)));
  7322. break;
  7323. default:
  7324. qDebug() << "Warning: Attempting to convert a non-temperature unit to a temperature unit";
  7325. break;
  7326. }
  7327. break;
  7328. }
  7329. }
  7330. @ Before measurements are displayed, we set a more sensible default display
  7331. style and an initial string. These defaults can all be overridden with calls to
  7332. the usual |QLCDNumber| methods.
  7333. \medskip
  7334. \resizebox*{6.3in}{!}{\includegraphics{QLCDNumber.png}}
  7335. \smallskip
  7336. \centerline{Figure \secno: Outline (Qt default) and Filled |QLCDNumber| Example}
  7337. \medskip
  7338. @<TemperatureDisplay Implementation@>=
  7339. TemperatureDisplay::TemperatureDisplay(QWidget *parent) :
  7340. QLCDNumber(8, parent), unit(Units::Fahrenheit), r(false)@/
  7341. {
  7342. setSegmentStyle(Filled);
  7343. display("---.--'F");
  7344. }
  7345. @ While it is not currently used, it would be good to allow an error state to
  7346. be easily discernible from a very stable temperature. Currently, if an error
  7347. occurs that results in the measurement thread exiting, no new measurements will
  7348. be generated and the temperature display will continue to read the most recent
  7349. measured value. If an error signal were emitted, it could be connected to the
  7350. following code to change the display to reflect the fact that the current
  7351. temperature is unknown.
  7352. @<TemperatureDisplay Implementation@>=
  7353. void TemperatureDisplay::invalidate()
  7354. {
  7355. display("---.--'F");
  7356. }
  7357. @ \pn{} supports the display of multiple types of unit. Typically, we use the
  7358. Auto scale which will cause |TemperatureDisplay| objects to display measurements
  7359. in whichever scale the measurement is associated with. Alternately, we can fix
  7360. the scale to a different supported scale and convert measurements to that scale
  7361. prior to display.
  7362. @<TemperatureDisplay Implementation@>=
  7363. void TemperatureDisplay::setDisplayUnits(Units::Unit scale)
  7364. {
  7365. unit = scale;
  7366. }
  7367. @ All that is left to deal with is the empty destructor.
  7368. @<TemperatureDisplay Implementation@>=
  7369. TemperatureDisplay::~TemperatureDisplay()
  7370. {
  7371. /* Nothing has to be done here. */
  7372. }
  7373. @ To use a |TemperatureDisplay| from a script, we need a function to pass a new
  7374. object to the scripting engine.
  7375. @<Function prototypes for scripting@>=
  7376. QScriptValue constructTemperatureDisplay(QScriptContext *context,
  7377. QScriptEngine *engine);
  7378. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine);
  7379. QScriptValue TemperatureDisplay_setDisplayUnits(QScriptContext *context,
  7380. QScriptEngine *engine);
  7381. @ The scripting engine must be informed of this function.
  7382. @<Set up the scripting engine@>=
  7383. constructor = engine->newFunction(constructTemperatureDisplay);
  7384. value = engine->newQMetaObject(&TemperatureDisplay::staticMetaObject,
  7385. constructor);
  7386. engine->globalObject().setProperty("TemperatureDisplay", value);
  7387. @ The constructor is trivial.
  7388. @<Functions for scripting@>=
  7389. QScriptValue constructTemperatureDisplay(QScriptContext *,
  7390. QScriptEngine *engine)
  7391. {
  7392. QScriptValue object = engine->newQObject(new TemperatureDisplay);
  7393. setTemperatureDisplayProperties(object, engine);
  7394. return object;
  7395. }
  7396. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine)
  7397. {
  7398. setQLCDNumberProperties(value, engine);
  7399. value.setProperty("setDisplayUnits",
  7400. engine->newFunction(TemperatureDisplay_setDisplayUnits));
  7401. }
  7402. @ There seems to be a bad interaction when enumerated value types as used as
  7403. the argument to slot methods called through QtScript. Script code that attempts
  7404. to make use of the enumeration appears to get the value without any type
  7405. information. When attempting to use that value as an argument the meta-object
  7406. system cannot find an appropriate match and the script just hangs silently.
  7407. The solution is to wrap such methods in the script bindings and explicitly cast
  7408. the argument value to the enumerated type. This looks stupid but it works.
  7409. @<Functions for scripting@>=
  7410. QScriptValue TemperatureDisplay_setDisplayUnits(QScriptContext *context, QScriptEngine *)
  7411. {
  7412. TemperatureDisplay *self = getself<@[TemperatureDisplay *@]>(context);
  7413. self->setDisplayUnits((Units::Unit)argument<int>(0, context));
  7414. return QScriptValue();
  7415. }
  7416. @* The MeasurementTimeOffset class.
  7417. When a |DAQ| object creates a |Measurement| object, the time component is a
  7418. system time. In most cases, the system time is not interesting and a more useful
  7419. time would be relative to the start of a process. This class should be used as a
  7420. filter, taking measurements with a system time stamp and producing measurements
  7421. with a relative time.
  7422. @<Class declarations@>=
  7423. class MeasurementTimeOffset : public QObject@/
  7424. {@t\1@>@/
  7425. Q_OBJECT@;
  7426. QTime epoch;
  7427. QTime previous;
  7428. bool hasPrevious;@/
  7429. public:@;
  7430. MeasurementTimeOffset(QTime zero);
  7431. QTime zeroTime();@/
  7432. @t\4@>public slots@t\kern-3pt@>:@;
  7433. void newMeasurement(Measurement measure);
  7434. void setZeroTime(QTime zero);
  7435. signals:@;
  7436. void measurement(Measurement measure);@t\2@>@/
  7437. }@t\kern-3pt@>;
  7438. @ The interesting part of this class is the function which takes a measurement
  7439. with a system time and produces a new measurement with a time relative to some
  7440. start time.
  7441. When using this class, it is possible that a measurement will arrive with a time
  7442. slightly before a newly chosen epoch. In such a case we do not want to simply
  7443. subtract the epoch from the measurement time as other classes will interpret
  7444. this incorrectly as a measurement time slightly less than 1 hour. This means
  7445. that we need to check if the measurement time is before the epoch. If it is, we
  7446. consider it to have been generated at the epoch rather than before. Aren't race
  7447. conditions fun?
  7448. Additionally, since we're only getting time of day information, some special
  7449. handling must be done for time series that cross the boundary between days. We
  7450. should never get measurements out of order, so keeping a record of the previous
  7451. measurement and verifying that the new measurement comes after it is sufficient.
  7452. @<MeasurementTimeOffset Implementation@>=
  7453. void MeasurementTimeOffset::newMeasurement(Measurement measure)@t\2\2@>@/
  7454. {@t\1@>@/
  7455. if(measure.time() < epoch)@/
  7456. {
  7457. if(hasPrevious)@/
  7458. {
  7459. QTime jitBase(epoch.hour() - 1, epoch.minute(), epoch.second(),
  7460. epoch.msec());
  7461. QTime jitComp(epoch.hour(), measure.time().minute(),
  7462. measure.time().second(), measure.time().msec());
  7463. int relTime = jitBase.msecsTo(jitComp);
  7464. @<Produce and emit relative time@>@;
  7465. }
  7466. else@/
  7467. {
  7468. Measurement rel = measure;
  7469. rel.setTime(QTime(0, 0, 0, 0));
  7470. emit measurement(rel);
  7471. }
  7472. }
  7473. else@/
  7474. {
  7475. int relTime = epoch.msecsTo(measure.time());
  7476. @<Produce and emit relative time@>@;
  7477. }
  7478. hasPrevious = true;
  7479. previous = measure.time();@t\2@>@/
  7480. }
  7481. @ The measurement emitted has a time with the number of minutes, seconds, and
  7482. milliseconds since the start of the batch. We never generate a time greater
  7483. than 1 hour.
  7484. @<Produce and emit relative time@>=
  7485. QTime newTime(0, 0, 0, 0);
  7486. newTime = newTime.addMSecs(relTime);
  7487. if(newTime.hour() > 0)
  7488. {
  7489. newTime.setHMS(0, newTime.minute(), newTime.second(), newTime.msec());
  7490. }
  7491. Measurement rel = measure;
  7492. rel.setTime(newTime);
  7493. emit measurement(rel);
  7494. @ The rest of the code handles updating and reporting the reference time.
  7495. @<MeasurementTimeOffset Implementation@>=
  7496. MeasurementTimeOffset::MeasurementTimeOffset(QTime zero) : epoch(zero),
  7497. previous(0, 0, 0, 0), hasPrevious(false)
  7498. {
  7499. /* Nothing has to be done here. */
  7500. }
  7501. QTime MeasurementTimeOffset::zeroTime()
  7502. {
  7503. return epoch;
  7504. }
  7505. void MeasurementTimeOffset::setZeroTime(QTime zero)
  7506. {
  7507. epoch = zero;
  7508. hasPrevious = false;
  7509. }
  7510. @ Two functions are required to make this class available to the scripting
  7511. engine.
  7512. @<Function prototypes for scripting@>=
  7513. QScriptValue constructMeasurementTimeOffset(QScriptContext *context,@|
  7514. QScriptEngine *engine);
  7515. void setMeasurementTimeOffsetProperties(QScriptValue value,
  7516. QScriptEngine *engine);
  7517. @ The scripting engine must be informed of the constructor.
  7518. @<Set up the scripting engine@>=
  7519. constructor = engine->newFunction(constructMeasurementTimeOffset);
  7520. value = engine->newQMetaObject(&MeasurementTimeOffset::staticMetaObject,
  7521. constructor);
  7522. engine->globalObject().setProperty("MeasurementTimeOffset", value);
  7523. @ Previously, another property was added to the newly created object. That
  7524. method is believed to be obsolete and has been removed. Careful testing will
  7525. need to be done to verify that this decision was sane. I was very hungry when
  7526. that change was made.
  7527. @<Functions for scripting@>=
  7528. QScriptValue constructMeasurementTimeOffset(QScriptContext *,
  7529. QScriptEngine *engine)
  7530. {
  7531. QScriptValue object =@|
  7532. engine->newQObject(new MeasurementTimeOffset(QTime::currentTime()));
  7533. setMeasurementTimeOffsetProperties(object, engine);
  7534. return object;
  7535. }
  7536. void setMeasurementTimeOffsetProperties(QScriptValue value,
  7537. QScriptEngine *engine)
  7538. {
  7539. setQObjectProperties(value, engine);
  7540. }
  7541. @* Measured value threshold detection.
  7542. \noindent There are times when one might want to detect when a measured value
  7543. from a data series has passed a given value, with the limitation that we are
  7544. only interested in the ascending or descending edge. This can be used, for
  7545. example, to translate roast profile data in a graph along the time axis such
  7546. that the bean temperature series are aligned at a given
  7547. temperature.\nfnote{More details on the reasoning behind why one might want
  7548. to do this are provided at:\par\indent\pdfURL{http://youtu.be/hS0SfzypyFQ}
  7549. {http://youtu.be/hS0SfzypyFQ}} For this we can use a |ThresholdDetector|.
  7550. If we would like to catch changes on both the ascending and descending edge, we
  7551. can use two objects, however it may be a good idea to use more than two to
  7552. allow for sane behavior in the face of hysteresis.
  7553. @<Class declarations@>=
  7554. class ThresholdDetector : public QObject@/
  7555. {
  7556. @[Q_OBJECT@]@;
  7557. @[Q_ENUMS(EdgeDirection)@]@;
  7558. public:@/
  7559. enum EdgeDirection {
  7560. Ascending, Descending
  7561. };
  7562. ThresholdDetector(double value);
  7563. @[public slots@]:@/
  7564. void newMeasurement(Measurement measure);
  7565. void setThreshold(double value);
  7566. void setEdgeDirection(EdgeDirection direction);
  7567. signals:@/
  7568. void timeForValue(double);
  7569. private:@/
  7570. bool previousValueValid;
  7571. double previousValue;
  7572. double threshold;
  7573. EdgeDirection currentDirection;
  7574. };
  7575. @ This class emits the time in seconds when a given measurement crosses the
  7576. threshold value in the appropriate direction.
  7577. This was previously written with |previousValue| initialized negative and a
  7578. check that |previousValue| was non-negative. When the |ThresholdDetector| is
  7579. connected to a data source representing temperature measurements this is a
  7580. reasonable choice, however it breaks when connected to a rate of change series.
  7581. To make this more generally correct, a boolean is checked to determine if a
  7582. previous value has been set.
  7583. @<ThresholdDetector Implementation@>=
  7584. void ThresholdDetector::newMeasurement(Measurement measure)
  7585. {
  7586. if((currentDirection == Ascending && previousValue < threshold &&
  7587. previousValueValid) || (currentDirection == Descending &&
  7588. previousValue > threshold && previousValueValid))
  7589. {
  7590. if((currentDirection == Ascending && measure.temperature() >= threshold) ||
  7591. (currentDirection == Descending && measure.temperature() <= threshold))
  7592. {
  7593. double offset = measure.time().hour() * 60 * 60;
  7594. offset += measure.time().minute() * 60;
  7595. offset += measure.time().second();
  7596. offset += measure.time().msec()/1000;
  7597. emit timeForValue(offset);
  7598. }
  7599. }
  7600. previousValue = measure.temperature();
  7601. previousValueValid = true;
  7602. }
  7603. ThresholdDetector::ThresholdDetector(double value) : QObject(NULL),
  7604. previousValueValid(false),
  7605. previousValue(-1), threshold(value), currentDirection(Ascending)
  7606. {
  7607. /* Nothing needs to be done here. */
  7608. }
  7609. void ThresholdDetector::setThreshold(double value)
  7610. {
  7611. threshold = value;
  7612. }
  7613. void ThresholdDetector::setEdgeDirection(EdgeDirection direction)
  7614. {
  7615. currentDirection = direction;
  7616. }
  7617. @ This is exposed to the host environment.
  7618. @<Function prototypes for scripting@>=
  7619. QScriptValue constructThresholdDetector(QScriptContext *context, QScriptEngine *engine);
  7620. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine);
  7621. @ Inform the engine of the constructor.
  7622. @<Set up the scripting engine@>=
  7623. constructor = engine->newFunction(constructThresholdDetector);
  7624. value = engine->newQMetaObject(&ThresholdDetector::staticMetaObject, constructor);
  7625. engine->globalObject().setProperty("ThresholdDetector", value);
  7626. @ Implementation. At present I'@q'@>m not bothering to implement constructor
  7627. arguments here and am aligning on a fixed point. Another slot method was added
  7628. to restore adjustability.
  7629. @<Functions for scripting@>=
  7630. QScriptValue constructThresholdDetector(QScriptContext *, QScriptEngine *engine)
  7631. {
  7632. QScriptValue object = engine->newQObject(new ThresholdDetector(300));
  7633. return object;
  7634. }
  7635. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine)
  7636. {
  7637. setQObjectProperties(value, engine);
  7638. }
  7639. @* The ZeroEmitter class.
  7640. \noindent Now that it is possible to record the time a measurement was taken
  7641. relative to an arbitrary start time, there is a minor problem left for logging.
  7642. It is extremely unlikely that a measurement will be passed through at the epoch.
  7643. For this, what we want to do is save the previous measurement and make it
  7644. available at time 0 whenever the start time is reset. This is the role of the
  7645. |ZeroEmitter| class.
  7646. Another problem is that most classes that are interested in a relative time are
  7647. also interested in logging multiple sets of temperature data. To facilitate this
  7648. an integer is emitted. Different temperature measurement sources should be set
  7649. to emit different numbers. A table view would place measurements in the
  7650. indicated column. A graph view would use different colors to plot different sets
  7651. of data.
  7652. @<Class declarations@>=
  7653. class ZeroEmitter : public QObject@/
  7654. {@t\1@>@/
  7655. @[Q_OBJECT@]@;
  7656. @[Q_PROPERTY(int column READ column WRITE setColumn)@]@;
  7657. Measurement cache;
  7658. int col;
  7659. public:@/
  7660. ZeroEmitter(int tempcolumn = 1);
  7661. int column();
  7662. double lastTemperature();@/
  7663. @t\4@>public slots@t\kern-3pt@>:@;
  7664. void newMeasurement(Measurement measure);
  7665. void setColumn(int column);
  7666. void emitZero();
  7667. signals:@;
  7668. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  7669. }@t\kern-3pt@>;
  7670. @ The implementation of the class is trivial.
  7671. @<ZeroEmitter Implementation@>=
  7672. ZeroEmitter::ZeroEmitter(int tempcolumn) : QObject(NULL), col(tempcolumn)@;
  7673. {
  7674. /* Nothing has to be done here. */
  7675. }
  7676. int ZeroEmitter::column()
  7677. {
  7678. return col;
  7679. }
  7680. double ZeroEmitter::lastTemperature()
  7681. {
  7682. return cache.temperature();
  7683. }
  7684. void ZeroEmitter::newMeasurement(Measurement measure)
  7685. {
  7686. cache = measure;
  7687. }
  7688. void ZeroEmitter::setColumn(int column)
  7689. {
  7690. col = column;
  7691. }
  7692. void ZeroEmitter::emitZero()
  7693. {
  7694. cache.setTime(QTime(0, 0, 0, 0));
  7695. emit measurement(cache, col);
  7696. }
  7697. @ Making this class available to scripts requires only two functions.
  7698. @<Function prototypes for scripting@>=
  7699. QScriptValue constructZeroEmitter(QScriptContext *context,
  7700. QScriptEngine *engine);
  7701. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine);
  7702. @ To use it, we must inform the engine of the constructor.
  7703. @<Set up the scripting engine@>=
  7704. constructor = engine->newFunction(constructZeroEmitter);
  7705. value = engine->newQMetaObject(&ZeroEmitter::staticMetaObject, constructor);
  7706. engine->globalObject().setProperty("ZeroEmitter", value);
  7707. @ The implementation of the constructor is trivial.
  7708. @<Functions for scripting@>=
  7709. QScriptValue constructZeroEmitter(QScriptContext *context,
  7710. QScriptEngine *engine)
  7711. {
  7712. QScriptValue object =
  7713. engine->newQObject(new ZeroEmitter(argument<int>(0, context)));
  7714. setZeroEmitterProperties(object, engine);
  7715. return object;
  7716. }
  7717. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine)
  7718. {
  7719. setQObjectProperties(value, engine);
  7720. }
  7721. @* The MeasurementAdapter class.
  7722. \noindent The last of the measurement filter classes is the |MeasurementAdapter|
  7723. class. This takes measurements, typically from a |MeasurementTimeOffset|, and
  7724. sends the measurement out with a number to indicate which data series the
  7725. measurement belongs to.
  7726. The measurement pipeline could probably be made simpler by introducing a series
  7727. identifier into the measurement class.
  7728. @<Class declarations@>=
  7729. class MeasurementAdapter : public QObject@/
  7730. {@t\1@>@/
  7731. Q_OBJECT@;
  7732. int col;
  7733. public:@/
  7734. MeasurementAdapter(int tempcolumn);
  7735. int column();@/
  7736. @t\4@>public slots@t\kern-3pt@>:@/
  7737. void newMeasurement(Measurement measure);
  7738. void setColumn(int column);
  7739. signals:@/
  7740. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  7741. }@t\kern-3pt@>;
  7742. @ The implementation of this filter class is trivial.
  7743. @<MeasurementAdapter Implementation@>=
  7744. MeasurementAdapter::MeasurementAdapter(int tempcolumn) : col(tempcolumn)@;
  7745. {
  7746. /* Nothing has to be done here. */
  7747. }
  7748. int MeasurementAdapter::column()
  7749. {
  7750. return col;
  7751. }
  7752. void MeasurementAdapter::newMeasurement(Measurement measure)
  7753. {
  7754. emit measurement(measure, col);
  7755. }
  7756. void MeasurementAdapter::setColumn(int column)
  7757. {
  7758. col = column;
  7759. }
  7760. @ This filter class is also available from the host environment.
  7761. @<Function prototypes for scripting@>=
  7762. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  7763. QScriptEngine *engine);
  7764. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine);
  7765. @ As usual, the engine must be informed of the constructor.
  7766. @<Set up the scripting engine@>=
  7767. constructor = engine->newFunction(constructMeasurementAdapter);
  7768. value = engine->newQMetaObject(&MeasurementAdapter::staticMetaObject,
  7769. constructor);
  7770. engine->globalObject().setProperty("MeasurementAdapter", value);
  7771. @ The implementation is trivial.
  7772. @<Functions for scripting@>=
  7773. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  7774. QScriptEngine *engine)
  7775. {
  7776. QScriptValue object =
  7777. engine->newQObject(new MeasurementAdapter(argument<int>(0, context)));
  7778. setMeasurementAdapterProperties(object, engine);
  7779. return object;
  7780. }
  7781. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine)
  7782. {
  7783. setQObjectProperties(value, engine);
  7784. }
  7785. @* A graph of temperature over time.
  7786. \noindent A useful tool when roasting is a visual depiction of the current batch
  7787. as it happens, possibly laid over a previously recorded target profile. The
  7788. |GraphView| class can take multiple sets of temperature data and produce such a
  7789. visualization.
  7790. \medskip
  7791. \centerline{\includegraphics{roast}}
  7792. \smallskip
  7793. \centerline{Figure \secno: A Typical Roast}
  7794. \medskip
  7795. This class assumes that temperature data will be passed in the correct order.
  7796. @<Class declarations@>=
  7797. class GraphView : public QGraphicsView@/
  7798. {@t\1@>@/
  7799. Q_OBJECT@;
  7800. QGraphicsScene *theScene;@/
  7801. QMap<int, QList<QGraphicsLineItem * > * > *graphLines;@/
  7802. QMap<int, QPointF> *prevPoints;
  7803. QMap<int, double> *translations;
  7804. QList<QGraphicsItem *> *gridLinesF;
  7805. QList<QGraphicsItem *> *gridLinesC;
  7806. QList<QGraphicsItem *> *relativeGridLines;
  7807. bool relativeEnabled;
  7808. bool timeIndicatorEnabled;
  7809. QGraphicsLineItem *timeLine;
  7810. LinearSplineInterpolator *relativeAdjuster;@/
  7811. public:@/
  7812. GraphView(QWidget *parent = NULL);
  7813. void removeSeries(int column);@/
  7814. protected:@/
  7815. void resizeEvent(QResizeEvent *event);@/
  7816. @t\4@>public slots@t\kern-3pt@>:@/
  7817. void newMeasurement(Measurement measure, int tempcolumn);
  7818. void setSeriesTranslation(int column, double offset);
  7819. void setTimeIndicatorEnabled(bool enabled);
  7820. void clear();
  7821. void showF();
  7822. void showC();@t\2@>@/
  7823. }@t\kern-3pt@>;
  7824. @ I decided that it would probably be best to keep the graph area the same even
  7825. with different roast lengths over different temperature ranges so that similar
  7826. portions between these graphs would continue to look similar rather than
  7827. constantly attempting to select the best way to display the data currently in
  7828. the view.
  7829. I have chosen to represent roasting times of up to 20 minutes and temperatures
  7830. between 0 and 500$^\circ$ Fahrenheit. This should certainly be configurable at
  7831. run time, but until that is implemented, roasters who routinely roast batches
  7832. for longer periods of time will want to change the constructor. This class
  7833. should probably be modified to allow the user to specify several characteristics
  7834. of the display.
  7835. This class must also deal with the fact that coordinates in a |QGraphicsScene|
  7836. are not quite the same as coordinates in a cartesian plane. The easiest way to
  7837. deal with this is to negate the y coordinate and translate the viewport to the
  7838. area we draw in.
  7839. A small margin area left around the edges of the graph. This should probably be
  7840. configurable for those with particularly small displays.
  7841. @<GraphView Implementation@>=
  7842. GraphView::GraphView(QWidget *parent) : QGraphicsView(parent),
  7843. theScene(new QGraphicsScene),@/
  7844. graphLines(new QMap<int, QList<QGraphicsLineItem *> *>),@/
  7845. prevPoints(new QMap<int, QPointF>),
  7846. translations(new QMap<int, double>),
  7847. gridLinesF(new QList<QGraphicsItem *>),
  7848. gridLinesC(new QList<QGraphicsItem *>),
  7849. relativeGridLines(new QList<QGraphicsItem *>),
  7850. relativeEnabled(false),
  7851. timeIndicatorEnabled(false),
  7852. timeLine(new QGraphicsLineItem),
  7853. relativeAdjuster(new LinearSplineInterpolator)@/
  7854. {
  7855. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  7856. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  7857. setScene(theScene);
  7858. setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
  7859. QPen timePen;
  7860. timePen.setColor(QColor(160, 160, 164, 127)); //gray, half opacity
  7861. timeLine->setPen(timePen);
  7862. timeLine->setLine(0, 0, 0, -500);
  7863. timeLine->hide();
  7864. theScene->addItem(timeLine);
  7865. @<Draw temperature axis and grid lines@>;
  7866. @<Draw secondary axes@>@;
  7867. @<Draw time axis and ticks@>;
  7868. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  7869. }
  7870. @ Grid lines are drawn every 100 degrees. These lines are labeled with
  7871. |setHtml()| for convenient access to the $^\circ$ symbol. If \pn{} is modified
  7872. to allow different units, this code should also be modified.
  7873. As of version 1.3.3 it is possible to switch the graph between degrees
  7874. Fahrenheit and degrees Celcius. Celcius grid lines are drawn but initially
  7875. hidden. Both the grid lines and the labels are added to a list depending on the
  7876. unit so that when changing from one view to another all that needs to happen is
  7877. hide one list of items and show another.
  7878. @<Draw temperature axis and grid lines@>=
  7879. QGraphicsLineItem *tempaxis = new QGraphicsLineItem;
  7880. tempaxis->setLine(-10, -500, -10, 0);
  7881. theScene->addItem(tempaxis);
  7882. QGraphicsLineItem *gridLine;
  7883. QGraphicsTextItem *label;
  7884. for(int y = -100; y > -600; y -= 100)@/
  7885. {@/
  7886. gridLine = new QGraphicsLineItem;
  7887. gridLine->setLine(0, y, 1200, y);
  7888. theScene->addItem(gridLine);
  7889. label = new QGraphicsTextItem;
  7890. label->setHtml(QString("%1&deg;F").arg(-y));
  7891. label->setPos(-55, y - (label->boundingRect().height() / 2));
  7892. theScene->addItem(label);
  7893. gridLinesF->append(gridLine);
  7894. gridLinesF->append(label);
  7895. }
  7896. for(int degC = 50; degC <= 250; degC += 50)
  7897. {
  7898. gridLine = new QGraphicsLineItem;
  7899. int y = -(degC * (9.0/5.0) + 32);
  7900. gridLine->setLine(0, y, 1200, y);
  7901. gridLine->hide();
  7902. theScene->addItem(gridLine);
  7903. gridLinesC->append(gridLine);
  7904. label = new QGraphicsTextItem;
  7905. label->setHtml(QString("%1&deg;C").arg(degC));
  7906. label->setPos(-55, y - (label->boundingRect().height() / 2));
  7907. label->hide();
  7908. theScene->addItem(label);
  7909. gridLinesC->append(label);
  7910. }
  7911. @ If we are going to plot relative temperature measurements, we must obtain
  7912. information on how we wish to do that from settings. We take advantage of the
  7913. fact that iterating over the keys in a |QMap| produces results in sorted order.
  7914. While drawing the grid lines we also set up the |relativeAdjuster| that will be
  7915. used to transform incoming measurements to our coordinate system.
  7916. @<Draw secondary axes@>=
  7917. QSettings settings;
  7918. if(settings.contains("settings/graph/relative/enable"))
  7919. {
  7920. if(settings.value("settings/graph/relative/enable").toBool())
  7921. {
  7922. relativeEnabled = @[true@];
  7923. QColor relativeColor = QColor(settings.value("settings/graph/relative/color").toString());
  7924. QString unit = QString(settings.value(@|"settings/graph/relative/unit").toInt() == 0 ? "F" : "C");
  7925. QMap<double, QString> relativeAxisPairs;
  7926. QStringList relativeAxisLabels = settings.value(@|"settings/graph/relative/grid").toString().split(QRegExp("[\\s,]+"), QString::SkipEmptyParts);
  7927. foreach(QString item, relativeAxisLabels)
  7928. {
  7929. relativeAxisPairs.insert(item.toDouble(), item);
  7930. }
  7931. if(relativeAxisPairs.size() > 1)
  7932. {
  7933. double skip = 500.0 / (relativeAxisPairs.size() - 1);
  7934. double y = 0;
  7935. foreach(double key, relativeAxisPairs.keys())
  7936. {
  7937. gridLine = new QGraphicsLineItem;
  7938. gridLine->setLine(0, y, 1205, y);
  7939. gridLine->setPen(QPen(relativeColor));
  7940. theScene->addItem(gridLine);
  7941. relativeGridLines->append(gridLine);
  7942. label = new QGraphicsTextItem;
  7943. label->setHtml(QString("%1&deg;%2").arg(relativeAxisPairs.value(key)).arg(unit));
  7944. label->setPos(1210, y - (label->boundingRect().height() / 2));
  7945. theScene->addItem(label);
  7946. relativeGridLines->append(label);
  7947. if(unit == "F")
  7948. {
  7949. relativeAdjuster->add_pair(key, -y);
  7950. }
  7951. else
  7952. {
  7953. relativeAdjuster->add_pair(key * (9.0/5.0), -y);
  7954. }
  7955. y -= skip;
  7956. }
  7957. }
  7958. }
  7959. }
  7960. @ Two slots are used to switch between the different sets of grid lines.
  7961. @<GraphView Implementation@>=
  7962. void GraphView::showF()
  7963. {
  7964. for(int i = 0; i < gridLinesF->size(); i++)
  7965. {
  7966. gridLinesF->at(i)->show();
  7967. }
  7968. for(int i = 0; i < gridLinesC->size(); i++)
  7969. {
  7970. gridLinesC->at(i)->hide();
  7971. }
  7972. }
  7973. void GraphView::showC()
  7974. {
  7975. for(int i = 0; i < gridLinesF->size(); i++)
  7976. {
  7977. gridLinesF->at(i)->hide();
  7978. }
  7979. for(int i = 0; i < gridLinesC->size(); i++)
  7980. {
  7981. gridLinesC->at(i)->show();
  7982. }
  7983. }
  7984. @ The time axis has a tick every two minutes. The use of the |?| tertiary
  7985. operator shifts the labels with two digits a little more than labels with only
  7986. one digit. If it worked, a more resilient approach would be to take the width of
  7987. the label and center it under the tick.
  7988. @<Draw time axis and ticks@>=
  7989. QGraphicsLineItem *timeaxis = new QGraphicsLineItem;
  7990. timeaxis->setLine(0, 10, 1200, 10);
  7991. theScene->addItem(timeaxis);
  7992. for(int x = 0; x < 1201; x += 120)@/
  7993. {@/
  7994. QGraphicsLineItem *tick = new QGraphicsLineItem;
  7995. tick->setLine(x, 0, x, 20);
  7996. theScene->addItem(tick);
  7997. QGraphicsTextItem *label = new QGraphicsTextItem;
  7998. label->setPlainText(QString("%1").arg(x/60));
  7999. label->setPos(x - (label->boundingRect().width() / 2), 20);
  8000. theScene->addItem(label);
  8001. }
  8002. @ Typically, the user will be able to resize the graph. When the widget is
  8003. resized, we should fit the graph to the new size of the widget. This is safe to
  8004. do as we have already turned off the scroll bars.
  8005. @<GraphView Implementation@>=
  8006. void GraphView::resizeEvent(QResizeEvent *)
  8007. {
  8008. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  8009. }
  8010. @ When adding a new measurement, there are three cases that should be
  8011. considered. In the case of the first measurement, no drawing occurs. A |QList|
  8012. of line items is initialized when the second measurement is taken. Subsequent
  8013. measurements are able to simply append new line segments to the list.
  8014. Relative measurements are first converted to the coordinate system of the
  8015. appropriate secondary axis.
  8016. @<GraphView Implementation@>=
  8017. #define FULLTIMETOINT(t) (t.msec() + (t.second() * 1000) + (t.minute() * 60 * 1000))
  8018. void GraphView::newMeasurement(Measurement measure, int tempcolumn)@/
  8019. {@/
  8020. double offset = 0;
  8021. if(measure.contains("relative"))
  8022. {
  8023. if(measure.value("relative").toBool())
  8024. {
  8025. if(relativeEnabled)
  8026. {
  8027. measure.setTemperature(relativeAdjuster->newMeasurement(measure).temperature());
  8028. }
  8029. else
  8030. {
  8031. return;
  8032. }
  8033. }
  8034. }
  8035. if(translations->contains(tempcolumn))
  8036. {
  8037. offset = translations->value(tempcolumn);
  8038. }
  8039. if(prevPoints->contains(tempcolumn))@/
  8040. @t\1@>{@/
  8041. @<At least one measurement exists@>@;
  8042. if(graphLines->contains(tempcolumn))@/
  8043. {@t\1@>
  8044. /* More than one measurement existed. */
  8045. graphLines->value(tempcolumn)->append(segment);@t\2@>@/
  8046. }@/
  8047. else@/
  8048. {@/
  8049. /* This is the second measurement. */
  8050. QList<QGraphicsLineItem *> *newLine =
  8051. new QList<QGraphicsLineItem *>;@/
  8052. newLine->append(segment);
  8053. graphLines->insert(tempcolumn, newLine);
  8054. }@t\2@>@/
  8055. }@/
  8056. else@/
  8057. {@/
  8058. @<Handle the first measurement@>@;
  8059. }
  8060. }
  8061. @ There are some parts of the code that are correct, but seem somewhat goofy.
  8062. This is especially true surrounding the graphics view architecture as this was
  8063. not working correctly when I wrote the code that uses it. The code as it is
  8064. written works for me, but when these workarounds are no longer needed it would
  8065. be better to remove them. Handling values on the time axis is one example of
  8066. this.
  8067. Some might question the use of an integer data type, particularly when storing
  8068. the result of a division operation. While this could be a concern if high
  8069. resolution wall sized displays become common, is is expected that in most cases
  8070. with sufficiently high sample rates, many data points will map to the same pixel
  8071. even with the minor data loss below.
  8072. In the case of the first measurement,
  8073. @<Handle the first measurement@>=
  8074. int x = FULLTIMETOINT(measure.time())/1000;
  8075. prevPoints->insert(tempcolumn, QPointF(x, measure.temperature()));
  8076. if(timeIndicatorEnabled)
  8077. {
  8078. timeLine->setLine(x, 0, x, -500);
  8079. }
  8080. @ When at least one measurement already exists, we need to handle drawing the
  8081. line between the new measurement and the previous measurement.
  8082. \danger At present, the color chosen for these lines is based on the temperature
  8083. column passed to the graph. It would be better if colors could be passed to the
  8084. view for a specified series rather than have this hard coded. \endanger
  8085. @<At least one measurement exists@>=
  8086. QGraphicsLineItem *segment = new QGraphicsLineItem;
  8087. QPointF nextPoint(FULLTIMETOINT(measure.time())/1000, measure.temperature());
  8088. segment->setLine(prevPoints->value(tempcolumn).x() + offset,
  8089. -(prevPoints->value(tempcolumn).y()),
  8090. nextPoint.x() + offset, -(nextPoint.y()));
  8091. static QColor p[12] = {Qt::yellow, Qt::blue, Qt::cyan, Qt::red, Qt::magenta,
  8092. Qt::green, Qt::darkGreen, Qt::darkMagenta,
  8093. Qt::darkRed, Qt::darkCyan, Qt::darkBlue,
  8094. Qt::darkYellow};
  8095. segment->setPen(p[tempcolumn % 12]);
  8096. theScene->addItem(segment);
  8097. prevPoints->insert(tempcolumn, nextPoint);
  8098. if(timeIndicatorEnabled)
  8099. {
  8100. timeLine->setLine(nextPoint.x() + offset, 0, nextPoint.x() + offset, -500);
  8101. }
  8102. @ In addition to adding data to the view, we also sometimes want to clear the
  8103. view of data.
  8104. @<GraphView Implementation@>=
  8105. void GraphView::clear()
  8106. {
  8107. int i;
  8108. foreach(i, prevPoints->keys())
  8109. {
  8110. removeSeries(i);
  8111. }
  8112. translations->clear();
  8113. }
  8114. @ Removing a set of data from the view involves removing the lines from the
  8115. scene and removing the column from a couple data structures.
  8116. @<GraphView Implementation@>=
  8117. void GraphView::removeSeries(int column)
  8118. {
  8119. if(graphLines->contains(column))
  8120. {
  8121. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  8122. QGraphicsLineItem *segment;
  8123. foreach(segment, *series)
  8124. {
  8125. theScene->removeItem(segment);
  8126. }
  8127. qDeleteAll(*series);
  8128. }
  8129. graphLines->remove(column);
  8130. prevPoints->remove(column);
  8131. }
  8132. @ Second prototype for data series translation.
  8133. @<GraphView Implementation@>=
  8134. void GraphView::setSeriesTranslation(int column, double offset)
  8135. {
  8136. if(graphLines->contains(column))
  8137. {
  8138. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  8139. QGraphicsLineItem *segment;
  8140. foreach(segment, *series)
  8141. {
  8142. segment->setPos(segment->pos().x()+offset, segment->pos().y());
  8143. }
  8144. }
  8145. if(translations->contains(column))
  8146. {
  8147. translations->insert(column, offset + translations->value(column));
  8148. }
  8149. else
  8150. {
  8151. translations->insert(column, offset);
  8152. }
  8153. }
  8154. @ Starting in \pn{} 1.6 it is possible to add a vertical line indicating the
  8155. time position of the most recent measurement. This should be hidden for loading
  8156. target roast profiles and shown depending on preference. A new method controls
  8157. this.
  8158. @<GraphView Implementation@>=
  8159. void GraphView::setTimeIndicatorEnabled(bool enabled)
  8160. {
  8161. timeIndicatorEnabled = enabled;
  8162. if(enabled)
  8163. {
  8164. timeLine->show();
  8165. }
  8166. else
  8167. {
  8168. timeLine->hide();
  8169. }
  8170. }
  8171. @ These functions are required to create a |GraphView| object from a script.
  8172. @<Function prototypes for scripting@>=
  8173. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine);
  8174. QScriptValue constructGraphView(QScriptContext *context, QScriptEngine *engine);
  8175. @ The scripting engine must be informed of the constructor.
  8176. @<Set up the scripting engine@>=
  8177. constructor = engine->newFunction(constructGraphView);
  8178. value = engine->newQMetaObject(&GraphView::staticMetaObject, constructor);
  8179. engine->globalObject().setProperty("GraphView", value);
  8180. @ The function implementation is trivial.
  8181. @<Functions for scripting@>=
  8182. QScriptValue constructGraphView(QScriptContext *, QScriptEngine *engine)
  8183. {
  8184. QScriptValue object = engine->newQObject(new GraphView);
  8185. setGraphViewProperties(object, engine);
  8186. return object;
  8187. }
  8188. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine)
  8189. {
  8190. setQGraphicsViewProperties(value, engine);
  8191. }
  8192. @* A table of roasting data.
  8193. \noindent A typical roast log is a table listing temperature measurements taken
  8194. at regular intervals. The introduction of a computer brings several advantages.
  8195. A human does not need to record the measurements. Every measurement taken can be
  8196. logged, but the measurements do not all need to be displayed. The |ZoomLog|
  8197. class presents a table with time, temperature, and annotation for one or more
  8198. sets of roasting data and allows the user to select from a few different levels
  8199. of detail.
  8200. Experience has shown that one measurement every 30 or 15 seconds is most useful,
  8201. but it is also possible to view one measurement every 1, 5, 10, or 60 seconds
  8202. and there is an option to view every measurement collected. This last is what is
  8203. saved to a file.
  8204. The zooming log is implemented by keeping a measurement model with every level
  8205. of detail of interest and making sure that new measurements get to the models
  8206. they belong in. Switching the level of detail of the view then becomes a matter
  8207. of changing which model the view is using. This is very inefficient in terms of
  8208. space, but it is very fast and simple to code.
  8209. Starting in version 1.4, column sizes are persisted automatically using the
  8210. same method as described in the section on |SqlQueryView|.
  8211. Starting in version 1.8, |rowCount()| is |Q_INVOKABLE|. This allows the manual
  8212. log entry interface to easily determine if any roasting data exists to save.
  8213. @<Class declarations@>=
  8214. class MeasurementModel;@/
  8215. class ZoomLog : public QTableView@/
  8216. {@/
  8217. @[Q_OBJECT@]@;
  8218. @<ZoomLog private member data@>@;
  8219. void switchLOD(MeasurementModel *m);@/
  8220. @[private slots@]:@/
  8221. void centerOn(int row);
  8222. void persistColumnResize(int column, int oldsize, int newsize);
  8223. void restoreColumnWidths();
  8224. public:@/
  8225. ZoomLog();
  8226. QVariant data(int row, int column) const;
  8227. @[Q_INVOKABLE@,@, int rowCount();
  8228. bool saveXML(QIODevice *device);
  8229. bool saveCSV(QIODevice *device);
  8230. QString lastTime(int series);
  8231. @[Q_INVOKABLE@,@, Units::Unit displayUnits()@];@t\2\2@>@/
  8232. @[public slots@]:@/
  8233. void setVisible(bool visibility);
  8234. void setHeaderData(int section, QString text);
  8235. void LOD_ms();
  8236. void LOD_1s();
  8237. void LOD_5s();
  8238. void LOD_10s();
  8239. void LOD_15s();
  8240. void LOD_30s();
  8241. void LOD_1m();
  8242. void newMeasurement(Measurement measure, int tempcolumn);
  8243. void newAnnotation(QString annotation, int tempcolumn,
  8244. int annotationcolumn);
  8245. void clear();
  8246. void addOutputTemperatureColumn(int column);
  8247. void addOutputControlColumn(int column);
  8248. void addOutputAnnotationColumn(int column);
  8249. void clearOutputColumns();
  8250. void setDisplayUnits(Units::Unit scale);
  8251. void addToCurrentColumnSet(int column);
  8252. void clearCurrentColumnSet();@/
  8253. protected:@/
  8254. virtual void showEvent(QShowEvent *event);
  8255. };
  8256. @ This class uses a different model for each level of detail and provides logic
  8257. for placing measurements and annotations in the appropriate models. A list of
  8258. each model is provided for conveniently performing operations that apply to
  8259. every model.
  8260. @<ZoomLog private member data@>=
  8261. MeasurementModel *model_ms;
  8262. MeasurementModel *model_1s;
  8263. MeasurementModel *model_5s;
  8264. MeasurementModel *model_10s;
  8265. MeasurementModel *model_15s;
  8266. MeasurementModel *model_30s;
  8267. MeasurementModel *model_1m;
  8268. QList<MeasurementModel *> modelSet;
  8269. QHash<int, Measurement> lastMeasurement;
  8270. MeasurementModel *currentModel;
  8271. QList<int> saveTempCols;
  8272. QList<int> saveControlCols;
  8273. QList<int> saveNoteCols;
  8274. QList<int> currentColumnSet;
  8275. @ Most of the functionality this class provides is in getting measurements to
  8276. the right models. Every measurement goes to the full detail model. We also keep
  8277. track of the most recent measurement to detect the first measurement in a new
  8278. second and pass all of these on to the 1 second level of detail model. Some of
  8279. these are also passed to other models. Additionally, the models that store
  8280. coarser data strip the millisecond portion of the time.
  8281. A decision was made to present data promptly. With a high sample rate, some
  8282. might prefer an average of a few measurements near the reported time, but such
  8283. a feature does not exist in \pn{} currently.
  8284. The first measurement is always added to each model.
  8285. @<ZoomLog Implementation@>=
  8286. void ZoomLog::newMeasurement(Measurement measure, int tempcolumn)
  8287. {
  8288. if(measure.time() != QTime(0, 0, 0, 0))
  8289. {
  8290. @<Synthesize measurements for slow hardware@>@;
  8291. }
  8292. model_ms->newMeasurement(measure, tempcolumn);
  8293. if(lastMeasurement.contains(tempcolumn))
  8294. {
  8295. if(measure.time().second() !=
  8296. lastMeasurement.value(tempcolumn).time().second())
  8297. {
  8298. Measurement adjusted = measure;
  8299. QTime adjtime(0, measure.time().minute(), measure.time().second(), 0);
  8300. adjusted.setTime(adjtime);
  8301. model_1s->newMeasurement(adjusted, tempcolumn);
  8302. if(adjusted.time().second() % 5 == 0)
  8303. {
  8304. model_5s->newMeasurement(adjusted, tempcolumn);
  8305. if(adjusted.time().second() % 10 == 0)
  8306. {
  8307. model_10s->newMeasurement(adjusted, tempcolumn);
  8308. }
  8309. if(adjusted.time().second() % 15 == 0)
  8310. {
  8311. model_15s->newMeasurement(adjusted, tempcolumn);
  8312. if(adjusted.time().second() % 30 == 0)
  8313. {
  8314. model_30s->newMeasurement(adjusted, tempcolumn);
  8315. if(adjusted.time().second() == 0)
  8316. {
  8317. model_1m->newMeasurement(adjusted, tempcolumn);
  8318. }
  8319. }
  8320. }
  8321. }
  8322. }
  8323. @<Synthesize measurements for columns in set@>@;
  8324. }
  8325. else
  8326. {
  8327. @<Add the first measurement to every model@>@;
  8328. }
  8329. lastMeasurement.insert(tempcolumn, measure);
  8330. }
  8331. @ The first measurement in a series should be the epoch measurement. This
  8332. should exist in every level of detail.
  8333. @<Add the first measurement to every model@>=
  8334. MeasurementModel *m;
  8335. foreach(m, modelSet)
  8336. {
  8337. m->newMeasurement(measure, tempcolumn);
  8338. }
  8339. @ Some measurement hardware in use cannot guarantee delivery of at least one
  8340. measurement per second. This causes problems for the current |ZoomLog|
  8341. implementation as, for example, if there is no measurement at a time where
  8342. the seconds are divisible by 5, there will be no entry in that view. This can
  8343. result in situations where the |ZoomLog| at its default view of one measurement
  8344. every 30 seconds might not display any data at all aside from the first
  8345. measurement, the last measurement, and any measurement that happens to have an
  8346. annotation associated with it. The solution in this case is to synthesize
  8347. measurements so that the |ZoomLog| thinks it gets at least one measurement
  8348. every second.
  8349. Prior to version 1.8 this simply replicated the last measurement every second
  8350. until the time for the most recent measurement was reached, however this yields
  8351. problematic results when loading saved data or attempting to use this view for
  8352. manual data entry. The current behavior performs a linear interpolation which
  8353. will match the graph.
  8354. @<Synthesize measurements for slow hardware@>=
  8355. if(lastMeasurement.contains(tempcolumn))
  8356. {
  8357. if(lastMeasurement[tempcolumn].time() < measure.time())
  8358. {
  8359. QList<QTime> timelist;
  8360. QList<double> templist;
  8361. QTime z = QTime(0, 0, 0, 0);
  8362. double ptime = (double)(z.secsTo(lastMeasurement[tempcolumn].time()));
  8363. double ptemp = lastMeasurement[tempcolumn].temperature();
  8364. double ctime = (double)(z.secsTo(measure.time()));
  8365. double ctemp = measure.temperature();
  8366. for(QTime i = lastMeasurement.value(tempcolumn).time().addSecs(1); i < measure.time(); i = i.addSecs(1))
  8367. {
  8368. timelist.append(i);
  8369. double v = ((ptemp * (ctime - z.secsTo(i))) + (ctemp * (z.secsTo(i) - ptime))) / (ctime - ptime);
  8370. templist.append(v);
  8371. }
  8372. for(int i = 0; i < timelist.size(); i++)
  8373. {
  8374. Measurement synthesized = measure;
  8375. synthesized.setTime(timelist[i]);
  8376. synthesized.setTemperature(templist[i]);
  8377. newMeasurement(synthesized, tempcolumn);
  8378. }
  8379. }
  8380. }
  8381. @ New to \pn{} 1.4 is the concept of a current column set. This was added to
  8382. improve support for devices where measurements on different data series may not
  8383. arrive at exactly the same time and for multi-device configurations where
  8384. measurements from different devices are unlikely to arrive at the same time.
  8385. This can cause issues with log annotations and serialization. The solution is
  8386. to group all columns that are logically part of the same data acquisition
  8387. process and as measurements come in, the most recent measurement from other
  8388. columns can be duplicated at the new time. Two methods are responsible for
  8389. managing this measurement set. One adds a column to the set and the other
  8390. removes all columns from the set.
  8391. @<ZoomLog Implementation@>=
  8392. void ZoomLog::addToCurrentColumnSet(int column)
  8393. {
  8394. currentColumnSet.append(column);
  8395. }
  8396. void ZoomLog::clearCurrentColumnSet()
  8397. {
  8398. currentColumnSet.clear();
  8399. }
  8400. @ Replicating the measurements occurs as measurements are delivered. Note
  8401. that this code will not be called for the first measurement in each column.
  8402. @<Synthesize measurements for columns in set@>=
  8403. if(currentColumnSet.contains(tempcolumn))
  8404. {
  8405. int replicationcolumn;
  8406. foreach(replicationcolumn, currentColumnSet)
  8407. {
  8408. if(replicationcolumn != tempcolumn)
  8409. {
  8410. if(lastMeasurement.contains(replicationcolumn))
  8411. {
  8412. if(measure.time() > lastMeasurement.value(replicationcolumn).time())
  8413. {
  8414. Measurement synthetic = lastMeasurement.value(replicationcolumn);
  8415. synthetic.setTime(measure.time());
  8416. model_ms->newMeasurement(synthetic, replicationcolumn);
  8417. if(synthetic.time().second() != lastMeasurement.value(replicationcolumn).time().second())@/
  8418. {
  8419. Measurement adjusted = synthetic;
  8420. adjusted.setTime(QTime(0, synthetic.time().minute(), synthetic.time().second(), 0));
  8421. model_1s->newMeasurement(adjusted, replicationcolumn);
  8422. if(adjusted.time().second() % 5 == 0)
  8423. {
  8424. model_5s->newMeasurement(adjusted, replicationcolumn);
  8425. if(adjusted.time().second() % 10 == 0)
  8426. {
  8427. model_10s->newMeasurement(adjusted, replicationcolumn);
  8428. }
  8429. if(adjusted.time().second() % 15 == 0)
  8430. {
  8431. model_15s->newMeasurement(adjusted, replicationcolumn);
  8432. if(adjusted.time().second() % 30 == 0)
  8433. {
  8434. model_30s->newMeasurement(adjusted, replicationcolumn);
  8435. if(adjusted.time().second() == 0)
  8436. {
  8437. model_1m->newMeasurement(adjusted, replicationcolumn);
  8438. }
  8439. }
  8440. }
  8441. }
  8442. }
  8443. lastMeasurement[replicationcolumn] = synthetic;
  8444. }
  8445. }
  8446. }
  8447. }
  8448. }
  8449. @ Just as the first measurement should exist at every level of detail, so should
  8450. any annotations. The measurement models will, when presented with an annotation,
  8451. apply it to the most recently entered measurement in the specified data series.
  8452. This presents a problem for the coarser views as the data point the annotation
  8453. belongs to most likely does not exist in that view. Furthermore, the model as it
  8454. is currently written will overwrite annotations that already exist on a
  8455. measurement if it is still the most recently entered. When collecting samples
  8456. during profile development, it is common to produce several annotations in a
  8457. short amount of time. The most useful thing to do in such a case is to add the
  8458. most recent measurement to each model and then apply the annotation. This, of
  8459. course, should only be done if there is a most recent measurement. An annotation
  8460. regarding the starting condition of the roaster should apply to the yet to be
  8461. recorded time zero measurement.
  8462. Note that only the value from the temperature column specified is displayed in
  8463. the row with the annotation. It would be better to check the full detail model
  8464. to determine if there are other measurements at the annotation time and present
  8465. these as well. Another possibility in the case of data not existing in other
  8466. temperature columns would be to interpolate a value from the existing data in
  8467. these columns, however this is potentially challenging as I would want to keep
  8468. true measurements distinct from estimations.
  8469. @<ZoomLog Implementation@>=
  8470. void ZoomLog::newAnnotation(QString annotation, int tempcolumn,
  8471. int annotationcolumn)
  8472. {
  8473. model_ms->newAnnotation(annotation, tempcolumn, annotationcolumn);
  8474. MeasurementModel *m;
  8475. if(lastMeasurement.contains(tempcolumn))
  8476. {
  8477. foreach(m, modelSet)
  8478. {
  8479. m->newMeasurement(lastMeasurement.value(tempcolumn), tempcolumn);
  8480. }
  8481. }
  8482. foreach(m, modelSet)
  8483. {
  8484. m->newAnnotation(annotation, tempcolumn, annotationcolumn);
  8485. }
  8486. }
  8487. @ As measurements are added to the model, the model will emit rowChanged
  8488. signals. These signals are connected to a function here that will attempt to
  8489. scroll the view to keep the most recently entered data in the center of the
  8490. view.
  8491. @<ZoomLog Implementation@>=
  8492. void ZoomLog::centerOn(int row)
  8493. {
  8494. scrollTo(currentModel->index(row, 0), QAbstractItemView::PositionAtCenter);
  8495. }
  8496. @ Once we are done with the data in the table, we want to clear it to prepare
  8497. for new data. This also clears the lists holding the output columns to use when
  8498. saving data.
  8499. @<ZoomLog Implementation@>=
  8500. void ZoomLog::clear()
  8501. {
  8502. MeasurementModel *m;
  8503. foreach(m, modelSet)
  8504. {
  8505. m->clear();
  8506. }
  8507. lastMeasurement.clear();
  8508. saveTempCols.clear();
  8509. saveControlCols.clear();
  8510. saveNoteCols.clear();
  8511. }
  8512. @ These are depreciated methods originally written to assist in serializing
  8513. model data prior to the introduction of the |XMLOutput| class. These methods are
  8514. likely to be removed in a future version of the program.
  8515. @<ZoomLog Implementation@>=
  8516. QVariant ZoomLog::data(int row, int column) const
  8517. {
  8518. return model_ms->data(model_ms->index(row, column, QModelIndex()),
  8519. Qt::DisplayRole);
  8520. }
  8521. int ZoomLog::rowCount()
  8522. {
  8523. return model_ms->rowCount();
  8524. }
  8525. @ This method initializes an |XMLOutput| instance, passes the columns that we
  8526. would like to save to that object, and uses it to write an XML file with the
  8527. desired data to the specified device.
  8528. Since the output format does not currently specify a unit, there is an
  8529. assumption that the XML output will always have measurements in Fahrenheit. If
  8530. the model is not currently displaying measurements in Fahrenheit, it is asked to
  8531. do so before writing the XML data. User preference is restored after the XML
  8532. data has been written. Since this change is only performed on |model_ms|, most
  8533. users will never notice this.
  8534. @<ZoomLog Implementation@>=
  8535. bool ZoomLog::saveXML(QIODevice *device)
  8536. {
  8537. Units::Unit prevUnits = model_ms->displayUnits();
  8538. if(prevUnits != Units::Fahrenheit)
  8539. {
  8540. model_ms->setDisplayUnits(Units::Fahrenheit);
  8541. }
  8542. XMLOutput writer(model_ms, device, 0);
  8543. int c;
  8544. foreach(c, saveTempCols)
  8545. {
  8546. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  8547. toString(), c);
  8548. }
  8549. foreach(c, saveControlCols)
  8550. {
  8551. writer.addControlColumn(model_ms->headerData(c, Qt::Horizontal).
  8552. toString(), c);
  8553. }
  8554. foreach(c, saveNoteCols)
  8555. {
  8556. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  8557. toString(), c);
  8558. }
  8559. bool retval = writer.output();
  8560. if(prevUnits != Units::Fahrenheit)
  8561. {
  8562. model_ms->setDisplayUnits(prevUnits);
  8563. }
  8564. return retval;
  8565. }
  8566. @ This method is similar to |saveXML()|. The main difference is that CSV data is
  8567. exported instead of XML.
  8568. @<ZoomLog Implementation@>=
  8569. bool ZoomLog::saveCSV(QIODevice *device)
  8570. {
  8571. CSVOutput writer(currentModel, device, 0);
  8572. int c;
  8573. foreach(c, saveTempCols)
  8574. {
  8575. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  8576. toString(), c);
  8577. }
  8578. foreach(c, saveControlCols)
  8579. {
  8580. writer.addControlColumn(model_ms->headerData(c, Qt::Horizontal).
  8581. toString(), c);
  8582. }
  8583. foreach(c, saveNoteCols)
  8584. {
  8585. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  8586. toString(), c);
  8587. }
  8588. return writer.output();
  8589. }
  8590. @ Several little functions, all alike\nfnote{If you get the reference, you may
  8591. enjoy reading another \cweb{} program:\par\indent\pdfURL{%
  8592. http://www-cs-staff.stanford.edu/$\sim$uno/programs/advent.w.gz}
  8593. {http://www-cs-staff.stanford.edu/~uno/programs/advent.w.gz}}, are used to
  8594. switch the view from one level of detail to another.
  8595. @<ZoomLog Implementation@>=
  8596. void ZoomLog::switchLOD(MeasurementModel *m)
  8597. {
  8598. disconnect(currentModel, SIGNAL(rowChanged(int)), this, 0);
  8599. setModel(m);
  8600. currentModel = m;
  8601. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  8602. }
  8603. void ZoomLog::LOD_ms()
  8604. {
  8605. switchLOD(model_ms);
  8606. }
  8607. void ZoomLog::LOD_1s()
  8608. {
  8609. switchLOD(model_1s);
  8610. }
  8611. void ZoomLog::LOD_5s()
  8612. {
  8613. switchLOD(model_5s);
  8614. }
  8615. void ZoomLog::LOD_10s()
  8616. {
  8617. switchLOD(model_10s);
  8618. }
  8619. void ZoomLog::LOD_15s()
  8620. {
  8621. switchLOD(model_15s);
  8622. }
  8623. void ZoomLog::LOD_30s()
  8624. {
  8625. switchLOD(model_30s);
  8626. }
  8627. void ZoomLog::LOD_1m()
  8628. {
  8629. switchLOD(model_1m);
  8630. }
  8631. @ It can be useful to display temperature measurements in various units. To do
  8632. so, we simply tell all of the models which unit to provide data in. It is also
  8633. possible to obtain the currently selected unit.
  8634. @<ZoomLog Implementation@>=
  8635. void ZoomLog::setDisplayUnits(Units::Unit scale)
  8636. {
  8637. model_ms->setDisplayUnits(scale);
  8638. model_1s->setDisplayUnits(scale);
  8639. model_5s->setDisplayUnits(scale);
  8640. model_10s->setDisplayUnits(scale);
  8641. model_15s->setDisplayUnits(scale);
  8642. model_30s->setDisplayUnits(scale);
  8643. model_1m->setDisplayUnits(scale);
  8644. }
  8645. Units::Unit ZoomLog::displayUnits()
  8646. {
  8647. return model_ms->displayUnits();
  8648. }
  8649. @ For convenience, a method is provided for returning a string containing the
  8650. time of the last inserted measurement in a given data series.
  8651. @<ZoomLog Implementation@>=
  8652. QString ZoomLog::lastTime(int series)
  8653. {
  8654. Measurement measure = lastMeasurement.value(series);
  8655. QTime time = measure.time();
  8656. return time.toString("h:mm:ss.zzz");
  8657. }
  8658. @ This just leaves the initial table setup.
  8659. @<ZoomLog Implementation@>=
  8660. ZoomLog::ZoomLog() : QTableView(NULL), model_ms(new MeasurementModel(this)),
  8661. model_1s(new MeasurementModel(this)),@/ model_5s(new MeasurementModel(this)),
  8662. model_10s(new MeasurementModel(this)),@/ model_15s(new MeasurementModel(this)),
  8663. model_30s(new MeasurementModel(this)),@/ model_1m(new MeasurementModel(this))@/
  8664. {@/
  8665. setEditTriggers(QAbstractItemView::NoEditTriggers);
  8666. setSelectionMode(QAbstractItemView::NoSelection);
  8667. modelSet << model_ms << model_1s << model_5s << model_10s << model_15s <<
  8668. model_30s << model_1m;
  8669. currentModel = model_30s;
  8670. setModel(currentModel);
  8671. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  8672. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  8673. this, SLOT(persistColumnResize(int, int, int)));
  8674. connect(horizontalHeader(), SIGNAL(sectionCountChanged(int, int)),
  8675. this, SLOT(restoreColumnWidths()));
  8676. }
  8677. @ A new method was added to this class for version 1.0.7. This allows header
  8678. data to be set on the log and have it propagate to the model set. The longer
  8679. term plan involves removing the hard coding of some of the header data.
  8680. @<ZoomLog Implementation@>=
  8681. void ZoomLog::setHeaderData(int section, QString text)
  8682. {
  8683. MeasurementModel *m;
  8684. foreach(m, modelSet)
  8685. {
  8686. m->setHeaderData(section, Qt::Horizontal, QVariant(text));
  8687. }
  8688. }
  8689. @ As of version 1.2.3, these methods replace similar methods added for version
  8690. 1.0.8. The main difference is that it is now possible to save multiple data
  8691. series to the same output document.
  8692. Starting in version 1.6 it is possible to save control columns. These should
  8693. contain unitless data which should remain unaffected by the current displayed
  8694. unit.
  8695. @<ZoomLog Implementation@>=
  8696. void ZoomLog::addOutputTemperatureColumn(int column)
  8697. {
  8698. saveTempCols.append(column);
  8699. }
  8700. void ZoomLog::addOutputControlColumn(int column)
  8701. {
  8702. saveControlCols.append(column);
  8703. }
  8704. void ZoomLog::addOutputAnnotationColumn(int column)
  8705. {
  8706. saveNoteCols.append(column);
  8707. }
  8708. void ZoomLog::clearOutputColumns()
  8709. {
  8710. saveTempCols.clear();
  8711. saveControlCols.clear();
  8712. saveNoteCols.clear();
  8713. }
  8714. @ Starting in version 1.4 two methods have been introduced which are used to
  8715. save and restore column widths.
  8716. @<ZoomLog Implementation@>=
  8717. void ZoomLog::persistColumnResize(int column, int, int newsize)
  8718. {
  8719. @<Save updated column size@>@;
  8720. }
  8721. void ZoomLog::restoreColumnWidths()
  8722. {
  8723. @<Restore table column widths@>@;
  8724. }
  8725. void ZoomLog::setVisible(bool visibility)
  8726. {
  8727. QTableView::setVisible(visibility);
  8728. }
  8729. void ZoomLog::showEvent(QShowEvent *)
  8730. {
  8731. @<Restore table column widths@>@;
  8732. }
  8733. @ The |ZoomLog| class is one of the more complicated classes to expose to the
  8734. scripting engine. In addition to a script constructor, we also need functions
  8735. for saving and restoring the state of the display and functions for saving data
  8736. from the log in the supported formats.
  8737. @<Function prototypes for scripting@>=
  8738. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine);
  8739. QScriptValue constructZoomLog(QScriptContext *context, QScriptEngine *engine);
  8740. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine);
  8741. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine);
  8742. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *engine);
  8743. QScriptValue ZoomLog_restoreState(QScriptContext *context,
  8744. QScriptEngine *engine);
  8745. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine);
  8746. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  8747. QScriptEngine *engnie);
  8748. QScriptValue ZoomLog_setDisplayUnits(QScriptContext *context,
  8749. QScriptEngine *engine);
  8750. @ Of these, the global object only needs to know about the constructor.
  8751. @<Set up the scripting engine@>=
  8752. constructor = engine->newFunction(constructZoomLog);
  8753. value = engine->newQMetaObject(&ZoomLog::staticMetaObject, constructor);
  8754. engine->globalObject().setProperty("ZoomLog", value);
  8755. @ The script constructor sets properties on the newly created object to allow
  8756. the other functions to be called.
  8757. @<Functions for scripting@>=
  8758. QScriptValue constructZoomLog(QScriptContext *, QScriptEngine *engine)@/
  8759. {@/
  8760. QScriptValue object = engine->newQObject(new ZoomLog);
  8761. setZoomLogProperties(object, engine);
  8762. return object;@/
  8763. }
  8764. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine)
  8765. {
  8766. setQTableViewProperties(value, engine);
  8767. value.setProperty("saveXML", engine->newFunction(ZoomLog_saveXML));
  8768. value.setProperty("saveCSV", engine->newFunction(ZoomLog_saveCSV));
  8769. value.setProperty("saveState", engine->newFunction(ZoomLog_saveState));
  8770. value.setProperty("restoreState",
  8771. engine->newFunction(ZoomLog_restoreState));
  8772. value.setProperty("lastTime", engine->newFunction(ZoomLog_lastTime));
  8773. value.setProperty("saveTemporary",
  8774. engine->newFunction(ZoomLog_saveTemporary));
  8775. value.setProperty("setDisplayUnits", engine->newFunction(ZoomLog_setDisplayUnits));
  8776. }
  8777. @ The functions for saving data are simple wrappers around the corresponding
  8778. calls in |ZoomLog|, except for a function added for saving data to a temporary
  8779. file. The last provides the name of the file saved for use in copying that data
  8780. to a database entry.
  8781. @<Functions for scripting@>=
  8782. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine)
  8783. {
  8784. ZoomLog *self = getself<ZoomLog *>(context);
  8785. bool retval = self->saveXML(argument<QIODevice *>(0, context));
  8786. return QScriptValue(engine, retval);
  8787. }
  8788. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine)
  8789. {
  8790. ZoomLog *self = getself<ZoomLog *>(context);
  8791. bool retval = self->saveCSV(argument<QIODevice *>(0, context));
  8792. return QScriptValue(engine, retval);
  8793. }
  8794. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  8795. QScriptEngine *engine)
  8796. {
  8797. ZoomLog *self = getself<ZoomLog *>(context);
  8798. QString filename = QDir::tempPath();
  8799. filename.append("/");
  8800. filename.append(QUuid::createUuid().toString());
  8801. filename.append(".xml");
  8802. QFile *file = new QFile(filename);
  8803. self->saveXML(file);
  8804. file->close();
  8805. delete file;
  8806. return QScriptValue(engine, filename);
  8807. }
  8808. @ The remaining functions are convenience functions for use with the scripting
  8809. engine. One will save the column widths to a |QSettings| object. Another will
  8810. restore the column widths from settings. Finally, there is a function for
  8811. obtaining a string representation of the most recent measurement from a data
  8812. series.
  8813. \danger There are a couple of problems with these functions. First, the body of
  8814. these functions would probably be better off as methods in the |ZoomLog| class
  8815. proper, either as slots or |Q_INVOKABLE| so the special scripting functions
  8816. could be eliminated. Second, rather than polluting the settings with separate
  8817. entries for each column, it would probably be better to store all of these
  8818. values in an array.\endanger
  8819. |ZoomLog_saveState()| was changed in version 1.2.3 to not save a new value for
  8820. the column width if that width is |0|. This was done mainly to ease debugging.
  8821. Similarly, |ZoomLog_restoreState()| picks a new default value when |0| is
  8822. encountered.
  8823. @<Functions for scripting@>=
  8824. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *)
  8825. {
  8826. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8827. QString key = argument<QString>(0, context);
  8828. int columns = argument<int>(1, context);
  8829. QSettings settings;
  8830. for(int i = 0; i < columns; i++)
  8831. {
  8832. if(self->columnWidth(i))
  8833. {
  8834. settings.beginGroup(key);
  8835. settings.setValue(QString("%1").arg(i), self->columnWidth(i));
  8836. settings.endGroup();
  8837. }
  8838. }
  8839. return QScriptValue();
  8840. }
  8841. QScriptValue ZoomLog_restoreState(QScriptContext *context, QScriptEngine *)
  8842. {
  8843. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8844. QString key = argument<QString>(0, context);
  8845. int columns = argument<int>(1, context);
  8846. QSettings settings;
  8847. for(int i = 0; i < columns; i++)
  8848. {
  8849. settings.beginGroup(key);
  8850. self->setColumnWidth(i,
  8851. settings.value(QString("%1").arg(i), 80).toInt());
  8852. if(settings.value(QString("%1").arg(i), 80).toInt() == 0)
  8853. {
  8854. self->setColumnWidth(i, 80);
  8855. }
  8856. settings.endGroup();
  8857. }
  8858. return QScriptValue();
  8859. }
  8860. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine)
  8861. {
  8862. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8863. return QScriptValue(engine, self->lastTime(argument<int>(0, context)));
  8864. }
  8865. @ There seems to be a bad interaction when enumerated value types as used as
  8866. the argument to slot methods called through QtScript. Script code that attempts
  8867. to make use of the enumeration appears to get the value without any type
  8868. information. When attempting to use that value as an argument the meta-object
  8869. system cannot find an appropriate match and the script just hangs silently.
  8870. The solution is to wrap such methods in the script bindings and explicitly cast
  8871. the argument value to the enumerated type. This looks stupid but it works.
  8872. @<Functions for scripting@>=
  8873. QScriptValue ZoomLog_setDisplayUnits(QScriptContext *context, QScriptEngine *)
  8874. {
  8875. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8876. self->setDisplayUnits((Units::Unit)argument<int>(0, context));
  8877. return QScriptValue();
  8878. }
  8879. @* A model for roasting data.
  8880. \noindent Qt provides a tool called the model view architecture. This provides a
  8881. uniform interface allowing different types of model classes to work with
  8882. different types of view classes without either needing to know implementation
  8883. details of the other. \pn{} provides the |MeasurementModel| as a specialization
  8884. of |QAbstractItemModel| for use in this architecture.
  8885. @<Class declarations@>=
  8886. class MeasurementList;@/
  8887. class MeasurementModel : public QAbstractItemModel@/
  8888. {@t\1@>@/
  8889. Q_OBJECT@;
  8890. Units::Unit unit;
  8891. QList<MeasurementList *> *entries;
  8892. QStringList *hData;
  8893. int colcount;
  8894. QHash<int, int> *lastTemperature;
  8895. QList<MeasurementList *>::iterator@, lastInsertion;
  8896. QHash<int, bool> *controlColumns;
  8897. public:@/
  8898. MeasurementModel(QObject *parent = NULL);
  8899. ~MeasurementModel();
  8900. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  8901. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  8902. bool setHeaderData(int section, Qt::Orientation orientation,
  8903. const QVariant &value,@|int role = Qt::DisplayRole);
  8904. QVariant data(const QModelIndex &index, int role) const;
  8905. bool setData(const QModelIndex &index, const QVariant &value,
  8906. int role = Qt::EditRole);
  8907. Qt::ItemFlags flags(const QModelIndex &index) const;
  8908. QVariant headerData(int section, Qt::Orientation orientation,
  8909. int role = Qt::DisplayRole) const;
  8910. QModelIndex index(int row, int column,
  8911. const QModelIndex &parent = QModelIndex()) const;
  8912. QModelIndex parent(const QModelIndex &index) const;
  8913. Units::Unit displayUnits();@/
  8914. @t\4@>public slots@t\kern-3pt@>:@/
  8915. void newMeasurement(Measurement measure, int tempcolumn);
  8916. void newAnnotation(QString annotation, int tempcolumn,
  8917. int annotationColumn);
  8918. void clear();
  8919. void setDisplayUnits(Units::Unit scale);
  8920. signals:@/
  8921. void rowChanged(int);@t\2@>@/
  8922. }@t\kern-3pt@>;
  8923. @ The measurement model stores its data in a list of measurement lists. This
  8924. allows the model to store as many sets of data as needed. In order to keep
  8925. measurements in the model sorted by time, the measurement list adds two
  8926. comparison functions.
  8927. @<Class declarations@>=
  8928. class MeasurementList : public QVariantList@/
  8929. {@t\1@>@/
  8930. @t\4@>public:@/
  8931. bool operator<(const MeasurementList &other) const;
  8932. bool operator==(const MeasurementList &other) const;@t\2@>@/
  8933. }@t\kern-3pt@>;
  8934. @ The overload of |<| checks if the time in one list (always stored in the first
  8935. column) is less than the time stored in the second. The overload of |==| is used
  8936. in an optimization that allows us to skip the search procedure on model
  8937. insertion.
  8938. @<MeasurementModel Implementation@>=
  8939. bool MeasurementList::operator<(const MeasurementList &other) const
  8940. {
  8941. return this->first().toTime() < other.first().toTime();
  8942. }
  8943. bool MeasurementList::operator==(const MeasurementList &other) const
  8944. {
  8945. return this->first().toTime() == other.first().toTime();
  8946. }
  8947. @ The |MeasurementModel| class extends the |QAbstractItemModel| class to work
  8948. better with measurements and annotations that are passed around in \pn{}. Many
  8949. of the class methods are required because of that choice. For example, the
  8950. parent function which is never used directly:
  8951. @<MeasurementModel Implementation@>=
  8952. QModelIndex MeasurementModel::parent(const QModelIndex&) const
  8953. {
  8954. return QModelIndex();
  8955. }
  8956. @ Perhaps the most complicated part of this class is the code for dealing with a
  8957. new measurement. This is complicated by the requirement to insert measurements
  8958. while keeping the model sorted by time.
  8959. @<MeasurementModel Implementation@>=
  8960. void MeasurementModel::newMeasurement(Measurement measure, int tempcolumn)
  8961. {
  8962. if(measure.scale() == Units::Unitless)
  8963. {
  8964. controlColumns->insert(tempcolumn, true);
  8965. }
  8966. else
  8967. {
  8968. controlColumns->insert(tempcolumn, false);
  8969. }
  8970. MeasurementList *temp;
  8971. temp = new MeasurementList;
  8972. temp->append(QVariant(measure.time()));
  8973. @<Find the insertion point@>@;
  8974. MeasurementList *newEntry;
  8975. int insertion;
  8976. if(i != entries->end())
  8977. {
  8978. insertion = entries->indexOf(*i);
  8979. if((*i)->first().toTime() == measure.time())
  8980. {
  8981. @<Insert a new measurement at an existing time@>@;
  8982. }
  8983. else
  8984. {
  8985. @<Insert a new measurement somewhere else@>@;
  8986. }
  8987. }
  8988. else
  8989. {
  8990. @<Append a measurement@>@;
  8991. }
  8992. if(tempcolumn >= colcount)
  8993. {
  8994. colcount = tempcolumn + 1;
  8995. }
  8996. emit rowChanged(insertion);
  8997. delete temp;
  8998. }
  8999. @ To find the insertion point for new measurements we use a binary search of the
  9000. existing data. The code below is a direct adaptation of Program B\nfnote{%
  9001. \underbar{The Art of Computer Programming} Volume 3 Sorting and Searching 2nd
  9002. ed. (Knuth, 1997) Section 6.2.1: Searching an Ordered Table} modified to use
  9003. list iterators and control structures more familiar to \CPLUSPLUS/programmers
  9004. rather than {\mc MIX} machine codes. When the loop exits |i| is the insertion
  9005. point.
  9006. \medskip
  9007. \centerline{\includegraphics{search}}
  9008. \smallskip
  9009. \centerline{Figure \secno: Binary Search}
  9010. \medskip
  9011. @<Find the insertion point@>=
  9012. @<Scan from most recent insertion@>@;
  9013. if(quickscan == false)
  9014. {
  9015. i = entries->begin();
  9016. QList<MeasurementList *>::iterator@, u = entries->end();
  9017. QList<MeasurementList *>::iterator@, midpoint;
  9018. int n = u - i;
  9019. int rA;
  9020. while(n > 0)@/
  9021. {
  9022. rA = n>>1; /* |rA = |~$\bigl\lfloor{n\over2}\bigr\rfloor$ */
  9023. midpoint = i + rA;
  9024. if(**midpoint < *temp)@/
  9025. {
  9026. i = midpoint + 1;
  9027. n -= rA + 1;
  9028. }
  9029. else@/
  9030. {
  9031. n = rA;
  9032. }
  9033. }
  9034. }
  9035. @ The binary search, while correct, is not a particularly optimal choice for
  9036. this application. While the average running time for this is on the order of
  9037. $\ln N$ when each insertion point is equally likely, the reality of this
  9038. application is that insertions will likely be at the beginning of the list, at
  9039. the point of the most recent insertion, or a short distance from the most recent
  9040. insertion. By first considering the possibility that the measurement should be
  9041. inserted at or near the most recent measurement, shorter, more constant running
  9042. times as $N$ increases can be obtained.
  9043. To do this, when the number of measurements in the list is above a small number
  9044. which must be greater than 1, we check first if the insertion point is at the
  9045. last insertion (the |<| comparison fails and we do an |==| comparison before
  9046. giving up), then we check a small number of rows for either the end of the list,
  9047. in which case the insertion point is at the end, or for a point at which the |<|
  9048. comparison fails. If neither condition holds for a small number of comparisons
  9049. we resort to the binary search.
  9050. Performance measurements with this modification compared with previous versions
  9051. shows that this provides a huge performance boost.
  9052. @<Scan from most recent insertion@>=
  9053. @[QList<MeasurementList *>::iterator@, i@] = lastInsertion;@/
  9054. bool quickscan = false;@/
  9055. if(entries->size() > 5)@/
  9056. {@t\1@>@/
  9057. if(**i < *temp)@/
  9058. {@t\1@>@/
  9059. i += 1;@/
  9060. for(int j = 10; j > 0; j--)@/
  9061. {@t\1@>@/
  9062. if(i != entries->end())@/
  9063. {@t\1@>@/
  9064. if(**i < *temp)@/
  9065. {
  9066. i += 1;
  9067. }@/
  9068. else@/
  9069. {@t\1@>@/
  9070. quickscan = true;
  9071. break;@t\2@>@/
  9072. }@t\2@>@/
  9073. }@/
  9074. else@/
  9075. {@t\1@>@/
  9076. quickscan = true;
  9077. break;@t\2@>@/
  9078. }@t\2@>@/
  9079. }@t\2@>@/
  9080. }@/
  9081. else@/
  9082. {@t\1@>@/
  9083. if(**i == *temp)@/
  9084. {@t\1@>@/
  9085. quickscan = true;@t\2@>@/
  9086. }@t\2@>@/
  9087. }@t\2@>@/
  9088. }
  9089. @ If the chosen insertion point is at an existing time, we don'@q'@>t need to
  9090. worry about inserting rows. There may be a need to increase the size of the
  9091. measurement list to accept an entry in a new data series.
  9092. @<Insert a new measurement at an existing time@>=
  9093. if((*i)->size() < tempcolumn + 1)
  9094. {
  9095. for(int j = (*i)->size() - 1; j < tempcolumn + 1; j++)
  9096. {
  9097. (*i)->append(QVariant());
  9098. }
  9099. }
  9100. (*i)->replace(tempcolumn, measure);
  9101. lastInsertion = i;
  9102. emit dataChanged(createIndex(insertion, tempcolumn),
  9103. createIndex(insertion, tempcolumn));
  9104. lastTemperature->insert(tempcolumn, insertion);
  9105. @ If the measurement is not past the end of the existing data and the insertion
  9106. point has a different time, we need to use |beginInsertRows()| and
  9107. |endInsertRows()| to notify any attached view that a new row will be added.
  9108. @<Insert a new measurement somewhere else@>=
  9109. beginInsertRows(QModelIndex(), insertion, insertion);
  9110. newEntry = new MeasurementList;
  9111. newEntry->append(QVariant(measure.time()));
  9112. for(int j = 0; j < tempcolumn + 1; j++)
  9113. {
  9114. newEntry->append(QVariant());
  9115. }
  9116. newEntry->replace(tempcolumn, measure);
  9117. lastInsertion = entries->insert(i, newEntry);
  9118. endInsertRows();
  9119. lastTemperature->insert(tempcolumn, insertion);
  9120. @ If the insertion point is past the end of the existing data, a new row should
  9121. be appended to the data. This only needs to be a separate case to prevent the
  9122. comparison with a nonexistent entry. This is very similar to the case of
  9123. inserting at a new time anywhere else.
  9124. @<Append a measurement@>=
  9125. insertion = entries->size();@/
  9126. @<Insert a new measurement somewhere else@>
  9127. @ The other bit of code that'@q'@>s a little bit more complicated than other
  9128. parts of the class handles adding annotations to the data. Two signals are
  9129. emitted in this method. The |dataChanged| signal is expected by view classes
  9130. that can use this model. The |rowChanged| signal is used by |ZoomLog| to scroll
  9131. the view to the row the annotation has been added to. This is mainly useful
  9132. when loading a target profile and entering the first annotation prior to
  9133. starting the batch.
  9134. @<MeasurementModel Implementation@>=
  9135. void MeasurementModel::newAnnotation(QString annotation, int tempcolumn,@|
  9136. int annotationColumn)
  9137. {
  9138. int r;
  9139. if(lastTemperature->contains(tempcolumn))
  9140. {
  9141. r = lastTemperature->value(tempcolumn);
  9142. }
  9143. else
  9144. {
  9145. r = 0;
  9146. }
  9147. if(r == 0 && entries->size() == 0)
  9148. {
  9149. @<Create the first row@>@;
  9150. }
  9151. MeasurementList *row = entries->at(r);
  9152. if(row->size() <= annotationColumn)
  9153. {
  9154. for(int i = row->size() - 1; i < annotationColumn + 1; i++)
  9155. {
  9156. row->append(QVariant());
  9157. }
  9158. }
  9159. row->replace(annotationColumn, annotation);
  9160. emit dataChanged(createIndex(r, annotationColumn),
  9161. createIndex(r, annotationColumn));
  9162. emit rowChanged(r);
  9163. if(annotationColumn > colcount - 1)
  9164. {
  9165. colcount = annotationColumn + 1;
  9166. }
  9167. }
  9168. @ There is no need to further complicate the function by adding the annotation
  9169. when the first row is created.
  9170. @<Create the first row@>=
  9171. beginInsertRows(QModelIndex(), 0, 0);
  9172. MeasurementList *newEntry = new MeasurementList;
  9173. newEntry->append(QVariant(QTime(0, 0, 0, 0)));
  9174. entries->append(newEntry);
  9175. endInsertRows();
  9176. @ Clearing the model data is a simple matter of deleting every row, remembering
  9177. to let any attached views know that we are doing this, and resetting the number
  9178. of columns.
  9179. @<MeasurementModel Implementation@>=
  9180. void MeasurementModel::clear()
  9181. {
  9182. beginRemoveRows(QModelIndex(), 0, entries->size());
  9183. while(entries->size() != 0)
  9184. {
  9185. MeasurementList *row = entries->takeFirst();
  9186. delete row;
  9187. }
  9188. endRemoveRows();
  9189. colcount = hData->size();
  9190. lastTemperature->clear();
  9191. reset();
  9192. }
  9193. @ While these methods for adding measurements and annotations are fine when
  9194. recording a stream of measurements, either from the |DAQ| or when loading saved
  9195. data, there are also cases where we'@q'@>d like to edit the data in the model
  9196. directly from the table view. For this, we need to reimplement |setData()|.
  9197. Note that editing from the |ZoomLog| has never been supported. While stream
  9198. inserted data currently preserves all properties of inserted measurements,
  9199. using |setData| it is possible to insert a numeric value as if it were a
  9200. measurement. Such an entry will not have any additional information associated
  9201. and cannot be expected to exhibit behavior implemented through the use of that
  9202. extra information.
  9203. Very little input checking is done here. Editable views may want to place
  9204. delegates\nfnote{Qt 4.4: Delegate Classes\par\indent\hbox{%
  9205. \pdfURL{http://doc.trolltech.com/4.4/model-view-delegate.html}{%
  9206. http://doc.trolltech.com/4.4/model-view-delegate.html}}} on the columns to make
  9207. editing the data easier and less error prone.
  9208. @<MeasurementModel Implementation@>=
  9209. bool MeasurementModel::setData(const QModelIndex &index,
  9210. const QVariant &value, int role)@t\2\2@>@/
  9211. {@t\1@>@/
  9212. if(role != Qt::EditRole && role != Qt::DisplayRole)@/
  9213. {@t\1@>@/
  9214. return false;@t\2@>@/
  9215. }@/
  9216. @<Check that the index is valid@>@;
  9217. if(!valid)@/
  9218. {@t\1@>@/
  9219. return false;@t\2@>@/
  9220. }@/
  9221. MeasurementList *row = entries->at(index.row());
  9222. if(index.column() >= row->size())
  9223. {
  9224. @<Expand the row to prepare for new data@>@;
  9225. }
  9226. if(index.column() == 0)
  9227. {
  9228. @<Edit data in the time column@>@;
  9229. }
  9230. else
  9231. {
  9232. @<Edit data in other columns@>@;
  9233. }
  9234. return true;@t\2@>@/
  9235. }
  9236. @ There is no sense in attempting to edit the data if there isn'@q'@>t any data
  9237. available to edit. This check is also used when retrieving data from the model.
  9238. @<Check that the index is valid@>=
  9239. bool valid = false;
  9240. if(index.isValid())@/
  9241. {@t\1@>@/
  9242. if(index.row() < entries->size())@/
  9243. {@t\1@>@/
  9244. if(index.column() < colcount)@/
  9245. {@t\1@>@/
  9246. valid = true;@t\2@>@/
  9247. }@t\2@>@/
  9248. }@t\2@>@/
  9249. }
  9250. @ When editing data, there might not be anything where we want to add the data.
  9251. For example, adding an annotation to an otherwise unannotated measurement. This
  9252. is fine, but we need to expand the row instead of inserting data out of bounds.
  9253. @<Expand the row to prepare for new data@>=
  9254. for(int i = row->size() - 1; i < index.column(); i++)
  9255. {
  9256. row->append(QVariant());
  9257. }
  9258. @ Changing time data must be considered separately from other data. As the model
  9259. keeps itself sorted based on the time field, allowing the user to get the model
  9260. data out of order would result in poorly defined behavior later. Our approach is
  9261. to remove the row from the model temporarily then reuse the code from
  9262. |newMeasurement()| to find the new insertion point. No attempt is made to merge
  9263. the contents from two rows with identical times, but an attempt is made to not
  9264. be too rigid in what we expect the user to enter. If an invalid time is entered,
  9265. we give up and leave the data as we found it.
  9266. @<Edit data in the time column@>=
  9267. QTime time;@/
  9268. if(!(time = QTime::fromString(value.toString(), "m:s.z")).isValid())@/
  9269. {@t\1@>@/
  9270. if(!(time = QTime::fromString(value.toString(), "m:s")).isValid())@/
  9271. {@t\1@>@/
  9272. return false;@t\2@>@/
  9273. }@t\2@>@/
  9274. }@/
  9275. row = entries->takeAt(index.row());
  9276. row->replace(index.column(), QVariant(time));
  9277. MeasurementList *temp = row;
  9278. @<Find the insertion point@>@;
  9279. entries->insert(i, row);
  9280. int newRow = entries->indexOf(*i);
  9281. if(newRow < index.row())@/
  9282. {
  9283. emit dataChanged(createIndex(newRow, index.column()), index);
  9284. }
  9285. else@/
  9286. {
  9287. emit dataChanged(index, createIndex(newRow, index.column()));
  9288. }
  9289. @ Data in other columns is a little easier to handle.
  9290. @<Edit data in other columns@>=
  9291. row->replace(index.column(), value);
  9292. emit dataChanged(index, index);
  9293. @ As it has already been established that the first column is always considered
  9294. the time of the measurement, this assumption can be built into the model
  9295. constructor.
  9296. @<MeasurementModel Implementation@>=
  9297. MeasurementModel::MeasurementModel(QObject *parent) : QAbstractItemModel(parent),
  9298. unit(Units::Fahrenheit), hData(new QStringList),
  9299. lastTemperature(new QHash<int, int>),
  9300. controlColumns(new QHash<int, bool>)@/
  9301. {
  9302. colcount = 1;
  9303. entries = new QList<MeasurementList *>;
  9304. lastInsertion = entries->begin();
  9305. hData->append(tr("Time"));
  9306. }
  9307. @ In the destructor we need to remember to clean up after ourselves.
  9308. @<MeasurementModel Implementation@>=
  9309. MeasurementModel::~MeasurementModel()
  9310. {
  9311. clear();
  9312. delete entries;
  9313. delete hData;
  9314. }
  9315. @ A pair of functions are used to determine the number of rows and columns the
  9316. model provides. No entries in the model have children, so the parent should
  9317. always be the invisible root object. If it isn'@q'@>t, we should return 0.
  9318. @<MeasurementModel Implementation@>=
  9319. int MeasurementModel::rowCount(const QModelIndex &parent) const
  9320. {
  9321. if(parent == QModelIndex())
  9322. {
  9323. return entries->size();
  9324. }
  9325. return 0;
  9326. }
  9327. int MeasurementModel::columnCount(const QModelIndex &parent) const
  9328. {
  9329. if(parent == QModelIndex())
  9330. {
  9331. return colcount;
  9332. }
  9333. return 0;
  9334. }
  9335. @ The model maintains a set of header data. At present, it only supports header
  9336. data at the top of the model due to the author'@q'@>s preference to not have row
  9337. numbers littering the left of the table (the time column is sufficient to
  9338. identify the row for the user).
  9339. The model view architecture supports the concept of different data roles in the
  9340. header data. At present, this model ignores the role when setting header data.
  9341. @<MeasurementModel Implementation@>=
  9342. bool MeasurementModel::setHeaderData(int section, Qt::Orientation orientation,@|
  9343. const QVariant &value, int)@t\2@>@/
  9344. @t\4@>{@/
  9345. if(orientation == Qt::Horizontal)@/
  9346. {@t\1@>@/
  9347. if(hData->size() < section + 1)@/
  9348. {@/
  9349. for(int i = hData->size(); i < section + 1; i++)@/
  9350. {@/
  9351. if(colcount < i)@/
  9352. {@/
  9353. beginInsertColumns(QModelIndex(), i, i);
  9354. }
  9355. hData->append(QString());
  9356. if(colcount < i)@/
  9357. {@/
  9358. endInsertColumns();
  9359. }
  9360. }
  9361. }
  9362. hData->replace(section, value.toString());
  9363. emit headerDataChanged(orientation, section, section);
  9364. if(colcount < section + 1)@/
  9365. {@/
  9366. colcount = section + 1;
  9367. }@/
  9368. return true;@t\2@>@/
  9369. }@/
  9370. return false;@/
  9371. @t\4@>}
  9372. @ While the current implementation always receives measurements in degrees
  9373. Fahrenheit, international users often want to see data presented in Celsius. To
  9374. do this, a slot is provided to allow selecting among different units. When this
  9375. method is called, the model indicates that all attached views must update all
  9376. displayed data and requests for temperature data will have any needed conversion
  9377. performed before sending that information to the view. Another method is
  9378. available to request a number identifyin the currently displayed units.
  9379. @<MeasurementModel Implementation@>=
  9380. void MeasurementModel::setDisplayUnits(Units::Unit scale)
  9381. {
  9382. beginResetModel();
  9383. unit = scale;
  9384. endResetModel();
  9385. }
  9386. Units::Unit MeasurementModel::displayUnits()
  9387. {
  9388. return unit;
  9389. }
  9390. @ A model is generally quite useless if the data the model contains cannot be
  9391. retrieved. To do this, we check that the index requested is a valid index that
  9392. is within the bounds of the model data and that a role we understand has been
  9393. requested. If none of these conditions are met, a default constructed |QVariant|
  9394. is returned.
  9395. At present, |Qt::DisplayRole| and |Qt::EditRole| are supported. These return the
  9396. same thing. Views will request the display role for presenting the information
  9397. to the user, but they will request the edit role if the user attempts to modify
  9398. the data through a view.
  9399. As of version 1.6, |Qt::UserRole| allows retrieval of raw measurement data.
  9400. @<MeasurementModel Implementation@>=
  9401. QVariant MeasurementModel::data(const QModelIndex &index, int role) const@/
  9402. {@/
  9403. @<Check that the index is valid@>@;
  9404. if(!valid)
  9405. {
  9406. return QVariant();
  9407. }
  9408. MeasurementList *row = entries->at(index.row());
  9409. if(role == Qt::UserRole)
  9410. {
  9411. return QVariant(row->at(index.column()));
  9412. }
  9413. if(role == Qt::DisplayRole || role == Qt::EditRole)
  9414. {
  9415. if(index.column() > row->size())
  9416. {
  9417. return QVariant();
  9418. }
  9419. else
  9420. {
  9421. if(index.column() == 0)
  9422. {
  9423. return QVariant(row->at(0).toTime().toString("mm:ss.zzz"));
  9424. }
  9425. else if(lastTemperature->contains(index.column()))
  9426. {
  9427. QVariantMap v = row->at(index.column()).toMap();
  9428. if(!v.contains("measurement"))
  9429. {
  9430. return QVariant();
  9431. }
  9432. if((Units::Unit)(v.value("unit").toInt()) == Units::Unitless)
  9433. {
  9434. return v.value("measurement");
  9435. }
  9436. else
  9437. {
  9438. if(v.contains("relative"))
  9439. {
  9440. if(v.value("relative").toBool())
  9441. {
  9442. return QVariant(QString("%1").@|arg(Units::convertRelativeTemperature(v.value("measurement").
  9443. toDouble(),@| (Units::Unit)(v.value("unit").toInt()), unit)));
  9444. }
  9445. }
  9446. return QVariant(QString("%1").@|
  9447. arg(Units::convertTemperature(v.value("measurement").toDouble(),@|
  9448. (Units::Unit)(v.value("unit").toInt()), unit)));
  9449. }
  9450. }
  9451. return QVariant(row->at(index.column()).toString());
  9452. }
  9453. }
  9454. return QVariant();@/
  9455. }
  9456. @ Views also must be able to retrieve the header data.
  9457. @<MeasurementModel Implementation@>=
  9458. QVariant MeasurementModel::headerData(int section, Qt::Orientation orientation,
  9459. int role ) const
  9460. {
  9461. if(orientation == Qt::Horizontal)
  9462. {
  9463. if(role == Qt::DisplayRole)
  9464. {
  9465. if(section < hData->size())
  9466. {
  9467. return QVariant(hData->at(section));
  9468. }
  9469. }
  9470. }
  9471. return QVariant();
  9472. }
  9473. @ Views will sometimes request information about the interactions available for
  9474. an index. In the case of this model, each index is treated in the same way.
  9475. It may be a good idea to extend the model class to allow models that can be
  9476. edited through the view such as the table view presented in the |LogEditWindow|
  9477. and models that probably shouldn'@q'@>t be edited in the view, such as the models
  9478. managed by |ZoomLog|. This could be done by subclassing and only reimplementing
  9479. this method. Otherwise, a new method to specify that the user should not edit
  9480. the model could be provided and a flag would be checked here.
  9481. @<MeasurementModel Implementation@>=
  9482. Qt::ItemFlags MeasurementModel::flags(const QModelIndex &index) const@/
  9483. {@/
  9484. @<Check that the index is valid@>@;
  9485. if(valid)
  9486. {
  9487. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
  9488. }
  9489. return 0;
  9490. }
  9491. @ Much of the way models are interacted with in Qt'@q'@>s model view architecture is
  9492. through model indices. The model is responsible for creating these indices from
  9493. row column pairs.
  9494. @<MeasurementModel Implementation@>=
  9495. QModelIndex MeasurementModel::index(int row, int column,
  9496. const QModelIndex &parent) const@t\2\2@>@/
  9497. {@t\1@>@/
  9498. if(parent == QModelIndex())@/
  9499. {@t\1@>@/
  9500. if(row < entries->size() && entries->isEmpty() == false)@/
  9501. {@/
  9502. if(column < entries->at(row)->size())@/
  9503. {@/
  9504. return createIndex(row, column);@/
  9505. }@/
  9506. }@t\2@>@/
  9507. }@/
  9508. return QModelIndex();@/
  9509. @t\4@>}
  9510. @** Annotating roast data.
  9511. \noindent In addition to recording time temperature pairs, \pn{} allows the user
  9512. to annotate the roasting log to indicate control changes, the end of the batch,
  9513. or samples collected from the roast. It is important that these annotations can
  9514. be applied to the roasting log quickly. This is the purpose of the
  9515. |AnnotationButton| class.
  9516. @<Class declarations@>=
  9517. class AnnotationButton : public QPushButton@/
  9518. {@t\1@>@/
  9519. Q_OBJECT@;
  9520. QString noteTemplate;
  9521. QString note;
  9522. int tc;
  9523. int ac;
  9524. int count;
  9525. QString batch;
  9526. public:@/
  9527. AnnotationButton(const QString &text, QWidget *parent = NULL);@/
  9528. @t\4@>public slots@t\kern-3pt@>:@/
  9529. void setAnnotation(const QString &annotation);
  9530. void setTemperatureColumn(int tempcolumn);
  9531. void setAnnotationColumn(int annotationcolumn);
  9532. void annotate();
  9533. void resetCount();
  9534. void resetBatch();
  9535. void incrementBatch();
  9536. signals:@/
  9537. void annotation(QString annotation, int tempcolumn,
  9538. int notecolumn);@t\2@>@/
  9539. }@t\kern-3pt@>;
  9540. @ Setting up a new annotation button begins with the constructor. This takes a
  9541. string specifying the text that will appear on the button and optionally a
  9542. parent widget. This is also a sensible place to set up the desired behavior the
  9543. button should exhibit when clicked.
  9544. @<AnnotationButton Implementation@>=
  9545. AnnotationButton::AnnotationButton(const QString &text, QWidget *parent) :
  9546. QPushButton(text, parent), noteTemplate(""), note(""), tc(0), ac(0),
  9547. count(0), batch("A")@/
  9548. {
  9549. connect(this, SIGNAL(clicked()), this, SLOT(annotate()));
  9550. }
  9551. @ The slot that is called when the button is clicked needs to be able to handle
  9552. two types of annotations. Simple annotations send the same annotation every time
  9553. the button is clicked. Counting annotations are annotation strings that have a
  9554. |"%1"| somewhere in the string. That substring will be replaced with an integer
  9555. that is incremented before the annotation is sent. This integer is initialized
  9556. to 0. It will be incremented to 1 the first time the button is clicked and that
  9557. will be the replacement value.
  9558. @<AnnotationButton Implementation@>=
  9559. void AnnotationButton::annotate()
  9560. {
  9561. if(note.contains("%1"))
  9562. {
  9563. count++;
  9564. emit annotation(note.arg(count), tc, ac);
  9565. }
  9566. else
  9567. {
  9568. emit annotation(note, tc, ac);
  9569. }
  9570. }
  9571. @ A few methods are available to indicate which temperature series the
  9572. annotation should be applied to, which column in a table view the annotation
  9573. should be entered in, and what text should be in the annotation.
  9574. @<AnnotationButton Implementation@>=
  9575. void AnnotationButton::setTemperatureColumn(int tempcolumn)
  9576. {
  9577. tc = tempcolumn;
  9578. }
  9579. void AnnotationButton::setAnnotationColumn(int annotationcolumn)
  9580. {
  9581. ac = annotationcolumn;
  9582. }
  9583. void AnnotationButton::setAnnotation(const QString &annotation)
  9584. {
  9585. noteTemplate = annotation;
  9586. @<Replace batch holder in template@>@;
  9587. }
  9588. @ Note templates that contain "%A" should have that replaced with a
  9589. string that can be incremented between batches.
  9590. @<Replace batch holder in template@>=
  9591. int batchReplace = noteTemplate.indexOf("%A");
  9592. if(batchReplace >= 0)
  9593. {
  9594. QString temp = noteTemplate;
  9595. note = temp.replace(batchReplace, 2, batch);
  9596. }
  9597. else
  9598. {
  9599. note = noteTemplate;
  9600. }
  9601. @ In the case of counting annotations, there should be a way to reset
  9602. the number and batch used in the annotation.
  9603. @<AnnotationButton Implementation@>=
  9604. void AnnotationButton::resetCount()
  9605. {
  9606. count = 0;
  9607. }
  9608. void AnnotationButton::resetBatch()
  9609. {
  9610. batch = "A";
  9611. @<Replace batch holder in template@>@;
  9612. }
  9613. @ The batch sequence starts at A through Z, then proceeds to AA through AZ
  9614. and so on.
  9615. @<AnnotationButton Implementation@>=
  9616. void AnnotationButton::incrementBatch()
  9617. {
  9618. int position = batch.size() - 1;
  9619. increment:
  9620. if(batch[position] != 'Z')
  9621. {
  9622. batch[position] = batch[position].unicode() + 1;
  9623. }
  9624. else
  9625. {
  9626. batch[position] = 'A';
  9627. if(position > 0)
  9628. {
  9629. position--;
  9630. goto increment;
  9631. }
  9632. else
  9633. {
  9634. batch.append("A");
  9635. }
  9636. }
  9637. @<Replace batch holder in template@>@;
  9638. }
  9639. @ A script constructor is needed to allow an |AnnotationButton| to be created
  9640. from a script.
  9641. @<Function prototypes for scripting@>=
  9642. QScriptValue constructAnnotationButton(QScriptContext *context,
  9643. QScriptEngine *engine);
  9644. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine);
  9645. @ In order to use this, the engine needs to be informed of the function.
  9646. @<Set up the scripting engine@>=
  9647. constructor = engine->newFunction(constructAnnotationButton);
  9648. value = engine->newQMetaObject(&AnnotationButton::staticMetaObject,
  9649. constructor);
  9650. engine->globalObject().setProperty("AnnotationButton", value);
  9651. @ The implementation is trivial.
  9652. @<Functions for scripting@>=
  9653. QScriptValue constructAnnotationButton(QScriptContext *context,
  9654. QScriptEngine *engine)
  9655. {
  9656. QScriptValue object =
  9657. engine->newQObject(new AnnotationButton(argument<QString>(0, context)));
  9658. setAnnotationButtonProperties(object, engine);
  9659. return object;
  9660. }
  9661. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine)
  9662. {
  9663. setQPushButtonProperties(value, engine);
  9664. }
  9665. @* A spin box for annotations.
  9666. \noindent While the annotation button is adequate for most log annotation tasks,
  9667. there are some times where the log should contain a small number of numerical
  9668. observations where it is inconvenient or cost prohibitive to enable automated
  9669. logging. For these tasks, a spin box that produces an appropriate annotation may
  9670. be useful.
  9671. @<Class declarations@>=
  9672. class AnnotationSpinBox : public QDoubleSpinBox@/
  9673. {@t\1@>@/
  9674. Q_OBJECT@;
  9675. QString pretext;
  9676. QString posttext;
  9677. int tc;
  9678. int ac;
  9679. bool change;
  9680. public:
  9681. AnnotationSpinBox(const QString &pret, const QString &postt,
  9682. QWidget *parent = NULL);@/
  9683. @t\4@>public slots@t\kern-3pt@>:@/
  9684. void setPretext(const QString &pret);
  9685. void setPosttext(const QString &postt);
  9686. void setTemperatureColumn(int tempcolumn);
  9687. void setAnnotationColumn(int annotationcolumn);
  9688. void annotate();
  9689. void resetChange();
  9690. signals:@/
  9691. void annotation(QString annotation, int tempcolumn,
  9692. int notecolumn);@t\2@>@/
  9693. }@t\kern-3pt@>;
  9694. @ Setting up a new annotation spin box begins with the constructor. This takes
  9695. two strings specifying optional text that may appear before or after the
  9696. numerical value of the spin box in the annotation. No spaces are placed between
  9697. the text and the numerical values, so if such spacing is required, it must be
  9698. included in the relevant string.
  9699. This function also sets up the behavior for firing annotation events. An
  9700. annotation should be fired when the user presses enter while the spin box has
  9701. focus. This implementation will also attempt to fire an annotation when the
  9702. spin box loses focus. No annotation is fired if the value of the spin box has
  9703. not been changed since the previous annotation event.
  9704. @<AnnotationSpinBox Implementation@>=
  9705. AnnotationSpinBox::AnnotationSpinBox(const QString &pret,
  9706. const QString &postt,@|
  9707. QWidget *parent)
  9708. : QDoubleSpinBox(parent), pretext(pret), posttext(postt)@/
  9709. {
  9710. resetChange();
  9711. connect(this, SIGNAL(editingFinished()), this, SLOT(annotate()));
  9712. connect(this, SIGNAL(valueChanged(double)), this, SLOT(resetChange()));
  9713. }
  9714. @ The |resetChange()| signal just sets a boolean which is checked prior to
  9715. sending an annotation. This is called automatically when the value of the spin
  9716. box is changed, but it should also be called when a batch is finished in case
  9717. the first required annotation is the same as the last required annotation from
  9718. the previous batch.
  9719. @<AnnotationSpinBox Implementation@>=
  9720. void AnnotationSpinBox::resetChange()@t\2\2@>@/
  9721. {@t\1@>@/
  9722. change = true;@t\2@>@/
  9723. }
  9724. @ The annotation slot is responsible for determining if an annotation should be
  9725. sent. The current implementation is to only attempt to send such a signal when
  9726. the |editingFinished()| signal is emitted, however this could also be connected
  9727. to other signals.
  9728. @<AnnotationSpinBox Implementation@>=
  9729. void AnnotationSpinBox::annotate()@t\2\2@>@/
  9730. {@t\1@>@/
  9731. if(change)@/
  9732. {@t\1@>@/
  9733. change = false;@/
  9734. emit annotation(QString("%1%2%3").arg(pretext).
  9735. arg(value()).arg(posttext), tc, ac);@t\2@>@/
  9736. }@t\2@>@/
  9737. }
  9738. @ These methods set various properties of the annotation.
  9739. @<AnnotationSpinBox Implementation@>=
  9740. void AnnotationSpinBox::setTemperatureColumn(int tempcolumn)
  9741. {
  9742. tc = tempcolumn;
  9743. }
  9744. void AnnotationSpinBox::setAnnotationColumn(int annotationcolumn)
  9745. {
  9746. ac = annotationcolumn;
  9747. }
  9748. void AnnotationSpinBox::setPretext(const QString &pret)
  9749. {
  9750. pretext = pret;
  9751. }
  9752. void AnnotationSpinBox::setPosttext(const QString &postt)
  9753. {
  9754. posttext = postt;
  9755. }
  9756. @ Two functions are needed to interface |AnnotationSpinBox| with the host
  9757. environment. Additional functions are required for setting up inheritance
  9758. properly.
  9759. @<Function prototypes for scripting@>=
  9760. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  9761. QScriptEngine *engine);
  9762. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9763. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9764. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9765. @ The first of these is passed into the host environment.
  9766. @<Set up the scripting engine@>=
  9767. constructor = engine->newFunction(constructAnnotationSpinBox);
  9768. value = engine->newQMetaObject(&AnnotationSpinBox::staticMetaObject,
  9769. constructor);
  9770. engine->globalObject().setProperty("AnnotationSpinBox", value);
  9771. @ The script constructor creates a new object and passes it to a function that
  9772. is responsible for setting up properties in the inheritance chain.
  9773. @<Functions for scripting@>=
  9774. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  9775. QScriptEngine *engine)
  9776. {
  9777. QScriptValue object = engine->newQObject(new AnnotationSpinBox(
  9778. argument<QString>(0, context), argument<QString>(1, context)));
  9779. setAnnotationSpinBoxProperties(object, engine);
  9780. return object;
  9781. }
  9782. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9783. {
  9784. setQDoubleSpinBoxProperties(value, engine);
  9785. }
  9786. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9787. {
  9788. setQAbstractSpinBoxProperties(value, engine);
  9789. }
  9790. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9791. {
  9792. setQWidgetProperties(value, engine);
  9793. }
  9794. @** A digital timer.
  9795. \noindent Before \pn{} was a data logger, it was a simple digital timer written
  9796. because there were no shops in Racine that could sell a simple dual digital
  9797. count up timer at a time when my first timer was malfunctioning. After
  9798. attempting to purchase a replacement device at several stores that have sold
  9799. such devices in the past, I decided to spend a couple hours writing my own
  9800. timer.
  9801. For historical reasons, the |TimerDisplay| class is considerably more functional
  9802. than \pn{} requires. Those needing only a digital timer can extract the code for
  9803. this class and use it in a timer application. This should work on any platform
  9804. supported by Qt.
  9805. @<Class declarations@>=
  9806. class TimerDisplay : public QLCDNumber@/
  9807. {@t\1@>@/
  9808. Q_OBJECT@/
  9809. @<TimerDisplay Properties@>@;
  9810. @t\4@>private slots@t\kern-3pt@>:@/
  9811. void updateTime();
  9812. void setCountUpMode();
  9813. void setCountDownMode();
  9814. void setClockMode();
  9815. public:@/
  9816. TimerDisplay(QWidget *parent = NULL);
  9817. ~TimerDisplay();
  9818. enum TimerMode
  9819. {
  9820. CountUp,
  9821. CountDown,
  9822. Clock
  9823. };
  9824. QString value();
  9825. QTime seconds();
  9826. TimerMode mode();
  9827. bool isRunning();
  9828. QTime resetValue();
  9829. QString displayFormat();
  9830. bool autoReset();@/
  9831. @t\4@>public slots@t\kern-3pt@>:@/
  9832. void setTimer(QTime value = QTime(0, 0, 0));
  9833. void setMode(TimerMode mode);
  9834. void startTimer();
  9835. void stopTimer();
  9836. void copyTimer();
  9837. void setResetValue(QTime value = QTime(0, 0, 0));
  9838. void reset();
  9839. void setDisplayFormat(QString format);
  9840. void setAutoReset(bool reset);
  9841. void updateDisplay();
  9842. signals:@/
  9843. void valueChanged(QTime);
  9844. void runStateChanged(bool);@/
  9845. private:@/
  9846. @<TimerDisplay Private Variables@>@;@t\2@>@/
  9847. }@t\kern-3pt@>;
  9848. @ Qt provides a property system based on its meta-object system. This allows for
  9849. a number of advanced features which \pn{} does not use. The properties available
  9850. for the TimerDisplay class exist for historical reasons, but there are some
  9851. plans for future development which may make use of them. The properties may also
  9852. be useful for someone using this class in another program.
  9853. @<TimerDisplay Properties@>=
  9854. Q_PROPERTY(QTime seconds READ seconds WRITE setTimer)@/
  9855. Q_PROPERTY(TimerMode mode READ mode WRITE setMode)@/
  9856. Q_PROPERTY(bool running READ isRunning)@/
  9857. Q_PROPERTY(QTime resetValue READ resetValue WRITE setResetValue)@/
  9858. Q_PROPERTY(QString displayFormat READ displayFormat WRITE setDisplayFormat)@/
  9859. Q_PROPERTY(bool autoReset READ autoReset WRITE setAutoReset)@/
  9860. Q_PROPERTY(QString value READ value)@/
  9861. @ A number of private variables are used to implement this class.
  9862. @<TimerDisplay Private Variables@>=
  9863. QTime s;
  9864. QTime r;
  9865. QTimer clock;
  9866. TimerDisplay::TimerMode m;
  9867. bool running;
  9868. bool ar;
  9869. QAction *startAction;
  9870. QAction *stopAction;
  9871. QAction *resetAction;
  9872. QString f;
  9873. QTime relative;
  9874. QTime base;
  9875. @ |TimerDisplay| is a specialization of |QLCDNumber| designed for time keeping
  9876. purposes. It sets up a timer that fires roughly every half second to see if it
  9877. needs to update itself. The constructor sets this up, but does not start the
  9878. timer. The class provides three actions which can be used to start, stop, or
  9879. reset the timer. These actions are also set up in the constructor.
  9880. By default, the timer will display its time in hours, minutes, and seconds. This
  9881. can be changed as is done with the batch timer (it is expected that nobody will
  9882. want to spend an hour or more to roast a batch of coffee). The display style is
  9883. also changed to a sensible default, but this can be changed with the usual
  9884. |QLCDNumber| methods.
  9885. @<TimerDisplay Implementation@>=
  9886. TimerDisplay::TimerDisplay(QWidget *parent) : QLCDNumber(8, parent),
  9887. s(QTime(0, 0, 0)), r(QTime(0, 0, 0)), clock(NULL),@/ m(TimerDisplay::CountUp),
  9888. running(false), ar(false), startAction(new QAction(tr("Start"), NULL)),@/
  9889. stopAction(new QAction(tr("Stop"), NULL)),
  9890. resetAction(new QAction(tr("Reset"), NULL)),@/ f(QString("hh:mm:ss")),
  9891. relative(QTime::currentTime()), base(QTime(0, 0, 0))@/
  9892. {
  9893. connect(startAction, SIGNAL(triggered(bool)), this, SLOT(startTimer()));
  9894. connect(stopAction, SIGNAL(triggered(bool)), this, SLOT(stopTimer()));
  9895. connect(resetAction, SIGNAL(triggered(bool)), this, SLOT(reset()));
  9896. clock.setInterval(500);
  9897. clock.setSingleShot(false);
  9898. connect(&clock, SIGNAL(timeout()), this, SLOT(updateTime()));
  9899. setSegmentStyle(Filled);
  9900. updateDisplay();
  9901. }
  9902. @ The complicated bits are all in the |updateTime()| method. The behavior of
  9903. this function depends on the current |TimerMode| of the display.
  9904. @<TimerDisplay Implementation@>=
  9905. void TimerDisplay::updateTime()
  9906. {
  9907. QTime time;
  9908. int cseconds = 0;
  9909. int oseconds = 0;
  9910. int r = 0;
  9911. QTime nt = QTime(0, 0, 0);
  9912. int n = 0;
  9913. int bseconds = 0;
  9914. switch(m)@/
  9915. {@t\1@>@/
  9916. case TimerDisplay::CountUp:@/
  9917. @<Check for Timer Increment@>;
  9918. break;
  9919. case TimerDisplay::CountDown:@/
  9920. @<Check for Timer Decrement@>;
  9921. break;
  9922. case TimerDisplay::Clock:@/
  9923. @<Check for Clock Change@>;
  9924. break;
  9925. default:@/
  9926. Q_ASSERT_X(false, "updateTime", "invalid timer mode");
  9927. break;@t\2@>@/
  9928. }
  9929. updateDisplay();
  9930. }
  9931. @ To have the timer count up, we calculate the value that the timer should
  9932. indicate and compare it to the time indicated. If there is a difference, we
  9933. update the time to the new value and send emit a signal.
  9934. @<Check for Timer Increment@>=
  9935. @<Load seconds since base time into r@>@;
  9936. nt = nt.addSecs(r);
  9937. if(nt != s)
  9938. {
  9939. s = nt;
  9940. emit valueChanged(s);
  9941. }
  9942. @ Here we want to calculate the number of seconds in the current time, the
  9943. number of seconds in a base time, and the difference between the two. The
  9944. value loaded into oseconds could probably be cached.
  9945. @<Load seconds since base time into r@>=
  9946. #define TIMETOINT(t) ((t.hour() * 60 * 60) + (t.minute() * 60) + (t.second()))
  9947. time = QTime::currentTime();
  9948. cseconds = TIMETOINT(time);
  9949. oseconds = TIMETOINT(relative);
  9950. r = cseconds - oseconds;
  9951. @ The logic for a count down timer is very similar to the logic for a count up
  9952. timer. A key difference is that we don'@q'@>t want to continue counting down if the
  9953. timer has already reached 0.
  9954. @<Check for Timer Decrement@>=
  9955. if(s > QTime(0, 0, 0))@/
  9956. {@/
  9957. @<Load seconds since base time into r@>@;
  9958. bseconds = TIMETOINT(base);
  9959. n = bseconds - r;
  9960. nt = nt.addSecs(n);
  9961. if(nt != s)
  9962. {
  9963. s = nt;
  9964. emit valueChanged(s);
  9965. }
  9966. } else {
  9967. stopTimer();
  9968. }
  9969. @ The clock mode is the simplest case as it just needs to find out if the time
  9970. has changed.
  9971. @<Check for Clock Change@>=
  9972. time = QTime::currentTime();
  9973. if(time != s)
  9974. {
  9975. s = time;
  9976. emit valueChanged(s);
  9977. }
  9978. @ When counting up or down, it is important to record the time at which the
  9979. timer starts. The clock that triggers time updates must also be started. The
  9980. timer also needs to reset its value if that behavior is desired.
  9981. @<TimerDisplay Implementation@>=
  9982. #define TIMESUBTRACT(t1, t2) (t1.addSecs(-(TIMETOINT(t2))).addSecs(-t2.msec()))
  9983. void TimerDisplay::startTimer()@t\2\2@>@/
  9984. {@t\1@>@/
  9985. if(!running)@/
  9986. {@t\1@>@/
  9987. relative = QTime::currentTime();
  9988. if(ar)@/
  9989. {
  9990. reset();
  9991. }
  9992. else
  9993. {
  9994. relative = TIMESUBTRACT(relative, s);
  9995. }
  9996. if(m == Clock)@/
  9997. {
  9998. updateTime();
  9999. }
  10000. base = s;
  10001. clock.start();@/
  10002. running = true;
  10003. emit runStateChanged(true);@t\2@>@/
  10004. }@t\2@>@/
  10005. }
  10006. @ Stopping the timer is a little simpler. Remember to stop the clock so we
  10007. aren'@q'@>t updating senselessly.
  10008. @<TimerDisplay Implementation@>=
  10009. void TimerDisplay::stopTimer()@t\2\2@>@/
  10010. {@t\1@>@/
  10011. if(running)@/
  10012. {@t\1@>@/
  10013. clock.stop();@/
  10014. running = false;
  10015. emit runStateChanged(false);@t\2@>@/
  10016. }@t\2@>@/
  10017. }
  10018. @ The clock is also stopped in the destructor.
  10019. @<TimerDisplay Implementation@>=
  10020. TimerDisplay::~TimerDisplay()
  10021. {
  10022. clock.stop();
  10023. }
  10024. @ The rest of the functions are trivial. There are functions for changing the
  10025. timer mode:
  10026. @<TimerDisplay Implementation@>=
  10027. void TimerDisplay::setCountUpMode()
  10028. {
  10029. m = TimerDisplay::CountUp;
  10030. }
  10031. void TimerDisplay::setCountDownMode()
  10032. {
  10033. m = TimerDisplay::CountDown;
  10034. }
  10035. void TimerDisplay::setClockMode()
  10036. {
  10037. m = TimerDisplay::Clock;
  10038. }
  10039. @ There are a few functions to obtain information about the state of the timer.
  10040. @<TimerDisplay Implementation@>=
  10041. QString TimerDisplay::value()
  10042. {
  10043. return s.toString(f);
  10044. }
  10045. QTime TimerDisplay::seconds()
  10046. {
  10047. return s;
  10048. }
  10049. TimerDisplay::TimerMode TimerDisplay::mode()
  10050. {
  10051. return m;
  10052. }
  10053. bool TimerDisplay::isRunning()
  10054. {
  10055. return running;
  10056. }
  10057. QTime TimerDisplay::resetValue()
  10058. {
  10059. return r;
  10060. }
  10061. QString TimerDisplay::displayFormat()
  10062. {
  10063. return f;
  10064. }
  10065. bool TimerDisplay::autoReset()
  10066. {
  10067. return ar;
  10068. }
  10069. @ There are also some functions for setting aspects of the timer state.
  10070. @<TimerDisplay Implementation@>=
  10071. void TimerDisplay::setTimer(QTime value)
  10072. {
  10073. if(value.isValid())
  10074. {
  10075. s = value;
  10076. updateDisplay();
  10077. emit valueChanged(value);
  10078. }
  10079. }
  10080. void TimerDisplay::setMode(TimerDisplay::TimerMode mode)
  10081. {
  10082. m = mode;
  10083. }
  10084. void TimerDisplay::setResetValue(QTime value)
  10085. {
  10086. r = value;
  10087. }
  10088. void TimerDisplay::setDisplayFormat(QString format)
  10089. {
  10090. f = format;
  10091. setNumDigits(format.length());
  10092. }
  10093. void TimerDisplay::setAutoReset(bool reset)
  10094. {
  10095. ar = reset;
  10096. }
  10097. @ |TimerDisplay| supports using the system clipboard to copy the current timer
  10098. value.
  10099. @<TimerDisplay Implementation@>=
  10100. void TimerDisplay::copyTimer()
  10101. {
  10102. QApplication::clipboard()->setText(value());
  10103. }
  10104. @ Resetting the timer is simple. We don'@q'@>t reset the timer if it is still running
  10105. mainly to prevent accidents.
  10106. @<TimerDisplay Implementation@>=
  10107. void TimerDisplay::reset()
  10108. {
  10109. if(!running)
  10110. {
  10111. s = r;
  10112. updateDisplay();
  10113. }
  10114. }
  10115. @ Finally, there is the function for changing the text of the display to the
  10116. current time value.
  10117. @<TimerDisplay Implementation@>=
  10118. void TimerDisplay::updateDisplay()
  10119. {
  10120. display(value());
  10121. }
  10122. @ Exposing |TimerDisplay| to the host environment is simple.
  10123. @<Function prototypes for scripting@>=
  10124. QScriptValue constructTimerDisplay(QScriptContext *context,
  10125. QScriptEngine *engine);
  10126. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine);
  10127. QScriptValue TimerDisplay_setTimerMode(QScriptContext *context, QScriptEngine *engine);
  10128. @ The engine must be informed of the script constructor.
  10129. @<Set up the scripting engine@>=
  10130. constructor = engine->newFunction(constructTimerDisplay);
  10131. value = engine->newQMetaObject(&TimerDisplay::staticMetaObject, constructor);
  10132. engine->globalObject().setProperty("TimerDisplay", value);
  10133. @ The implementation of these functions is trivial.
  10134. @<Functions for scripting@>=
  10135. QScriptValue constructTimerDisplay(QScriptContext *, QScriptEngine *engine)
  10136. {
  10137. QScriptValue object = engine->newQObject(new TimerDisplay);
  10138. setTimerDisplayProperties(object, engine);
  10139. return object;
  10140. }
  10141. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine)
  10142. {
  10143. setQLCDNumberProperties(value, engine);
  10144. value.setProperty("setTimerMode", engine->newFunction(TimerDisplay_setTimerMode));
  10145. }
  10146. @ A new feature in \pn{} 1.6.4 benefits from having the ability to set the
  10147. timer mode from a script. Rather than exposing the |enum| responsible for this
  10148. to the host environment, a new function is provided to allow integer based
  10149. setting.
  10150. @<Functions for scripting@>=
  10151. QScriptValue TimerDisplay_setTimerMode(QScriptContext *context, QScriptEngine *)
  10152. {
  10153. TimerDisplay *self = getself<TimerDisplay *>(context);
  10154. if(self)
  10155. {
  10156. switch(argument<int>(0, context))
  10157. {
  10158. case 0:
  10159. self->setMode(TimerDisplay::CountUp);
  10160. break;
  10161. case 1:
  10162. self->setMode(TimerDisplay::CountDown);
  10163. break;
  10164. case 2:
  10165. self->setMode(TimerDisplay::Clock);
  10166. break;
  10167. default:
  10168. break;
  10169. }
  10170. }
  10171. return QScriptValue();
  10172. }
  10173. @** The Human Computer Interface.
  10174. \noindent A few classes are required for putting the rest of the program
  10175. together in a way that it can be used by a human. There is a layout class for
  10176. arranging widgets in a way that is not simple with the layouts provided by Qt.
  10177. There are classes for labeling the various indicators. There are also window
  10178. classes that put all of this together in a useful and usable way. One of these
  10179. classes is currently depreciated.
  10180. @* The PackLayout Class.
  10181. \noindent The |PackLayout| class provides functionality similar to the
  10182. |QBoxLayout| class in Qt. It allows the construction of a row or column of
  10183. widgets. Each item will take up space along the orientation of the layout equal
  10184. to its size hint except for the last widget which will take up all remaining
  10185. space. Widgets will be resized in the direction perpendicular to the orientation
  10186. of the layout to use all available space.
  10187. This class was originally written with the |WidgetDecorator| class which we will
  10188. get to later in mind, but it has found use in other places where the left or top
  10189. most widgets should not be resized.
  10190. By default, a new |PackLayout| will arrange widgets horizontally. This can be
  10191. changed with a call to |setOrientation()|.
  10192. @<Class declarations@>=
  10193. class PackLayout : public QLayout@/
  10194. {@/
  10195. int doLayout(const QRect &rect, bool testOnly) const;@/
  10196. QList<QLayoutItem *> itemList;@/
  10197. Qt::Orientations@, orientation;@/
  10198. public:@/
  10199. PackLayout(QWidget *parent, int margin = 0, int spacing = -1);
  10200. PackLayout(int spacing = -1);
  10201. ~PackLayout();
  10202. void addItem(QLayoutItem *item);
  10203. Qt::Orientations@, expandingDirections() const;
  10204. bool hasHeightForWidth() const;
  10205. int heightForWidth(int width) const;
  10206. int count() const;
  10207. QLayoutItem *itemAt(int index) const;
  10208. QSize minimumSize() const;
  10209. void setGeometry(const QRect &rect);
  10210. void setOrientation(Qt::Orientations direction);
  10211. QSize sizeHint() const;
  10212. QLayoutItem *takeAt(int index);
  10213. };
  10214. @ The interesting portion of this class is in |doLayout()|. This function goes
  10215. over the items in the layout and sets the geometry appropriately.
  10216. The seemingly odd choice of returning |y| at the end of this function (indeed of
  10217. having a return value at all) is to allow this function to provide the return
  10218. value needed in |heightForWidth()|.
  10219. If |testOnly| is set to |true|, |y| will be calculated, but the widget geometry
  10220. will not be changed.
  10221. @<PackLayout Implementation@>=
  10222. int PackLayout::doLayout(const QRect &rect, bool testOnly) const
  10223. {
  10224. int x = rect.x();
  10225. int y = rect.y();
  10226. QLayoutItem *item;
  10227. if(orientation == Qt::Horizontal)
  10228. {
  10229. @<Lay the widgets out horizontally@>@;
  10230. }
  10231. else
  10232. {
  10233. @<Lay the widgets out vertically@>@;
  10234. }
  10235. return y;
  10236. }
  10237. @ To lay the widgets out horizontally, we go over each item in the list taking
  10238. the width of the size hint and spacing into account unless the item is the last
  10239. item in the list, in which case the right of the widget needs to be at the end
  10240. of the available space. We use the foreach construction that Qt provides to
  10241. iterate over each item in the list in much the same way as foreach constructions
  10242. are used in languages that support them directly.
  10243. @<Lay the widgets out horizontally@>=
  10244. foreach(item, itemList)
  10245. {
  10246. int nextX = x + item->sizeHint().width() + spacing();
  10247. int right = x + item->sizeHint().width();
  10248. if(item == itemList.last())
  10249. {
  10250. right = rect.right();
  10251. }
  10252. int bottom = rect.bottom();
  10253. if(!testOnly)
  10254. {
  10255. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  10256. }
  10257. x = nextX;
  10258. }
  10259. @ Laying out the widgets vertically is very similar.
  10260. @<Lay the widgets out vertically@>=
  10261. foreach(item, itemList)
  10262. {
  10263. int nextY = y + item->sizeHint().height() + spacing();
  10264. int bottom = y + item->sizeHint().height();
  10265. if(item == itemList.last())
  10266. {
  10267. bottom = rect.bottom();
  10268. }
  10269. int right = rect.right();
  10270. if(!testOnly)
  10271. {
  10272. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  10273. }
  10274. y = nextY;
  10275. }
  10276. @ As a layout class, there are a number of things the class should be able to do
  10277. in order to play nicely with other classes. One of these is determining the
  10278. minimum size of the layout. The minimum size of the layout is equal to the space
  10279. required for each item in the layout plus the margin space. The margin space
  10280. will be equal to twice the specified margin in each direction to account for a
  10281. top, bottom, left, and right margin.
  10282. @<PackLayout Implementation@>=
  10283. QSize PackLayout::minimumSize() const
  10284. {
  10285. QSize size;
  10286. QLayoutItem *item;
  10287. foreach(item, itemList)
  10288. {
  10289. if(orientation == Qt::Horizontal)
  10290. {
  10291. size += QSize(item->minimumSize().width(), 0);
  10292. if(size.height() < item->minimumSize().height())
  10293. {
  10294. size.setHeight(item->minimumSize().height());
  10295. }
  10296. }
  10297. else
  10298. {
  10299. size += QSize(0, item->minimumSize().height());
  10300. if(size.width() < item->minimumSize().width())
  10301. {
  10302. size.setWidth(item->minimumSize().width());
  10303. }
  10304. }
  10305. }
  10306. size += QSize(2*margin(), 2*margin());
  10307. return size;
  10308. }
  10309. @ |PackLayout| features two constructors. One allows for setting the margin,
  10310. spacing, and a parent widget at the time of construction. The other creates a
  10311. parentless layout which will have to be added to another widget or layout.
  10312. @<PackLayout Implementation@>=
  10313. PackLayout::PackLayout(QWidget *parent, int margin, int spacing) :
  10314. QLayout(parent)@/
  10315. {
  10316. setMargin(margin);
  10317. setSpacing(spacing);
  10318. setOrientation(Qt::Horizontal);
  10319. }
  10320. PackLayout::PackLayout(int spacing)
  10321. {
  10322. setSpacing(spacing);
  10323. setOrientation(Qt::Horizontal);
  10324. }
  10325. @ In Qt, items in a layout are owned by that layout. When the layout is
  10326. destroyed, all of the items in that layout must also be deleted.
  10327. @<PackLayout Implementation@>=
  10328. PackLayout::~PackLayout()
  10329. {
  10330. QLayoutItem *item;
  10331. while((item = takeAt(0)))
  10332. {
  10333. delete item;
  10334. }
  10335. }
  10336. @ Deleting the items uses the |takeAt()| method to remove each widget from the
  10337. layout prior to deleting it. The item requested should exist, but if it doesn'@q'@>t,
  10338. |NULL| is returned.
  10339. @<PackLayout Implementation@>=
  10340. QLayoutItem* PackLayout::takeAt(int index)
  10341. {
  10342. if(index >= 0 && index < itemList.size())
  10343. {
  10344. return itemList.takeAt(index);
  10345. }
  10346. else
  10347. {
  10348. return NULL;
  10349. }
  10350. }
  10351. @ If we are interested in which item is in a particular position in the layout
  10352. but do not want to remove it from the layout, |itemAt()| provides that.
  10353. @<PackLayout Implementation@>=
  10354. QLayoutItem* PackLayout::itemAt(int index) const
  10355. {
  10356. if(index >= 0 && index < itemList.size())
  10357. {
  10358. return itemList.at(index);
  10359. }
  10360. else
  10361. {
  10362. return NULL;
  10363. }
  10364. }
  10365. @ A layout class is not very useful unless there is a way to get items into the
  10366. layout. The |QLayoutItem| class is designed in such a way that it is possible to
  10367. pass pointers to objects that inherit |QLayout| or |QWidget|.
  10368. The base |QLayout| class provides an |addWidget()| method that will use our
  10369. version of |addItem()|. That should be used when adding a widget to the layout.
  10370. The Qt documentation recommends also providing an |addLayout()| method so that
  10371. other code does not need to call this method, but that has not been provided
  10372. yet.
  10373. @<PackLayout Implementation@>=
  10374. void PackLayout::addItem(QLayoutItem *item)
  10375. {
  10376. itemList.append(item);
  10377. }
  10378. @ It is sometimes useful to know how many items are in a layout.
  10379. @<PackLayout Implementation@>=
  10380. int PackLayout::count() const@;@/
  10381. {@/
  10382. return itemList.size();@/
  10383. }
  10384. @ A few more functions are needed to make the layout class work well with other
  10385. classes. For more details, please consult the Qt Reference
  10386. Documentation\nfnote{Qt Reference Documentation\par\indent\hbox{%
  10387. \pdfURL{http://doc.trolltech.com/4.3/index.html}%
  10388. {http://doc.trolltech.com/4.3/index.html}}}
  10389. @<PackLayout Implementation@>=
  10390. Qt::Orientations PackLayout::expandingDirections() const
  10391. {
  10392. return Qt::Vertical | Qt::Horizontal;
  10393. }
  10394. bool PackLayout::hasHeightForWidth() const@t\2\2@>@/
  10395. {@t\1@>@/
  10396. return false;@t\2@>@/
  10397. }@/
  10398. int PackLayout::heightForWidth(int width) const
  10399. {
  10400. return doLayout(QRect(0, 0, width, 0), true);
  10401. }
  10402. void PackLayout::setGeometry(const QRect &rect)
  10403. {
  10404. QLayout::setGeometry(rect);
  10405. doLayout(rect, false);
  10406. }
  10407. QSize PackLayout::sizeHint() const
  10408. {
  10409. return minimumSize();
  10410. }
  10411. @ It was mentioned previously that this layout is capable of lining widgets up
  10412. in a row or presenting them in a column. This is done with the
  10413. |setOrientation()| method.
  10414. @<PackLayout Implementation@>=
  10415. void PackLayout::setOrientation(Qt::Orientations direction)
  10416. {
  10417. orientation = direction;
  10418. doLayout(geometry(), false);
  10419. }
  10420. @* The SceneButton Class.
  10421. \noindent Ordinarily, mouse down events that are passed from a |QGraphicsView|
  10422. to an interactive |QGraphicsScene| will continue to pass that click down to an
  10423. item in the scene. This class is used when we are interested in a click anywhere
  10424. in the view and it doesn'@q'@>t really matter where in the scene that click occurred
  10425. or even if there is a graphics item at that point. Any click passed to the
  10426. |SceneButton| will cause the scene to emit a signal containing the screen
  10427. coordinates of the click.
  10428. This was originally designed for use in the |WidgetDecorator| class. While the
  10429. functionality provided is not currently used, the original plan was to use this
  10430. to provide access to configuration options.
  10431. It is possible that this class is no longer necessary even if features it was
  10432. made for are implemented.
  10433. @<Class declarations@>=
  10434. class SceneButton : public QGraphicsScene@/
  10435. {@/
  10436. Q_OBJECT@;
  10437. public:@/
  10438. SceneButton();
  10439. ~SceneButton();
  10440. protected:@/
  10441. void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
  10442. signals:@/
  10443. void clicked(QPoint pos);
  10444. };
  10445. @ The implementation is trivial.
  10446. @<SceneButton Implementation@>=
  10447. SceneButton::SceneButton() : QGraphicsScene()@/
  10448. {
  10449. /* Nothing has to be done here. */
  10450. }
  10451. SceneButton::~SceneButton()
  10452. {
  10453. /* Nothing has to be done here. */
  10454. }
  10455. void SceneButton::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
  10456. {
  10457. emit clicked(mouseEvent->buttonDownScreenPos(mouseEvent->button()));
  10458. }
  10459. @* The WidgetDecorator Class.
  10460. \noindent The |WidgetDecorator| class provides a way to label various widgets
  10461. while also providing additional options for interacting with them. The
  10462. decoration can exist to the left or atop the widget being decorated. When the
  10463. label is to the left of the widget, the label text is rotated.
  10464. This class is likely to change considerably in the future as features are added
  10465. that allow actions to be added to the decoration to allow various configuration
  10466. options.
  10467. @<Class declarations@>=
  10468. class WidgetDecorator : public QWidget@/
  10469. {
  10470. Q_OBJECT@;
  10471. PackLayout *layout;
  10472. QGraphicsView *label;
  10473. QGraphicsTextItem *text;
  10474. SceneButton *scene;
  10475. public:@/
  10476. WidgetDecorator(QWidget *widget, const QString &labeltext,@|
  10477. Qt::Orientations@, orientation = Qt::Horizontal,@|
  10478. QWidget *parent = NULL, Qt::WindowFlags f = 0);
  10479. ~WidgetDecorator();
  10480. void setBackgroundBrush(QBrush background);
  10481. void setTextColor(QColor color);
  10482. };
  10483. @ Almost everything this class currently does is handled in the constructor.
  10484. @<WidgetDecorator Implementation@>=
  10485. WidgetDecorator::WidgetDecorator(QWidget *widget, const QString &labeltext,
  10486. Qt::Orientations orientation,
  10487. QWidget *parent, Qt::WindowFlags f)@/:
  10488. QWidget(parent, f), label(new QGraphicsView()),
  10489. scene(new SceneButton())@t\2@>@/
  10490. {
  10491. layout = new PackLayout(this);
  10492. layout->setOrientation(orientation);
  10493. @<Prepare the graphics view@>@;
  10494. @<Add the label to the scene@>@;
  10495. @<Adjust the decoration width@>@;
  10496. @<Pack widgets into the layout@>@;
  10497. }
  10498. @ The decoration is a |QGraphicsView|. To get this to look right, we need to
  10499. make sure there aren'@q'@>t any scroll bars and there shouldn'@q'@>t be a frame
  10500. surrounding it. While we'@q'@>re at it, we allow it to accept clicks, though this
  10501. functionality is not yet used.
  10502. @<Prepare the graphics view@>=
  10503. label->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  10504. label->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  10505. label->setFrameShape(QFrame::NoFrame);
  10506. label->setInteractive(true);
  10507. @ The |QGraphicsView| needs a scene to display anything. The scene consists of a
  10508. background which, by default is solid cyan. This can be changed later by setting
  10509. a different background brush. Text also needs to be added to the scene. If the
  10510. decoration is to the left of the widget, the text needs to be rotated.
  10511. @<Add the label to the scene@>=
  10512. scene->setBackgroundBrush(Qt::cyan);
  10513. text = scene->addText(labeltext);
  10514. if(orientation == Qt::Horizontal)
  10515. {
  10516. text->rotate(270.0);
  10517. }
  10518. label->setScene(scene);
  10519. @ The decoration should have the text centered in the view. The widget should
  10520. also be no wider (or taller for horizontal orientation) than necessary for the
  10521. text.
  10522. The case for horizontal orientation here may seem a little strange, however the
  10523. dimensions of the bounding rectangle are not affected by rotation. This means
  10524. that even though we want the width of the rotated text, this is the same as the
  10525. height of the text.
  10526. @<Adjust the decoration width@>=
  10527. if(orientation == Qt::Horizontal)
  10528. {
  10529. label->setMaximumWidth((int)(text->boundingRect().height() + 1));
  10530. }
  10531. else
  10532. {
  10533. label->setMaximumHeight((int)(text->boundingRect().height() + 1));
  10534. }
  10535. label->centerOn(text);
  10536. @ Once the decoration is ready, the decoration and the widget being decorated
  10537. can be added to the layout. A minimum size for the compound widget is also
  10538. calculated.
  10539. @<Pack widgets into the layout@>=
  10540. layout->addWidget(label);
  10541. layout->addWidget(widget);
  10542. if(orientation == Qt::Horizontal)
  10543. {
  10544. setMinimumSize(widget->sizeHint().width() + label->sizeHint().width(),
  10545. widget->sizeHint().height());
  10546. }
  10547. else
  10548. {
  10549. setMinimumSize(widget->sizeHint().width(),
  10550. widget->sizeHint().height() + label->sizeHint().height());
  10551. }
  10552. @ As mentioned previously, it is possible to change the background pattern for
  10553. the decoration. It is also possible to change the color of the text.
  10554. @<WidgetDecorator Implementation@>=
  10555. void WidgetDecorator::setBackgroundBrush(QBrush background)
  10556. {
  10557. scene->setBackgroundBrush(background);
  10558. }
  10559. void WidgetDecorator::setTextColor(QColor color)
  10560. {
  10561. text->setDefaultTextColor(color);
  10562. }
  10563. @ Finally, there is a destructor.
  10564. @<WidgetDecorator Implementation@>=
  10565. WidgetDecorator::~WidgetDecorator()
  10566. {
  10567. /* Nothing has to be done here. */
  10568. }
  10569. @ In order to create a decorated widget from a script, we need these functions.
  10570. @<Function prototypes for scripting@>=
  10571. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine);
  10572. QScriptValue constructWidgetDecorator(QScriptContext *context,
  10573. QScriptEngine *engine);
  10574. @ The scripting engine must be informed of this function.
  10575. @<Set up the scripting engine@>=
  10576. constructor = engine->newFunction(constructWidgetDecorator);
  10577. value = engine->newQMetaObject(&WidgetDecorator::staticMetaObject, constructor);
  10578. engine->globalObject().setProperty("WidgetDecorator", value);
  10579. @ The constructor is slightly more complex than other script constructors, but
  10580. still simple.
  10581. @<Functions for scripting@>=
  10582. QScriptValue constructWidgetDecorator(QScriptContext *context,
  10583. QScriptEngine *engine)
  10584. {
  10585. QWidget *widget = argument<QWidget *>(0, context);
  10586. QString text = argument<QString>(1, context);
  10587. Qt::Orientations@, orientation;
  10588. switch(argument<int>(2, context))@/
  10589. {@t\1@>@/
  10590. case 2:@/
  10591. orientation = Qt::Vertical;
  10592. break;
  10593. default:@/
  10594. orientation = Qt::Horizontal;
  10595. break;@t\2@>@/
  10596. }
  10597. QScriptValue object =
  10598. engine->newQObject(new WidgetDecorator(widget, text, orientation));
  10599. setWidgetDecoratorProperties(object, engine);
  10600. return object;
  10601. }
  10602. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine)
  10603. {
  10604. setQWidgetProperties(value, engine);
  10605. }
  10606. @* The LogEditWindow Class.
  10607. \noindent This class will be depreciated in a future release once I have
  10608. confirmed that the class can be replaced by the configuration system. It has not
  10609. been updated to support new functionality added in version 1.2.3 and use of this
  10610. class is highly discouraged.
  10611. While the logging window provided in the example configuration is fine for
  10612. recording an existing roast, there are some who would like to be able to use
  10613. \pn{} to work with data collected with a manual logger. Different controls are
  10614. useful in such a case. The |LogEditWindow| provides this.
  10615. @<Class declarations@>=
  10616. class LogEditWindow : public QMainWindow@/
  10617. {@t\1@>@/
  10618. Q_OBJECT@;
  10619. QWidget *centralWidget;
  10620. PackLayout *mainLayout;
  10621. QHBoxLayout *addRowsLayout;
  10622. QLabel *startTimeLabel;
  10623. QTimeEdit *startTime;
  10624. QLabel *endTimeLabel;
  10625. QTimeEdit *endTime;
  10626. QLabel *intervalLabel;
  10627. QSpinBox *interval;
  10628. QPushButton *addRows;
  10629. QAction *saveXml;
  10630. QAction *saveCsv;
  10631. QAction *openXml;
  10632. MeasurementModel *model;
  10633. QTableView *log;@/
  10634. @t\4@>private slots@t\kern-3pt@>:@/
  10635. void addTheRows();
  10636. void saveXML();
  10637. void saveCSV();
  10638. void openXML();@/
  10639. protected:@/
  10640. void closeEvent(QCloseEvent *event);@/
  10641. public:@/
  10642. LogEditWindow();@t\2@>@/
  10643. }@t\kern-3pt@>;
  10644. @ This window provides controls for adding rows to a measurement. Typically, the
  10645. data on a manual roast log will have measurements at regular intervals with the
  10646. possible exception of a few points where there are control changes or the end of
  10647. the batch. The routine for adding rows is capable of adding a single row, rows
  10648. in a range of times at regular intervals, or rows in a range of times at regular
  10649. intervals plus one time at the end.
  10650. @<LogEditWindow Implementation@>=
  10651. void LogEditWindow::addTheRows()
  10652. {
  10653. QTime s = startTime->time();
  10654. while(s < endTime->time())
  10655. {
  10656. model->newMeasurement(Measurement(0, s), 1);
  10657. s = s.addSecs(interval->value());
  10658. }
  10659. model->newMeasurement(Measurement(0, endTime->time()), 1);
  10660. }
  10661. @ The window is prepared in its constructor.
  10662. @<LogEditWindow Implementation@>=
  10663. LogEditWindow::LogEditWindow() : QMainWindow(NULL),
  10664. centralWidget(new QWidget(NULL)), mainLayout(new PackLayout(0)),@|
  10665. addRowsLayout(new QHBoxLayout(NULL)),
  10666. startTimeLabel(new QLabel("Start Time")),@|
  10667. startTime(new QTimeEdit(QTime(0, 0, 0, 0))),@|
  10668. endTimeLabel(new QLabel("End Time")),
  10669. endTime(new QTimeEdit(QTime(0, 20, 0, 0))),@|
  10670. intervalLabel(new QLabel("Interval (seconds)")),@|
  10671. interval(new QSpinBox()),
  10672. addRows(new QPushButton("Add Rows")),@|
  10673. saveXml(new QAction(tr("Save Profile As..."), NULL)),@|
  10674. saveCsv(new QAction(tr("Export CSV"), NULL)),@|
  10675. openXml(new QAction(tr("Load Target Profile..."), NULL)),@|
  10676. model(new MeasurementModel()),
  10677. log(new QTableView())@/
  10678. {
  10679. @<Restore editor window geometry from settings@>@;
  10680. @<Set up the editor control bar@>@;
  10681. @<Prepare the model@>@;
  10682. @<Prepare the log table@>@;
  10683. mainLayout->addItem(addRowsLayout);
  10684. mainLayout->addWidget(log);
  10685. centralWidget->setLayout(mainLayout);
  10686. setCentralWidget(centralWidget);
  10687. QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
  10688. fileMenu->addAction(openXml);
  10689. connect(openXml, SIGNAL(triggered()), this, SLOT(openXML()));
  10690. fileMenu->addAction(saveXml);
  10691. connect(saveXml, SIGNAL(triggered()), this, SLOT(saveXML()));
  10692. fileMenu->addAction(saveCsv);
  10693. connect(saveCsv, SIGNAL(triggered()), this, SLOT(saveCSV()));
  10694. }
  10695. @ The window keeps its previous size and location in settings. These need to be
  10696. restored when a new window is created.
  10697. @<Restore editor window geometry from settings@>=
  10698. QSettings settings;
  10699. resize(settings.value("logSize", QSize(620,400)).toSize());
  10700. move(settings.value("logPos", QPoint(200,60)).toPoint());
  10701. @ When a new window is opened, it starts with an empty profile. If this is used
  10702. to manually enter a profile rather than edit an existing profile, rows will need
  10703. to be added. For this, we provide a set of controls where a start time, an end
  10704. time, and an interval in seconds is specified along with a button that, when
  10705. pressed, will produce a row in the model for the starting time, the ending time,
  10706. and regularly spaced times between the two. If only a single row is needed, this
  10707. can be produced by setting the start and end times the same.
  10708. @<Set up the editor control bar@>=
  10709. mainLayout->setOrientation(Qt::Vertical);
  10710. addRowsLayout->addSpacing(10);
  10711. addRowsLayout->addWidget(startTimeLabel);
  10712. addRowsLayout->addWidget(startTime);
  10713. addRowsLayout->addSpacing(10);
  10714. startTime->setDisplayFormat("mm:ss");
  10715. addRowsLayout->addWidget(endTimeLabel);
  10716. addRowsLayout->addWidget(endTime);
  10717. addRowsLayout->addSpacing(10);
  10718. endTime->setDisplayFormat("mm:ss");
  10719. addRowsLayout->addWidget(intervalLabel);
  10720. addRowsLayout->addWidget(interval);
  10721. addRowsLayout->addSpacing(10);
  10722. interval->setRange(0, 60);
  10723. interval->setValue(30);
  10724. addRowsLayout->addWidget(addRows);
  10725. addRowsLayout->addSpacing(10);
  10726. connect(addRows, SIGNAL(clicked()), this, SLOT(addTheRows()));
  10727. @ The model will have three columns: Time, Temperature, and Annotation. This
  10728. probably should not be hard coded.
  10729. @<Prepare the model@>=
  10730. model->setHeaderData(0, Qt::Horizontal, "Time");
  10731. model->setHeaderData(1, Qt::Horizontal, "Temperature");
  10732. model->setHeaderData(2, Qt::Horizontal, "Annotation");
  10733. model->clear();
  10734. @ The profile is presented in a table view. The columns should be wide enough to
  10735. contain a label, the data contained in the column, and an editor delegate.
  10736. @<Prepare the log table@>=
  10737. log->setModel(model);
  10738. log->setColumnWidth(0, 100);
  10739. log->setColumnWidth(1, 100);
  10740. log->setColumnWidth(2, 100);
  10741. @ Most users will want to save a profile after they'@q'@>ve edited it. We also
  10742. provide CSV export here. Note that this class only supports logs with a single
  10743. temperature and a single annotation column. As the class is considered
  10744. depreciated, it will not be extended to support arbitrarily many columns.
  10745. @<LogEditWindow Implementation@>=
  10746. void LogEditWindow::saveXML()
  10747. {
  10748. QSettings settings;
  10749. QString lastDir = settings.value("lastDirectory").toString();
  10750. QString filename = QFileDialog::getSaveFileName(this, tr("Save Log As..."),
  10751. lastDir, "", 0);
  10752. QFile file(filename);
  10753. XMLOutput writer(model, &file, 0);
  10754. writer.addTemperatureColumn("Temperature", 1);
  10755. writer.addAnnotationColumn("Annotation", 2);
  10756. if(writer.output())
  10757. {
  10758. QFileInfo info(filename);
  10759. QDir directory = info.dir();
  10760. lastDir = directory.path();
  10761. settings.setValue("lastDirectory", lastDir);
  10762. }
  10763. }
  10764. void LogEditWindow::saveCSV()
  10765. {
  10766. QSettings settings;
  10767. QString lastDir = settings.value("lastDirectory").toString();
  10768. QString filename = QFileDialog::getSaveFileName(this, tr("Export As..."),
  10769. lastDir, "", 0);
  10770. QFile file(filename);
  10771. CSVOutput writer(model, &file, 0);
  10772. writer.addTemperatureColumn("Temperature", 1);
  10773. writer.addAnnotationColumn("Annotation", 2);
  10774. if(writer.output())
  10775. {
  10776. QFileInfo info(filename);
  10777. QDir directory = info.dir();
  10778. lastDir = directory.path();
  10779. settings.setValue("lastDirectory", lastDir);
  10780. }
  10781. }
  10782. @ Some may want to open a previously saved profile, for example, to adjust the
  10783. position of an annotation. Note that this class is not appropriate for editing
  10784. profiles with more than one temperature column.
  10785. @<LogEditWindow Implementation@>=
  10786. void LogEditWindow::openXML()
  10787. {
  10788. QSettings settings;
  10789. QString lastDir = settings.value("lastDirectory").toString();
  10790. QString filename = QFileDialog::getOpenFileName(this, tr("Open XML Log..."),
  10791. lastDir, "", 0);
  10792. if(filename.isNull())
  10793. {
  10794. return;
  10795. }
  10796. QFile file(filename);
  10797. XMLInput reader(&file, 1);
  10798. connect(&reader, SIGNAL(measure(Measurement, int)),
  10799. model, SLOT(newMeasurement(Measurement, int)));
  10800. connect(&reader, SIGNAL(annotation(QString, int, int)),
  10801. model, SLOT(newAnnotation(QString, int, int)));
  10802. if(reader.input())
  10803. {
  10804. QFileInfo info(filename);
  10805. setWindowTitle(QString(tr("%1 - %2")).@|
  10806. arg(QCoreApplication::applicationName()).arg(info.baseName()));
  10807. QDir directory = info.dir();
  10808. lastDir = directory.path();
  10809. settings.setValue("lastDirectory", lastDir);
  10810. }
  10811. }
  10812. @ The window should remember its last size and position, so we store this
  10813. information in settings when the window is closed.
  10814. @<LogEditWindow Implementation@>=
  10815. void LogEditWindow::closeEvent(QCloseEvent *event)
  10816. {
  10817. QSettings settings;
  10818. settings.setValue("logSize", size());
  10819. settings.setValue("logPos", pos());
  10820. event->accept();
  10821. }
  10822. @ One function is required to instantiate this class from a script.
  10823. @<Function prototypes for scripting@>=
  10824. QScriptValue constructLogEditWindow(QScriptContext *context,
  10825. QScriptEngine *engine);
  10826. @ The engine must be informed of this function.
  10827. @<Set up the scripting engine@>=
  10828. constructor = engine->newFunction(constructLogEditWindow);
  10829. value = engine->newQMetaObject(&LogEditWindow::staticMetaObject, constructor);
  10830. engine->globalObject().setProperty("LogEditWindow", value);
  10831. @ The constructor just creates the window and passes it back to the engine.
  10832. @<Functions for scripting@>=
  10833. QScriptValue constructLogEditWindow(QScriptContext *, QScriptEngine *engine)
  10834. {
  10835. QScriptValue object = engine->newQObject(new LogEditWindow);
  10836. return object;
  10837. }
  10838. @** File IO.
  10839. \noindent So far, the data is all stored in memory. It is often useful to save
  10840. data to a file or read back previously saved data. Presently, two formats are
  10841. supported: an XML format which can also be read back in and CSV which can easily
  10842. be used with many external tools.
  10843. File IO is handled by a few classes: one per input format and one per output
  10844. format. The classes in the following sections should be simple enough to follow
  10845. that it should be clear how to extend \pn{} to support other formats if needed.
  10846. Should additional output formats be required, it may be beneficial to
  10847. reimplement the serializers as subclasses of a new abstract serializer class in
  10848. order to share common code among them where reusing \cweb{} chunks is not an
  10849. appropriate technique.
  10850. @* XML Output.
  10851. \noindent An XML format has been chosen as the native format for \pn{} because
  10852. of Qt'@q'@>s excellent support for reading and writing such documents. Using this
  10853. capability is less error prone than developing a new, more compact format.
  10854. Another reason to choose XML is that it becomes quite easy to modify saved data
  10855. in a text editor and still end up with something \pn{} will understand.
  10856. The structure of the file we will produce is simple, however it has been
  10857. modified from a simpler structure that was used in versions of Typica prior to
  10858. 1.2.3. How to read these files can be determined by the document type found at
  10859. the start of the file. At the start of the file, there should be one or more
  10860. {\tt <tempseries>} elements and one or more {\tt <noteseries>} elements. These
  10861. are empty elements with a {\tt name} attribute which can be used to label the
  10862. column in a view. Once these column declarations have been written, a
  10863. {\tt <roast>} element is produced which contains a set of zero or more
  10864. {\tt <tuple>} elements. Each tuple contains one {\tt <time>} element containing
  10865. the time of the measurement relative to the start of the batch and optionally
  10866. one or more {\tt <temperature>} and {\tt <annotation>} elements containing
  10867. measurement and annotation data associated with that time. The
  10868. {\tt <temperature>} and {\tt <annotation>} elements have a {\tt series}
  10869. attribute where the value of the attribute matches the {\tt name} attribute of a
  10870. {\tt <tempseries>} or {\tt <noteseries>} element which allows each measurement
  10871. to be placed in the correct data series regardless of element ordering in the
  10872. document.
  10873. There are certain oddities about this format compared with other XML based
  10874. formats. The order of some elements in the current implementation affects the
  10875. behavior of the program and there is no longer a proper root element. This
  10876. format may be extended in future versions of \pn{} to support additional
  10877. functionality or to improve the robustness of the format. Should such
  10878. modifications occur, an effort should be made to ensure that \pn{} continues to
  10879. support the import of old data.
  10880. As of version 1.0.8, this class is derived from |QObject| for easier integration
  10881. with the scripting engine.
  10882. The |temperatureColumns| and |annotationColumns| member data structures are
  10883. currently a |QMap| rather than a |QHash| because the number of data series in a
  10884. single file is likely to be small enough that the difference in lookup time
  10885. should be negligeable and the ability to iterate over the keys in the |QMap| in
  10886. sorted order is useful.
  10887. @<Class declarations@>=
  10888. class XMLOutput : public QObject@/
  10889. {@/
  10890. Q_OBJECT@;@/
  10891. MeasurementModel *data;
  10892. QIODevice *out;
  10893. int time;
  10894. QMap<int, QString> temperatureColumns;
  10895. QMap<int, QString> controlColumns;
  10896. QMap<int, QString> annotationColumns;
  10897. public:@/
  10898. XMLOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  10899. void addTemperatureColumn(const QString &series, int column);
  10900. void addControlColumn(const QString &series, int column);
  10901. void addAnnotationColumn(const QString &series, int column);
  10902. void setModel(MeasurementModel *model);
  10903. void setTimeColumn(int column);
  10904. void setDevice(QIODevice *device);
  10905. bool output();
  10906. };
  10907. @ The interesting part of this class is the |output| routine. This goes over the
  10908. data in the model and constructs an appropriate XML document. If the operation
  10909. fails, the function returns |false|, otherwise it returns |true|.
  10910. @<XMLOutput Implementation@>=
  10911. bool XMLOutput::output()@t\2\2@>@/
  10912. {@t\1@>@/
  10913. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  10914. {@t\1@>@/
  10915. return false;@t\2@>@/
  10916. }@/
  10917. QXmlStreamWriter xmlout(out);
  10918. xmlout.writeStartDocument("1.0");
  10919. xmlout.writeDTD("<!DOCTYPE roastlog3.0>");
  10920. xmlout.writeStartElement("roastlog");
  10921. @<Output the column declarations@>@;
  10922. xmlout.writeStartElement("roast");
  10923. bool oresult;
  10924. for(int i = 0; i < data->rowCount(); i++)@/
  10925. {
  10926. @<Check if row should be output@>@;
  10927. if(oresult)
  10928. {
  10929. @<Output tuple element@>@;
  10930. }
  10931. }
  10932. xmlout.writeEndElement();
  10933. xmlout.writeEndElement();
  10934. xmlout.writeEndDocument();
  10935. out->close();@/
  10936. return true;@t\2@>@/
  10937. }
  10938. @ Temperature column declarations are output before annotation column
  10939. declarations. Within each category, column declarations are output in order by
  10940. column number.
  10941. @<Output the column declarations@>=
  10942. foreach(int c, temperatureColumns.keys())
  10943. {
  10944. xmlout.writeStartElement("tempseries");
  10945. xmlout.writeAttribute("name", temperatureColumns.value(c));
  10946. xmlout.writeEndElement();
  10947. }
  10948. foreach(int c, controlColumns.keys())
  10949. {
  10950. xmlout.writeStartElement("controlseries");
  10951. xmlout.writeAttribute("name", controlColumns.value(c));
  10952. xmlout.writeEndElement();
  10953. }
  10954. foreach(int c, annotationColumns.keys())
  10955. {
  10956. xmlout.writeStartElement("noteseries");
  10957. xmlout.writeAttribute("name", annotationColumns.value(c));
  10958. xmlout.writeEndElement();
  10959. }
  10960. @ When checking a row in the model to determine if it contains values that need
  10961. to be written, we want to know if any of the temperature or annotation columns
  10962. contain a value. If at least one of these columns is not empty for this row, we
  10963. need to output a tuple for that row.
  10964. @<Check if row should be output@>=
  10965. oresult = false;@/
  10966. foreach(int c, temperatureColumns.keys())@/
  10967. {@t\1@>@/
  10968. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10969. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10970. {@t\1@>@/
  10971. oresult = true;
  10972. break;@t\2@>@/
  10973. }@t\2@>@/
  10974. }@/
  10975. foreach(int c, controlColumns.keys())
  10976. {
  10977. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10978. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))
  10979. {
  10980. oresult = true;
  10981. break;
  10982. }
  10983. }
  10984. if(oresult == false)@/
  10985. {@t\1@>@/
  10986. foreach(int c, annotationColumns.keys())@/
  10987. {@t\1@>@/
  10988. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10989. !(data->data(data->index(i, c), Qt::DisplayRole).toString().
  10990. isEmpty()))@/
  10991. {@t\1@>@/
  10992. oresult = true;
  10993. break;@t\2@>@/
  10994. }@t\2@>@/
  10995. }@t\2@>@/
  10996. }
  10997. @ Now that we know that values from the current row should be output, we can
  10998. produce a {\tt <tuple>} element, a {\tt <time>} element for that tuple, and then
  10999. iterate over the set of columns we might want to output, producing an
  11000. appropriate element for each non-empty column for that row.
  11001. @<Output tuple element@>=
  11002. xmlout.writeStartElement("tuple");
  11003. xmlout.writeTextElement("time", data->data(data->index(i, time),
  11004. Qt::DisplayRole).toString());
  11005. foreach(int c, temperatureColumns.keys())@/
  11006. {
  11007. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  11008. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  11009. {
  11010. xmlout.writeStartElement("temperature");
  11011. xmlout.writeAttribute("series", temperatureColumns.value(c));
  11012. if(data->data(data->index(i, c), Qt::UserRole).toMap().contains("relative"))
  11013. {
  11014. if(data->data(data->index(i, c), Qt::UserRole).toMap().value("relative").toBool())
  11015. {
  11016. xmlout.writeAttribute("relative", "true");
  11017. }
  11018. }
  11019. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  11020. toString());
  11021. xmlout.writeEndElement();
  11022. }
  11023. }
  11024. foreach(int c, controlColumns.keys())
  11025. {
  11026. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  11027. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))
  11028. {
  11029. xmlout.writeStartElement("control");
  11030. xmlout.writeAttribute("series", controlColumns.value(c));
  11031. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).toString());
  11032. xmlout.writeEndElement();
  11033. }
  11034. }
  11035. foreach(int c, annotationColumns.keys())@/
  11036. {
  11037. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  11038. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  11039. {
  11040. xmlout.writeStartElement("annotation");
  11041. xmlout.writeAttribute("series", annotationColumns.value(c));
  11042. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  11043. toString());
  11044. xmlout.writeEndElement();
  11045. }
  11046. }
  11047. xmlout.writeEndElement();
  11048. @ The rest of the class just initializes the private member data.
  11049. @<XMLOutput Implementation@>=
  11050. XMLOutput::XMLOutput(MeasurementModel *model, QIODevice *device, int timec)
  11051. : QObject(NULL), data(model), out(device), time(timec)@/
  11052. {
  11053. /* Nothing has to be done here. */
  11054. }@;
  11055. void XMLOutput::setModel(MeasurementModel *model)
  11056. {
  11057. data = model;
  11058. }
  11059. void XMLOutput::setTimeColumn(int column)
  11060. {
  11061. time = column;
  11062. }
  11063. void XMLOutput::setDevice(QIODevice *device)
  11064. {
  11065. out = device;
  11066. }
  11067. @ As of version 1.2.3, the old |setTemperatureColumn()| and
  11068. |setAnnotationColumn()| methods have been replaced with the
  11069. |addTemperatureColumn()| and |addAnnotationColumn()| methods respectively. The
  11070. main difference is that the new methods take a column name in addition to a
  11071. number and it is now possible to specify multiple columns of each category for
  11072. export.
  11073. @<XMLOutput Implementation@>=
  11074. void XMLOutput::addTemperatureColumn(const QString &series, int column)
  11075. {
  11076. temperatureColumns.insert(column, series);
  11077. }
  11078. void XMLOutput::addControlColumn(const QString &series, int column)
  11079. {
  11080. controlColumns.insert(column, series);
  11081. }
  11082. void XMLOutput::addAnnotationColumn(const QString &series, int column)
  11083. {
  11084. annotationColumns.insert(column, series);
  11085. }
  11086. @* XML Input.
  11087. \noindent Once model data can be saved to a file, it is useful to be able to
  11088. read that data back in. This is a little different from reading data out of a
  11089. model as more than one object is potentially interested in the data. Instead, we
  11090. emit signals for measurements and annotations. This class has been modified to
  11091. support both the current (as of version 1.2.3) output of the |XMLOutput| class
  11092. and the older version. If changes are made to |XMLOutput| this class may also
  11093. need to be modified.
  11094. The main differences in the current version of this class are that the first
  11095. column is specified rather than specifying temperature and annotation columns
  11096. separately and additional signals are emitted to allow views to prepare for an
  11097. arbitrary number of columns.
  11098. The |newTemperatureColumn| and |newAnnotationColumn| signals can be used to set
  11099. up column headers while the |lastColumn| signal can be used to shift live data
  11100. streams to unoccupied columns.
  11101. @<Class declarations@>=
  11102. class XMLInput : public QObject@/
  11103. {
  11104. Q_OBJECT@;
  11105. int firstc;
  11106. QIODevice *in;
  11107. public:@/
  11108. XMLInput(QIODevice *input, int c);
  11109. void setFirstColumn(int column);
  11110. void setDevice(QIODevice *device);
  11111. bool input();
  11112. signals:@/
  11113. void measure(Measurement, int);
  11114. void annotation(QString, int, int);
  11115. void newTemperatureColumn(int, QString);
  11116. void newAnnotationColumn(int, QString);
  11117. void lastColumn(int);
  11118. };
  11119. @ The main point of interest here is the |input()| method. If the file is read
  11120. successfully, |true| is returned. Otherwise, |false| is returned.
  11121. @<XMLInput Implementation@>=
  11122. bool XMLInput::input()@t\2\2@>@/
  11123. {@t\1@>@/
  11124. if(!in->open(QIODevice::ReadOnly | QIODevice::Text))@/
  11125. {@t\1@>@/
  11126. return false;@t\2@>@/
  11127. }@/
  11128. QXmlStreamReader xmlin(in);
  11129. QMap<QString, int> temperatureColumns;
  11130. QMap<QString, int> annotationColumns;
  11131. int nextColumn = firstc;
  11132. @<Read column declarations@>@;
  11133. QTime timeval = QTime();
  11134. double tempval = 0;
  11135. QString noteval = QString();
  11136. int column;
  11137. int counter = 0;@/
  11138. while(!xmlin.atEnd())@/
  11139. {@/
  11140. @<Read XML file@>@;
  11141. }@/
  11142. return true;@t\2@>@/
  11143. }
  11144. @ A data file may or may not contain elements that specify the name of a column.
  11145. In order to determine how to proceed, we should check the doctype of the input
  11146. file. This should be the first element of the input file encountered.
  11147. \danger There is not nearly enough error checking here.
  11148. \endanger
  11149. @<Read column declarations@>=
  11150. while(!xmlin.isDTD())
  11151. {
  11152. xmlin.readNext();
  11153. }
  11154. if(xmlin.isDTD())
  11155. {
  11156. if(xmlin.text() == "<!DOCTYPE roastlog>")
  11157. {
  11158. @<Emit old format column specification@>@;
  11159. }
  11160. else
  11161. {
  11162. xmlin.readNext();
  11163. @<Scan for column declarations and emit@>@;
  11164. }
  11165. }
  11166. @ Old format data will not have column declarations. This means that we must
  11167. produce a default set of signals rather than waiting to read elements describing
  11168. the columns.
  11169. @<Emit old format column specification@>=
  11170. emit newTemperatureColumn(firstc, "Bean");
  11171. emit newAnnotationColumn(firstc + 1, "Note");
  11172. emit lastColumn(firstc + 1);
  11173. @ The current format will have column declarations prior to the {\tt <roast>}
  11174. element. We can just read until we hit that element and emit the appropriate
  11175. signals as elements are encountered.
  11176. @<Scan for column declarations and emit@>=
  11177. while(xmlin.name() != "roast")
  11178. {
  11179. if(xmlin.isStartElement())
  11180. {
  11181. if((xmlin.name() == "tempseries") || (xmlin.name() == "controlseries"))
  11182. {
  11183. temperatureColumns.insert(xmlin.attributes().value("name").
  11184. toString(),
  11185. nextColumn);
  11186. emit newTemperatureColumn(nextColumn,
  11187. xmlin.attributes().value("name").
  11188. toString());
  11189. nextColumn++;
  11190. }
  11191. else if(xmlin.name() == "noteseries")
  11192. {
  11193. annotationColumns.insert(xmlin.attributes().value("name").
  11194. toString(), nextColumn);
  11195. emit newAnnotationColumn(nextColumn,
  11196. xmlin.attributes().value("name").
  11197. toString());
  11198. nextColumn++;
  11199. }
  11200. }
  11201. xmlin.readNext();
  11202. }
  11203. emit lastColumn(nextColumn - 1);
  11204. @ Now we are ready to read measurements from the file. When encountering a
  11205. {\tt <time>} element, we record the time and move on. For {\tt <temperature>}
  11206. and {\tt <annotation>} elements, we emit the appropriate signal. This is handled
  11207. slightly differently depending on which version of the file format is being
  11208. used. Note that there is not nearly enough error checking here and we are
  11209. basically ignoring {\tt <tuple>} elements.
  11210. Due to the typically large number of measurements taken over the course of a
  11211. roast and the amount of time often taken to process these measurements when they
  11212. are read from a file, there is a need to periodically pass control back to the
  11213. event loop to remain responsive to user input.
  11214. @<Read XML file@>=
  11215. xmlin.readNext();
  11216. if(xmlin.isStartElement())
  11217. {
  11218. @<Read measurement data@>@;
  11219. }
  11220. counter++;
  11221. if(counter % 100 == 0)
  11222. {
  11223. QCoreApplication::processEvents();
  11224. }
  11225. @ When reading start elements, it is safe to ignore {\tt <tuple>} and
  11226. {\tt <roast>}. Technically, this means that the program can read certain types
  11227. of invalid data. The Robustness Principle\nfnote{``Be liberal in what you
  11228. accept, and conservative in what you send,'' --- Robert Braden, {\it RFC 1122
  11229. \S 1.2.2}} is generally applicable to any type of data exchange. That said,
  11230. malformed data is not guaranteed readable in the future, even if it does work
  11231. now.
  11232. \danger One set of test input caused this code to emit an empty annotation for
  11233. every measurement. This is the reason for wrapping the annotation signal
  11234. emission to check for this. The detected annotation elements were not present in
  11235. the input stream and I have absolutely no idea where the program came up with
  11236. them. \endanger
  11237. @<Read measurement data@>=
  11238. if(xmlin.name() == "time")
  11239. {
  11240. timeval = QTime::fromString(xmlin.readElementText(), "mm:ss.zzz");
  11241. }
  11242. else if(xmlin.name() == "temperature")
  11243. {
  11244. column = xmlin.attributes().hasAttribute("series") ?
  11245. temperatureColumns.value(xmlin.attributes().value("series").toString()) : firstc;
  11246. bool relative = (xmlin.attributes().value("relative") == "true");
  11247. tempval = xmlin.readElementText().toDouble();
  11248. Measurement measurement(tempval, timeval);
  11249. if(relative)
  11250. {
  11251. measurement.insert("relative", true);
  11252. }
  11253. emit measure(measurement, column);
  11254. }
  11255. else if(xmlin.name() == "control")
  11256. {
  11257. column = xmlin.attributes().value("series").toString().isEmpty() ?
  11258. firstc : temperatureColumns.value(xmlin.attributes().
  11259. value("series").toString());
  11260. tempval = xmlin.readElementText().toDouble();
  11261. Measurement measurement(tempval, timeval, Units::Unitless);
  11262. emit measure(measurement, column);
  11263. }
  11264. else if(xmlin.name() == "annotation")
  11265. {
  11266. column = xmlin.attributes().value("series").toString().isEmpty() ?
  11267. firstc + 1 : annotationColumns.value(xmlin.attributes().
  11268. value("series").toString());
  11269. noteval = xmlin.readElementText();
  11270. if(!noteval.isEmpty())
  11271. {
  11272. emit annotation(noteval, firstc, column);
  11273. }
  11274. }
  11275. @ The other methods just set the private member data.
  11276. @<XMLInput Implementation@>=
  11277. XMLInput::XMLInput(QIODevice *input, int c) :
  11278. firstc(c), in(input)@/
  11279. {@/
  11280. /* Nothing has to be done here. */
  11281. }
  11282. void XMLInput::setFirstColumn(int column)
  11283. {
  11284. firstc = column;
  11285. }
  11286. void XMLInput::setDevice(QIODevice *device)
  11287. {
  11288. in = device;
  11289. }
  11290. @ In order to allow scripts to instantiate the |XMLInput| class, we need a
  11291. constructor and a wrapper around the |input()| method.
  11292. @<Function prototypes for scripting@>=
  11293. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine);
  11294. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *engine);
  11295. @ The script constructor is passed to the scripting engine.
  11296. @<Set up the scripting engine@>=
  11297. constructor = engine->newFunction(constructXMLInput);
  11298. value = engine->newQMetaObject(&XMLInput::staticMetaObject, constructor);
  11299. engine->globalObject().setProperty("XMLInput", value);
  11300. @ The implementation should seem familiar.
  11301. @<Functions for scripting@>=
  11302. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine)
  11303. {
  11304. QIODevice *device = argument<QIODevice *>(0, context);
  11305. QScriptValue object = engine->newQObject(new XMLInput(&*device,
  11306. argument<int>(1, context)));
  11307. object.setProperty("input", engine->newFunction(XMLInput_input));
  11308. return object;
  11309. }
  11310. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *)
  11311. {
  11312. XMLInput *self = getself<@[XMLInput *@]>(context);
  11313. self->input();
  11314. return QScriptValue();
  11315. }
  11316. @* CSV Output.
  11317. \noindent While XML is convenient for \pn{}, other programs may not handle this
  11318. format well. For this purpose, we use a text file with comma separated values.
  11319. Data in this format can easily be handled by shell scripts, simple programs, and
  11320. any spreadsheet (though some may handle the time column poorly).
  11321. We do not need to concern ourselves with reading data in this format back in,
  11322. but there is no reason a class could not be written to do this.
  11323. The structure of this class is very similar to the |XMLOutput| class.
  11324. @<Class declarations@>=
  11325. class CSVOutput@/
  11326. {@/
  11327. MeasurementModel *data;
  11328. QIODevice *out;
  11329. int time;
  11330. QMap<int, QString> temperatureColumns;
  11331. QMap<int, QString> controlColumns;
  11332. QMap<int, QString> annotationColumns;@/
  11333. public:@/
  11334. CSVOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  11335. void addTemperatureColumn(const QString &series, int column);
  11336. void addControlColumn(const QString &series, int column);
  11337. void addAnnotationColumn(const QString &series, int column);
  11338. void setModel(MeasurementModel *model);
  11339. void setTimeColumn(int column);
  11340. void setDevice(QIODevice *device);
  11341. bool output();@/
  11342. };
  11343. @ Very little needs to be done to output the data. We open the output stream
  11344. and, if the output stream was successfully opened, we look for measurements and
  11345. output the text, remembering to output a comma between items and a newline after
  11346. each record. If the data is successfully output, |true| is returned, otherwise
  11347. we return |false|.
  11348. The comparably simple structure of the CSV format allows us to just fling the
  11349. data onto a text stream.
  11350. @<CSVOutput Implementation@>=
  11351. bool CSVOutput::output()@t\2\2@>@/
  11352. {@t\1@>@/
  11353. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  11354. {@t\1@>@/
  11355. return false;@t\2@>@/
  11356. }@/
  11357. QTextStream output(out);
  11358. @<Output CSV column headers@>@;
  11359. bool oresult;
  11360. for(int i = 0; i < data->rowCount(); i++)@/
  11361. {
  11362. @<Check if row should be output@>@;
  11363. if(oresult)
  11364. {
  11365. @<Output CSV row@>@;
  11366. }
  11367. }
  11368. out->close();@/
  11369. return true;@t\2@>@/
  11370. }
  11371. @ Before writing the data, we output a row containing the name of each column.
  11372. @<Output CSV column headers@>=
  11373. output << "Time";
  11374. foreach(int c, temperatureColumns.keys())
  11375. {
  11376. output << ',' << temperatureColumns.value(c);
  11377. }
  11378. foreach(int c, controlColumns.keys())
  11379. {
  11380. output << ',' << controlColumns.value(c);
  11381. }
  11382. foreach(int c, annotationColumns.keys())
  11383. {
  11384. output << ',' << annotationColumns.value(c);
  11385. }
  11386. output << '\n';
  11387. @ Once the header information has been written, we can proceed to output the
  11388. real data. The algorithm for doing this has been changed as of version 1.2.3
  11389. with the result that most uses will now produce more delimiters than the same
  11390. data in previous versions. This should have no impact on the ability of other
  11391. programs to interact with data produced by \pn{}. The code to handle output in
  11392. this way is much easier to read. A future version might once again suppress
  11393. superfluous commas, however the presence of these commas is not considered a
  11394. serious issue at this time.
  11395. @<Output CSV row@>=
  11396. output << data->data(data->index(i, time), Qt::DisplayRole).toString();
  11397. foreach(int c, temperatureColumns.keys())
  11398. {
  11399. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11400. }
  11401. foreach(int c, controlColumns.keys())
  11402. {
  11403. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11404. }
  11405. foreach(int c, annotationColumns.keys())
  11406. {
  11407. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11408. }
  11409. output << '\n';
  11410. @ The rest of the class just initializes the private member data. See notes
  11411. on the implementation of |XMLOutput|.
  11412. @<CSVOutput Implementation@>=
  11413. CSVOutput::CSVOutput(MeasurementModel *model, QIODevice *device, int timec) :
  11414. data(model), out(device), time(timec)@/
  11415. {
  11416. /* Nothing has to be done here. */
  11417. }@;
  11418. void CSVOutput::setModel(MeasurementModel *model)
  11419. {
  11420. data = model;
  11421. }
  11422. void CSVOutput::setTimeColumn(int column)
  11423. {
  11424. time = column;
  11425. }
  11426. void CSVOutput::addTemperatureColumn(const QString &series, int column)
  11427. {
  11428. temperatureColumns.insert(column, series);
  11429. }
  11430. void CSVOutput::addControlColumn(const QString &series, int column)
  11431. {
  11432. controlColumns.insert(column, series);
  11433. }
  11434. void CSVOutput::addAnnotationColumn(const QString &series, int column)
  11435. {
  11436. annotationColumns.insert(column, series);
  11437. }
  11438. void CSVOutput::setDevice(QIODevice *device)
  11439. {
  11440. out = device;
  11441. }
  11442. @i webview.w
  11443. @i printerselector.w
  11444. @* The Application class.
  11445. The |Application| class represents the \pn{} program. It is responsible for
  11446. setting up the settings object and localization in addition to the normal
  11447. responsibilities of |QApplication|. In addition to declaring the class, we also
  11448. define a macro that returns the |Application| instance.
  11449. @<Class declarations@>=
  11450. #define AppInstance (qobject_cast<@[Application *@]>(qApp))
  11451. class NodeInserter;
  11452. class DeviceTreeModel;
  11453. class DatabaseNotification;
  11454. class Application : public QApplication@/
  11455. {@/
  11456. @[Q_OBJECT@]@;
  11457. public:@/
  11458. Application(int &argc, char **argv);
  11459. QDomDocument* configuration();
  11460. @<Device configuration members@>@;
  11461. QSqlDatabase database();
  11462. Q_INVOKABLE bool databaseConnected();
  11463. Q_INVOKABLE QString currentTypicaUser();
  11464. Q_INVOKABLE bool login(const QString &user, const QString &password);
  11465. Q_INVOKABLE bool autoLogin();
  11466. QScriptEngine *engine;
  11467. QNetworkAccessManager *network;
  11468. DatabaseNotification *subscribe(const QString &notification);@/
  11469. @[public slots@]:@/
  11470. void setDatabaseConnected(bool status);
  11471. void setCurrentTypicaUser(const QString &user);
  11472. void notify(const QString &notification);
  11473. @<Extended Application slots@>@;
  11474. @[signals@]:@/
  11475. void userChanged(const QString &user);
  11476. private:@/
  11477. @<Application private data members@>@;
  11478. QDomDocument conf;
  11479. bool connectionStatus;
  11480. QString currentUser;
  11481. QMap<QString, DatabaseNotification*> notifiers;
  11482. QSqlDriver *notificationDriver;
  11483. };
  11484. @ The constructor for this class handles a few things that had previously been
  11485. handled in |main()|.
  11486. @<Application Implementation@>=
  11487. Application::Application(int &argc, char **argv) : QApplication(argc, argv),
  11488. connectionStatus(false), currentUser(QString())@/
  11489. {
  11490. network = new QNetworkAccessManager(this);
  11491. @<Allow use of the default QSettings constructor@>@;
  11492. @<Load translation objects@>@;
  11493. @<Register meta-types@>@;
  11494. @<Register top level device configuration nodes@>@;
  11495. }
  11496. @ We use |QSettings| objects throughout \pn{} to remember details such as the
  11497. size and position of windows and the most recently used directory. To simplify
  11498. the creation of these objects, we specify some details up front. This allows us
  11499. to use the default constructor rather than specifying these things every time we
  11500. need an object.
  11501. @<Allow use of the default QSettings constructor@>=
  11502. setOrganizationName("Wilson's Coffee & Tea");
  11503. setOrganizationDomain("wilsonscoffee.com");
  11504. setApplicationName(PROGRAM_NAME);
  11505. @ Much of the user visible text in \pn{} is wrapped in a call to |tr()|. Such
  11506. text can be replaced with translated text based on the user'@q'@>s locale. For more
  11507. details, see the Qt Linguist manual.
  11508. @<Load translation objects@>=
  11509. QTranslator *base = new QTranslator;
  11510. if(base->load(QString("qt_%1").arg(QLocale::system().name()), QString("%1/Translations").arg(QCoreApplication::applicationDirPath())))
  11511. {
  11512. installTranslator(base);
  11513. }
  11514. QTranslator *app = new QTranslator;
  11515. if(app->load(QString("%1_%2").arg("Typica").arg(QLocale::system().name()), QString("%1/Translations").arg(QCoreApplication::applicationDirPath())))
  11516. {
  11517. installTranslator(app);
  11518. }
  11519. @ We also want to be able to access the application instance from within the
  11520. scripting engine. We don'@q'@>t need to be able to create new instances, just access the one that already exists.
  11521. @<Set up the scripting engine@>=
  11522. value = engine->newQObject(AppInstance);
  11523. value.setProperty("subscribe", engine->newFunction(Application_subscribe));
  11524. engine->globalObject().setProperty("Application", value);
  11525. @ The |configuration()| method provides access to an XML document containing the
  11526. current application configuration. The object is populated in |main()|.
  11527. @<Application Implementation@>=
  11528. QDomDocument* Application::configuration()
  11529. {
  11530. return &conf;
  11531. }
  11532. @ The |database()| method provides access to a database connection for use by
  11533. database aware widgets.
  11534. @<Application Implementation@>=
  11535. QSqlDatabase Application::database()
  11536. {
  11537. QString connectionName;
  11538. QSqlDatabase connection =
  11539. QSqlDatabase::database(QLatin1String(QSqlDatabase::defaultConnection), false);
  11540. do
  11541. {
  11542. connectionName = QUuid::createUuid().toString();
  11543. } while (QSqlDatabase::connectionNames().contains(connectionName));
  11544. return QSqlDatabase::cloneDatabase(connection, QString(connectionName));
  11545. }
  11546. @ Starting with version 1.8 there are methods for determining if a connection
  11547. to the database was successfully established when Typica was opened.
  11548. @<Application Implementation@>=
  11549. void Application::setDatabaseConnected(bool status)
  11550. {
  11551. connectionStatus = status;
  11552. }
  11553. bool Application::databaseConnected()
  11554. {
  11555. return connectionStatus;
  11556. }
  11557. @ Database notifications allow various parts of Typica to be aware when data in
  11558. the database may have been changed by another instance of Typica running on a
  11559. different computer or by another program that uses the same database. To pass
  11560. notifications to the various places that may be interested in these and not
  11561. bother notification aware controls that are uninterested in unrelated
  11562. notifications, a notification object is created for each notification.
  11563. Note that the notification channel is an identifier and unquoted identifiers
  11564. will be converted to lowercase while \pn{} will attempt to match subscribed to
  11565. notifications exactly. This means that it is generally a good idea to subscribe
  11566. with the channel specified in lowercase.
  11567. @<Application Implementation@>=
  11568. DatabaseNotification* Application::subscribe(const QString &notification)
  11569. {
  11570. DatabaseNotification *retval;
  11571. if(notifiers.contains(notification))
  11572. {
  11573. retval = notifiers.value(notification);
  11574. }
  11575. else
  11576. {
  11577. if(notifiers.size() == 0)
  11578. {
  11579. notificationDriver = QSqlDatabase::database().driver();
  11580. connect(notificationDriver, SIGNAL(notification(QString)), this, SLOT(notify(QString)));
  11581. }
  11582. retval = new DatabaseNotification;
  11583. connect(this, SIGNAL(aboutToQuit()), retval, SLOT(deleteLater()));
  11584. if(notifiers.size() !=
  11585. notificationDriver->subscribedToNotifications().size())
  11586. {
  11587. for(int i = 0; i < notifiers.size(); i++)
  11588. {
  11589. notificationDriver->subscribeToNotification(notifiers.keys().at(i));
  11590. }
  11591. }
  11592. notifiers.insert(notification, retval);
  11593. notificationDriver->subscribeToNotification(notification);
  11594. }
  11595. return retval;
  11596. }
  11597. @ As the various parts of \pn{} operate mostly indepent of each other and
  11598. notifications from the current instance may not be immediately returned, it is
  11599. generally a good idea for operations that would generate a notification to also
  11600. signal that notification within the application.
  11601. @<Application Implementation@>=
  11602. void Application::notify(const QString &notification)
  11603. {
  11604. if(notifiers.contains(notification))
  11605. {
  11606. DatabaseNotification *notifier = notifiers.value(notification);
  11607. notifier->forwardNotification(notification);
  11608. }
  11609. }
  11610. @ A function is provided to allow subscribing to notifications from scripts.
  11611. @<Function prototypes for scripting@>=
  11612. QScriptValue Application_subscribe(QScriptContext *context,
  11613. QScriptEngine *engine);
  11614. @ The implementation is trivial.
  11615. @<Functions for scripting@>=
  11616. QScriptValue Application_subscribe(QScriptContext *context,
  11617. QScriptEngine *engine)
  11618. {
  11619. return engine->newQObject(
  11620. AppInstance->subscribe(argument<QString>(0, context)));
  11621. }
  11622. @ The DatabaseNotification object just needs a signal that interested objects
  11623. can connect to.
  11624. @<Class declarations@>=
  11625. class DatabaseNotification : public QObject
  11626. {
  11627. Q_OBJECT
  11628. public:
  11629. DatabaseNotification();
  11630. public slots:
  11631. void forwardNotification(const QString &notification);
  11632. signals:
  11633. void notify(const QString &notification);
  11634. };
  11635. @ The implementation is trivial.
  11636. @<Class declarations@>=
  11637. DatabaseNotification::DatabaseNotification() : QObject(NULL)
  11638. {
  11639. /* Nothing needs to be done here. */
  11640. }
  11641. void DatabaseNotification::forwardNotification(const QString &notification)
  11642. {
  11643. emit notify(notification);
  11644. }
  11645. @** Table editor for ordered arrays with SQL relations.
  11646. \noindent A database in use at Wilson's Coffee \char'046~Tea stores information
  11647. for a roasting log and uses entered information to adjust inventory tracking
  11648. tables. This roasting log connects the use of unroasted coffee with the creation
  11649. of roasted coffee. In order to support roasting coffee from more than one lot at
  11650. the same time, the columns that specify the types of coffee used and the amount
  11651. of each coffee are entered as ordered arrays in which the first entry in the
  11652. array specifying an unroasted coffee is associated with the first entry in the
  11653. array specifying the amount of coffee used. While most batches will involve only
  11654. a single unroasted coffee, the database has no limitation on the number of
  11655. coffees that may be roasted in a single batch. An additional characteristic of
  11656. this table is that the database requires an identification number for unroasted
  11657. coffee items, but it would be better to provide a list of acceptable items with
  11658. human readable names.
  11659. A scrollable area containing a table view which can provide the necessary input
  11660. delegates (such as a combo box for SQL relations) and validators which ensures
  11661. that there is always at least one empty row available for input with convenience
  11662. functions for extracting the arrays needed for database insertion would be ideal
  11663. for this.
  11664. To get this, we need a simple table model based on |QStandardItemModel|
  11665. or |QAbstractItemModel|. The model should ensure that there is always at least
  11666. one empty row available for editing. It should also provide a function for
  11667. obtaining a string that presents all values from a specified column with a given
  11668. role as an array literal suitable for binding to an SQL query.
  11669. A class based on |QComboBox| providing options selected from an SQL query will
  11670. be needed. This can be used as a standalone widget elsewhere, but here it is
  11671. also needed as an editor class for a column delegate. Another delegate class
  11672. allows input in another column to be constrained by a |QValidator| (in this case
  11673. a |QDoubleValidator|).
  11674. A class based on |QTableView| brings all of these classes together and presents
  11675. them to the user.
  11676. @* A table model for producing SQL array literals.
  11677. \noindent This is a simple table model which provides two somewhat unusual
  11678. features. First, it always provides at least one empty row at the end of the
  11679. data. Second, it provides SQL array literals for columns in the model.
  11680. \danger At some point I would like to replace this model and |MeasurementModel|
  11681. with an improved table model suitable to replace both. Some preliminary design
  11682. work suggests that this improvement simplifies \pn{} considerably both
  11683. internally and in the data flow configuration. This has not yet been done due to
  11684. development time constraints.\endanger
  11685. @<Class declarations@>=
  11686. class SaltModel : public QAbstractItemModel@/
  11687. {
  11688. Q_OBJECT@t\2\2@>@/
  11689. QList<QList<QMap<int, QVariant> > > modelData;
  11690. QStringList hData;
  11691. int colcount;@t\1\1@>@/
  11692. public:@/
  11693. SaltModel(int columns);
  11694. ~SaltModel();
  11695. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  11696. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  11697. bool setHeaderData(int section, Qt::Orientation@, orientation,
  11698. const QVariant &value, int role = Qt::DisplayRole);
  11699. QVariant data(const QModelIndex &index, int role) const;
  11700. bool setData(const QModelIndex &index, const QVariant &value,
  11701. int role = Qt::EditRole);
  11702. Qt::ItemFlags@, flags(const QModelIndex &index) const;
  11703. QVariant headerData(int section, Qt::Orientation@, orientation,
  11704. int role = Qt::DisplayRole) const;
  11705. QModelIndex index(int row, int column,
  11706. const QModelIndex &parent = QModelIndex()) const;
  11707. QModelIndex parent(const QModelIndex &index) const;
  11708. QString arrayLiteral(int column, int role) const;
  11709. QString quotedArrayLiteral(int column, int role) const;
  11710. void clear();
  11711. bool removeRows(int row, int count,
  11712. const QModelIndex &parent = QModelIndex());
  11713. int findData(const QVariant &value, int column, int role = Qt::UserRole);
  11714. };
  11715. @ The only unique methods in this class are the |arrayLiteral| and
  11716. |quotedArrayLiteral| methods. These take a column number and a data role and
  11717. produce a SQL array literal for every entry in that column with the specified
  11718. role. The string will take the form of
  11719. {\tt{'\LB row 1, row 2, }}$\dots$ {\tt{row N\RB '}}.
  11720. This is done simply by starting with a string identifying the start of an array
  11721. literal, looping over the rows in the model while appending any data found along
  11722. with the commas to separate values. If any data is found, the extra comma and
  11723. space are removed from the constructed string. Finally, text marking the end of
  11724. the array literal is added.
  11725. The |arrayLiteral| method is appropriate where the expected values are numeric.
  11726. The |quotedArrayLiteral| method is appropriate where the expected values are
  11727. text. The values in the array will have quotation marks around them for the
  11728. |quotedArrayLiteral|. Note that when binding these values to placeholders in a
  11729. SQL query the leading and trailing single quote characters should be removed.
  11730. \danger The way this method is currently used is quite harmless. Data from one
  11731. column is integer data obtained as a result of a previous database query and
  11732. data from the other column is restricted by the view to numeric data. Please
  11733. note, however, that it would be extremely stupid to use code such as this when
  11734. user input cannot be controlled so tightly. Were this model used with a view
  11735. that allows general text input, it would be trivial to construct an SQL
  11736. injection attack.
  11737. \medskip
  11738. \centerline{\includegraphics[width=6in]{exploits_of_a_mom}}
  11739. \smallskip
  11740. \centerline{Figure \secno: An Example of an SQL injection attack.\nfnote{%
  11741. Comic copyright Randall Munroe. Original can be found at:~%
  11742. \pdfURL{%
  11743. http://xkcd.com/327/}%
  11744. {http://xkcd.com/327/}}}
  11745. \medskip
  11746. \endanger
  11747. @<SaltModel Implementation@>=
  11748. QString SaltModel::arrayLiteral(int column, int role) const
  11749. {
  11750. QString literal = "'{";
  11751. for(int i = 0; i < rowCount(); i++)
  11752. {
  11753. QString datum = data(index(i, column), role).toString();
  11754. if(!datum.isEmpty())
  11755. {
  11756. literal.append(datum);
  11757. literal.append(", ");
  11758. }
  11759. }
  11760. if(literal.size() > 2)
  11761. {
  11762. literal.chop(2);
  11763. }
  11764. literal.append("}'");
  11765. return literal;
  11766. }
  11767. QString SaltModel::quotedArrayLiteral(int column, int role) const
  11768. {
  11769. QString literal = "'{";
  11770. for(int i = 0; i < rowCount(); i++)
  11771. {
  11772. QString datum = data(index(i, column), role).toString();
  11773. if(!datum.isEmpty())
  11774. {
  11775. literal.append("\"");
  11776. literal.append(datum);
  11777. literal.append("\", ");
  11778. }
  11779. }
  11780. if(literal.size() > 2)
  11781. {
  11782. literal.chop(2);
  11783. }
  11784. literal.append("}'");
  11785. return literal;
  11786. }
  11787. @ No entries in this model have children.
  11788. @<SaltModel Implementation@>=
  11789. QModelIndex SaltModel::parent(const QModelIndex &) const
  11790. {
  11791. return QModelIndex();
  11792. }
  11793. @ The |setData()| method is called by delegates on views when the user enters
  11794. new data. This method must check to determine if the data is being entered in
  11795. the last row to increase the size of the table.
  11796. The end of this function may seem a little strange. Why not simply look up the
  11797. map and insert information directly into the model data? Well, as of this
  11798. writing, that doesn'@q'@>t work. There are two ways around that problem. One is to
  11799. have the lists store references and dereference the real data. The other option
  11800. is to obtain a copy of the row, then a copy of the cell, update the cell, then
  11801. replace the old value of the cell in the copy of the row, then replace the old
  11802. values of the row in the real data. The other option would probably be more
  11803. efficient, but this does work.
  11804. @<SaltModel Implementation@>=
  11805. bool SaltModel::setData(const QModelIndex &index, const QVariant &value,
  11806. int role)@t\2\2@>@/
  11807. {@t\1@>@/
  11808. @<Check that the SaltModel index is valid@>@;
  11809. if(!valid)@/
  11810. {@t\1@>@/
  11811. return false;@t\2@>@/
  11812. }
  11813. if(index.row() == modelData.size() - 1)@/
  11814. {
  11815. beginInsertRows(QModelIndex(), modelData.size(), modelData.size());
  11816. @<Expand the SaltModel@>@;
  11817. endInsertRows();
  11818. }
  11819. QList<QMap<int, QVariant> > row = modelData.at(index.row());
  11820. QMap<int, QVariant> cell = row.at(index.column());
  11821. cell.insert(role, value);
  11822. if(role == Qt::EditRole)@/
  11823. {
  11824. cell.insert(Qt::DisplayRole, value);
  11825. }
  11826. row.replace(index.column(), cell);
  11827. modelData.replace(index.row(), row);
  11828. emit dataChanged(index, index);@/
  11829. return true;@t\2@>@/
  11830. }
  11831. @ Some model operations require checking that a model index is valid. This
  11832. chunk is used in these cases.
  11833. @<Check that the SaltModel index is valid@>=
  11834. bool valid = false;@/
  11835. if(index.isValid())@/
  11836. {@t\1@>@/
  11837. if(index.row() < modelData.size())@/
  11838. {@t\1@>@/
  11839. if(index.column() < colcount)@/
  11840. {@t\1@>@/
  11841. valid = true;@t\2@>@/
  11842. }@t\2@>@/
  11843. }@t\2@>@/
  11844. }
  11845. @ When data is modified in the last row of the table, the model must be expanded
  11846. to allow for additional data.
  11847. @<Expand the SaltModel@>=
  11848. QList<QMap<int, QVariant> > newRow;
  11849. QMap<int, QVariant> defaults;
  11850. for(int i = 0; i < colcount; i++)
  11851. {
  11852. newRow.append(defaults);
  11853. }
  11854. modelData.append(newRow);
  11855. @ The number of columns in the table is specified in the model constructor.
  11856. @<SaltModel Implementation@>=
  11857. SaltModel::SaltModel(int columns) : QAbstractItemModel(), colcount(columns)
  11858. {
  11859. for(int i = 0; i < columns; i++)
  11860. {
  11861. hData << "";
  11862. }
  11863. @<Expand the SaltModel@>@;
  11864. }
  11865. @ The destructor doesn'@q'@>t need to do anything.
  11866. @<SaltModel Implementation@>=
  11867. SaltModel::~SaltModel()
  11868. {
  11869. /* Nothing needs to be done here. */
  11870. }
  11871. @ A pair of methods provide the number of rows and columns in the model. No
  11872. entries in the model have children, so the parent should always be the invisible
  11873. root object.
  11874. @<SaltModel Implementation@>=
  11875. int SaltModel::rowCount(const QModelIndex &parent) const
  11876. {
  11877. return (parent == QModelIndex() ? modelData.size() : 0);
  11878. }
  11879. int SaltModel::columnCount(const QModelIndex &parent) const
  11880. {
  11881. return (parent == QModelIndex() ? colcount : 0);
  11882. }
  11883. @ The model maintains header data for labeling the model columns.
  11884. @<SaltModel Implementation@>=
  11885. bool SaltModel::setHeaderData(int section, Qt::Orientation@, orientation,@|
  11886. const QVariant &value, int)@t\2\2@>@/
  11887. {@t\1@>@/
  11888. if(orientation == Qt::Horizontal && section < colcount)@/
  11889. {@t\1@>@/
  11890. hData.replace(section, value.toString());@/
  11891. emit headerDataChanged(orientation, section, section);@/
  11892. return true;@t\2@>@/
  11893. }@/
  11894. return false;@t\2@>@/
  11895. }
  11896. @ Views need to be able to retrieve model and header data.
  11897. @<SaltModel Implementation@>=
  11898. QVariant SaltModel::data(const QModelIndex &index, int role) const
  11899. {
  11900. @<Check that the SaltModel index is valid@>@;
  11901. if(!valid)
  11902. {
  11903. return QVariant();
  11904. }
  11905. QList<QMap<int,QVariant> > row = modelData.at(index.row());
  11906. QMap<int,QVariant> cell = row.at(index.column());
  11907. return cell.value(role, QVariant());
  11908. }
  11909. QVariant SaltModel::headerData(int section, Qt::Orientation@, orientation,
  11910. int role) const
  11911. {
  11912. if(orientation == Qt::Horizontal && role == Qt::DisplayRole &&
  11913. section < colcount)
  11914. {
  11915. return QVariant(hData.at(section));
  11916. }
  11917. return QVariant();
  11918. }
  11919. @ Views need to know certain details such as if an item in the view can be
  11920. altered by the view. For this model, all valid indices can be edited.
  11921. @<SaltModel Implementation@>=
  11922. Qt::ItemFlags SaltModel::flags(const QModelIndex &index) const
  11923. {
  11924. @<Check that the SaltModel index is valid@>@;
  11925. if(valid)
  11926. {
  11927. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled;
  11928. }
  11929. return 0;
  11930. }
  11931. @ So far, many of the methods use model indices. The model is responsible for
  11932. creating these.
  11933. @<SaltModel Implementation@>=
  11934. QModelIndex SaltModel::index(int row, int column,
  11935. const QModelIndex &parent) const
  11936. {
  11937. if(parent == QModelIndex())
  11938. {
  11939. if(row < modelData.size() && column < colcount)
  11940. {
  11941. return createIndex(row, column);
  11942. }
  11943. }
  11944. return QModelIndex();
  11945. }
  11946. @ There are some times when it is useful to clear the model data. Note that
  11947. column header data is retained and the table will contain a single empty row
  11948. after this method is called.
  11949. @<SaltModel Implementation@>=
  11950. void SaltModel::clear()
  11951. {
  11952. beginResetModel();
  11953. modelData.clear();
  11954. @<Expand the SaltModel@>@;
  11955. endResetModel();
  11956. }
  11957. @ Another commonly useful operation is the ability to remove rows from the
  11958. model. The new batch window uses this feature to eliminate rows in which the
  11959. coffee is set to NULL. Note that if all rows of the model are removed, a new
  11960. empty row will be created.
  11961. @<SaltModel Implementation@>=
  11962. bool SaltModel::removeRows(int row, int count,
  11963. const QModelIndex &parent)
  11964. {
  11965. if(parent == QModelIndex())
  11966. {
  11967. if(row >= 0 && count > 0 && (row + count - 1) < modelData.size())
  11968. {
  11969. beginRemoveRows(parent, row, row + count - 1);
  11970. for(int i = 0; i < count; i++)
  11971. {
  11972. modelData.removeAt(row);
  11973. }
  11974. endRemoveRows();
  11975. if(modelData.size() == 0)
  11976. {
  11977. beginInsertRows(parent, 0, 0);
  11978. @<Expand the SaltModel@>@;
  11979. endInsertRows();
  11980. }
  11981. return @[true@];
  11982. }
  11983. }
  11984. return @[false@];
  11985. }
  11986. @ To find the row number for removal operations it is useful to search for
  11987. special values on a given role. The |findData()| method returns the first row
  11988. in which the given value matches for a particular column and a particular role
  11989. or |-1| if no such match exists.
  11990. @<SaltModel Implementation@>=
  11991. int SaltModel::findData(const QVariant &value, int column, int role)
  11992. {
  11993. for(int i = 0; i < modelData.size(); i++)
  11994. {
  11995. if(modelData.at(i).size() > column)
  11996. {
  11997. if(modelData.at(i).at(column).contains(role))
  11998. {
  11999. if(modelData.at(i).at(column).value(role) == value)
  12000. {
  12001. return i;
  12002. }
  12003. }
  12004. }
  12005. }
  12006. return -1;
  12007. }
  12008. @* A Delegate for SQL Relations.
  12009. \noindent The first column of the table view being described is responsible for
  12010. providing item numbers to the database. Requiring that these numbers be entered
  12011. directly is prone to not particularly user friendly and almost encourages input
  12012. errors. These item numbers, however, refer to the items table in the database
  12013. which includes, among other details, a human readable text string naming the
  12014. item. This delegate provides the user with a drop down menu from which such a
  12015. string may be selected with this information provided by the database itself.
  12016. When the user selects an item, it informs the model not only of the text string
  12017. in the display role, but also of the id number in a user data role which can
  12018. later be queried in order to properly craft the appropriate query.
  12019. This is implemented with two classes. The first is a |QComboBox| which queries
  12020. the database and maintains a mapping of id to text. This is made its own widget
  12021. as it is useful without being turned into a delegate. The second class provides
  12022. this widget as a delegate and handles communications between it and the model.
  12023. @<Class declarations@>=
  12024. class SqlComboBox : public QComboBox@/
  12025. {@t\1@>@/
  12026. Q_OBJECT@;
  12027. int dataColumn;
  12028. int displayColumn;
  12029. bool dataColumnShown;
  12030. QString specialNullText;
  12031. QVariant specialNullData;
  12032. public:@/
  12033. SqlComboBox();
  12034. ~SqlComboBox();
  12035. SqlComboBox* clone(QWidget *parent);@/
  12036. @t\4@>public slots@t\kern-3pt@>:@/
  12037. void addNullOption();
  12038. void addSqlOptions(QString query);
  12039. void setDataColumn(int column);
  12040. void setDisplayColumn(int column);
  12041. void showData(bool show);
  12042. void setNullText(QString nullText);
  12043. void setNullData(QVariant nullData);@t\2@>@/
  12044. }@t\kern-3pt@>;
  12045. @ In order to make this class work a little more nicely as an item delegate,
  12046. the |clone()| method has been provided to create a new object with the same
  12047. options as a prototype.
  12048. @<SqlComboBox Implementation@>=
  12049. SqlComboBox* SqlComboBox::clone(QWidget *parent)
  12050. {
  12051. SqlComboBox *widget = new SqlComboBox();
  12052. widget->setParent(parent);
  12053. for(int i = 0; i < count(); i++)
  12054. {
  12055. widget->addItem(itemText(i), itemData(i));
  12056. }
  12057. return widget;
  12058. }
  12059. @ When using this class, we must first decide if the data column is shown. If
  12060. this is desired, the entries displayed will contain both the value from the
  12061. display column followed by the value from the data column. This can be useful in
  12062. cases where the same text is used for two different items.
  12063. @<SqlComboBox Implementation@>=
  12064. void SqlComboBox::showData(bool show)
  12065. {
  12066. dataColumnShown = show;
  12067. }
  12068. @ Next, there is a need to know if the NULL value may legally be selected. Where
  12069. this is the case, we generally want this to be inserted first. As the
  12070. |QComboBox| supports storing both display and user data, much of the code is a
  12071. thin wrapper around calls to the base class. The text and data for the NULL
  12072. value can be set arbitrarily, which can be useful in certain cases. Note that
  12073. any customization of the NULL text or data must be set before a call to
  12074. |addNullOption()|.
  12075. @<SqlComboBox Implementation@>=
  12076. void SqlComboBox::addNullOption()
  12077. {
  12078. addItem(specialNullText, specialNullData);
  12079. }
  12080. void SqlComboBox::setNullText(QString nullText)
  12081. {
  12082. specialNullText = nullText;
  12083. }
  12084. void SqlComboBox::setNullData(QVariant nullData)
  12085. {
  12086. specialNullData = nullData;
  12087. }
  12088. @ Typically, the SQL query used to populate this widget will request two columns
  12089. of data. One column is used as the display data, the other as user data. This is
  12090. done to present a human readable string where a database query needs an
  12091. identification number. By default, column |0| is used in both roles. If this
  12092. is not desired, the methods to change that must be called before specifying the
  12093. query.
  12094. @<SqlComboBox Implementation@>=
  12095. void SqlComboBox::setDataColumn(int column)
  12096. {
  12097. dataColumn = column;
  12098. }
  12099. void SqlComboBox::setDisplayColumn(int column)
  12100. {
  12101. displayColumn = column;
  12102. }
  12103. @ Once the widget is properly configured, we can run the SQL query and populate
  12104. the combo box with the results.
  12105. @<SqlComboBox Implementation@>=
  12106. void SqlComboBox::addSqlOptions(QString query)
  12107. {
  12108. SqlQueryConnection h;
  12109. QSqlQuery *dbquery = h.operator->();
  12110. if(!dbquery->exec(query))
  12111. {
  12112. QSqlError error = dbquery->lastError();
  12113. qDebug() << error.databaseText();
  12114. qDebug() << error.driverText();
  12115. qDebug() << error.text();
  12116. qDebug() << dbquery->lastQuery();
  12117. /* Throw an error here, please. */
  12118. }
  12119. while(dbquery->next())
  12120. {
  12121. QString displayValue(dbquery->value(displayColumn).toString());
  12122. QString dataValue(dbquery->value(dataColumn).toString());
  12123. if(dataColumnShown)
  12124. {
  12125. displayValue.append(QString(" (%1)").arg(dataValue));
  12126. }
  12127. addItem(displayValue, dataValue);
  12128. }
  12129. }
  12130. @ The constructor initializes some private member data. A size policy is also
  12131. set on the pop up. This allows the pop up to appear wider than the combo box to
  12132. allow more data to appear. On Linux this appears to also change the text elide
  12133. mode to something that is conveniently more appropriate for the use cases in
  12134. Typica. Note that this was not enough of a change to force the pop up to be
  12135. wide enough to contain all of the text for especially long items, but if the
  12136. combo box is wide enough the pop up will match that width.
  12137. The destructor is trivial.
  12138. @<SqlComboBox Implementation@>=
  12139. SqlComboBox::SqlComboBox() :
  12140. dataColumn(0), displayColumn(0), dataColumnShown(false),
  12141. specialNullText(tr("Unknown")), specialNullData(QVariant::String)
  12142. {
  12143. view()->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
  12144. }
  12145. SqlComboBox::~SqlComboBox()
  12146. {
  12147. /* Nothing needs to be done here. */
  12148. }
  12149. @ To use this class as an editor delegate in a model we wrap the class in a
  12150. |QItemDelegate|.
  12151. @<Class declarations@>=
  12152. class SqlComboBoxDelegate : public QItemDelegate@/
  12153. {
  12154. Q_OBJECT@;
  12155. SqlComboBox *delegate;
  12156. public:@/
  12157. SqlComboBoxDelegate(QObject *parent = NULL);
  12158. QWidget *createEditor(QWidget *parent,
  12159. const QStyleOptionViewItem &option,@|
  12160. const QModelIndex &index) const;
  12161. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  12162. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  12163. const QModelIndex &index) const;
  12164. void setWidget(SqlComboBox *widget);
  12165. virtual QSize sizeHint() const;
  12166. void updateEditorGeometry(QWidget *editor,
  12167. const QStyleOptionViewItem &option,@|
  12168. const QModelIndex &index) const;
  12169. };
  12170. @ Rather than set the values for the combo box through the delegate class, we
  12171. create the editor and pass it in to the delegate.
  12172. @<SqlComboBoxDelegate Implementation@>=
  12173. void SqlComboBoxDelegate::setWidget(SqlComboBox *widget)
  12174. {
  12175. delegate = widget;
  12176. }
  12177. @ When a view requests this delegate, we simply return the widget that was
  12178. previously passed in.
  12179. @<SqlComboBoxDelegate Implementation@>=
  12180. QWidget* SqlComboBoxDelegate::createEditor(QWidget *parent,@|
  12181. const QStyleOptionViewItem &,
  12182. const QModelIndex &) const
  12183. {
  12184. return delegate->clone(parent);
  12185. }
  12186. @ To set the appropriate editor data, we check the value in the model and
  12187. attempt to set the value to match that.
  12188. @<SqlComboBoxDelegate Implementation@>=
  12189. void SqlComboBoxDelegate::setEditorData(QWidget *editor,
  12190. const QModelIndex &index) const
  12191. {
  12192. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  12193. self->setCurrentIndex(self->findData(
  12194. index.model()->data(index,
  12195. Qt::UserRole).toString()));
  12196. }
  12197. @ When setting the model data, we need to specify both the display role and the
  12198. user data role.
  12199. @<SqlComboBoxDelegate Implementation@>=
  12200. void SqlComboBoxDelegate::setModelData(QWidget *editor,@|
  12201. QAbstractItemModel *model,
  12202. const QModelIndex &index) const
  12203. {
  12204. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  12205. model->setData(index, self->itemData(self->currentIndex(), Qt::UserRole),
  12206. Qt::UserRole);
  12207. model->setData(index, self->currentText(), Qt::DisplayRole);
  12208. }
  12209. @ This is needed to play nicely with the model view architecture.
  12210. @<SqlComboBoxDelegate Implementation@>=
  12211. void SqlComboBoxDelegate::updateEditorGeometry(QWidget *editor,
  12212. const QStyleOptionViewItem &option,
  12213. const QModelIndex &) const
  12214. {
  12215. editor->setGeometry(option.rect);
  12216. }
  12217. @ When this delegate is used in a table view, we want to be able to provide a
  12218. size hint that can be used to resize the column in order to fit the delegate.
  12219. @<SqlComboBoxDelegate Implementation@>=
  12220. QSize SqlComboBoxDelegate::sizeHint() const
  12221. {
  12222. return delegate->sizeHint();
  12223. }
  12224. @ Finally, we need a constructor.
  12225. @<SqlComboBoxDelegate Implementation@>=
  12226. SqlComboBoxDelegate::SqlComboBoxDelegate(QObject *parent)
  12227. : QItemDelegate(parent)@/
  12228. {
  12229. /* Nothing needs to be done here. */
  12230. }
  12231. @** The main program.
  12232. The |main()| function is where program execution starts. Most of the work
  12233. required here is taken care of for us by the |Application| object.
  12234. The odd handling of argc is required to prevent segmentation faults in the Linux
  12235. build.
  12236. @<The main program@>=
  12237. int main(int argc, char **argv)@/
  12238. {@/
  12239. int *c = &argc;
  12240. Application app(*c, argv);
  12241. QSettings settings;
  12242. @<Set up logging@>@;
  12243. @<Set up icons@>@;
  12244. @<Set up fonts@>@;
  12245. @<Register device configuration widgets@>@;
  12246. @<Prepare the database connection@>@;
  12247. @<Load the application configuration@>@;
  12248. @<Set up the scripting engine@>@;
  12249. app.engine = engine;
  12250. @<Find and evaluate starting script@>@;
  12251. int retval = app.exec();
  12252. delete engine;
  12253. return retval;@/
  12254. }
  12255. @ \pn{} 1.6.3 introduces optional logging of diagnostic messages to a file. By
  12256. default this feature is not enabled. A sensible future refinement to this would
  12257. allow specification of where this file should be created.
  12258. @<Set up logging@>=
  12259. if(settings.value("settings/advanced/logging", false).toBool())
  12260. {
  12261. qInstallMsgHandler(messageFileOutput);
  12262. }
  12263. @ This requires that we have our messageFileOutput function.
  12264. @<Logging function prototype@>=
  12265. void messageFileOutput(QtMsgType type, const char *msg);
  12266. @ The current implementation is straightforward.
  12267. @<Logging function implementation@>=
  12268. void messageFileOutput(QtMsgType, const char *msg)
  12269. {
  12270. QFile output("Typica-"+QDate::currentDate().toString("yyyy-MM-dd")+".log");
  12271. output.open(QIODevice::WriteOnly | QIODevice::Append);
  12272. QTextStream outstream(&output);
  12273. outstream << msg << "\r\n";
  12274. }
  12275. @ \pn{} 1.4 introduces the ability to use icons in certain interface elements.
  12276. Some commonly desired public domain graphics are provided by the Tango Desktop
  12277. Project. We also set an application level default window icon.
  12278. @<Set up icons@>=
  12279. QStringList themeSearchPath = QIcon::themeSearchPaths();
  12280. themeSearchPath.append(":/resources/icons/tango");
  12281. QIcon::setThemeSearchPaths(themeSearchPath);
  12282. QIcon::setThemeName(":/resources/icons/tango");
  12283. app.setWindowIcon(QIcon(":/resources/icons/appicons/logo.svg"));
  12284. @ Similarly some elements make use of a special font which is loaded from
  12285. resource data.
  12286. There has been a report of a bug which I have not been able to reproduce and
  12287. which the original reporter has not yet gotten back to me with the results of
  12288. a test, so I have opted for an alternate approach which does not preclude the
  12289. use of the earlier plan but which may solve the matter. This brings in the
  12290. TeX Gyre Pagella font and sets this as the default standard font for all web
  12291. views.
  12292. @s QFontDatabase int
  12293. @s QWebSettings int
  12294. @<Set up fonts@>=
  12295. QFile entypo(":/resources/fonts/entypo.ttf");
  12296. entypo.open(QIODevice::ReadOnly);
  12297. QFontDatabase::addApplicationFontFromData(entypo.readAll());
  12298. entypo.close();
  12299. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-regular.otf");
  12300. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-bold.otf");
  12301. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-bolditalic.otf");
  12302. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-italic.otf");
  12303. QWebSettings::globalSettings()->setFontFamily(QWebSettings::StandardFont, "Tex Gyre Pagella");
  12304. @ Some widgets provided by \pn{} require access to a database in order to work.
  12305. To simplify using these widgets, the application will request information
  12306. needed to connect to a database. The use of two distinct |if| blocks rather than
  12307. an |if|$\dots$|else| construction is used because the data from settings can be
  12308. changed if an attempt to connect to the database fails.
  12309. @<Prepare the database connection@>=
  12310. if(settings.value("database/exists", "false").toString() == "true")
  12311. {
  12312. @<Try connecting to the database@>@;
  12313. }
  12314. if(settings.value("database/exists", "false").toString() == "false")
  12315. {
  12316. @<Prompt for database connection information@>@;
  12317. }
  12318. @ In order to connect to the database, we need five pieces of information: the
  12319. name of a database driver (PostgreSQL is recommended for now), the host name of
  12320. the computer running the database, the name of the database, the name of the
  12321. user connecting to the database, and that user'@q'@>s password. This information will
  12322. be stored in the user settings for the application so that the database
  12323. connection can be established without prompting the user next time. A class is
  12324. provided to gather this information.
  12325. @<Class declarations@>=
  12326. class SqlConnectionSetup : public QDialog@/
  12327. {@t\1@>@/
  12328. Q_OBJECT@;
  12329. public:@/
  12330. SqlConnectionSetup();
  12331. ~SqlConnectionSetup();@/
  12332. @t\4@>public slots@t\kern-3pt@>:@/
  12333. void testConnection();
  12334. private:@/
  12335. QFormLayout *formLayout;
  12336. QComboBox *driver;
  12337. QLineEdit *hostname;
  12338. QLineEdit *portnumber;
  12339. QLineEdit *dbname;
  12340. QLineEdit *user;
  12341. QLineEdit *password;
  12342. QVBoxLayout *layout;
  12343. QHBoxLayout *buttons;
  12344. QPushButton *cancelButton;
  12345. QPushButton *connectButton;@t\2@>@/
  12346. }@t\kern-3pt@>;
  12347. @ The constructor sets up this widget. The destructor does nothing.
  12348. @<SqlConnectionSetup implementation@>=
  12349. SqlConnectionSetup::SqlConnectionSetup() :
  12350. formLayout(new QFormLayout), driver(new QComboBox), hostname(new QLineEdit),
  12351. portnumber(new QLineEdit),
  12352. dbname(new QLineEdit), user(new QLineEdit), password(new QLineEdit),
  12353. layout(new QVBoxLayout), buttons(new QHBoxLayout),
  12354. cancelButton(new QPushButton(tr("Cancel"))),
  12355. connectButton(new QPushButton(tr("Connect")))@/
  12356. {
  12357. QSettings settings;
  12358. driver->addItem("PostgreSQL", "QPSQL");
  12359. formLayout->addRow(tr("Database driver:"), driver);
  12360. formLayout->addRow(tr("Host name:"), hostname);
  12361. hostname->setText(settings.value("database/hostname").toString());
  12362. formLayout->addRow(tr("Port number:"), portnumber);
  12363. portnumber->setText(settings.value("database/portnumber", "5432").toString());
  12364. formLayout->addRow(tr("Database name:"), dbname);
  12365. dbname->setText(settings.value("database/dbname").toString());
  12366. formLayout->addRow(tr("User name:"), user);
  12367. user->setText(settings.value("database/user").toString());
  12368. password->setEchoMode(QLineEdit::Password);
  12369. formLayout->addRow(tr("Password:"), password);
  12370. password->setText(settings.value("database/password").toString());
  12371. layout->addLayout(formLayout);
  12372. buttons->addStretch(1);
  12373. buttons->addWidget(cancelButton);
  12374. connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(reject()));
  12375. buttons->addWidget(connectButton);
  12376. layout->addLayout(buttons);
  12377. connect(connectButton, SIGNAL(clicked(bool)), this, SLOT(testConnection()));
  12378. connectButton->setDefault(true);
  12379. setLayout(layout);
  12380. setModal(true);
  12381. }
  12382. SqlConnectionSetup::~SqlConnectionSetup()
  12383. {
  12384. /* Nothing needs to be done here. */
  12385. }
  12386. @ The |testConnection()| method checks if the information provided can be used
  12387. to open a new database connection.
  12388. @<SqlConnectionSetup implementation@>=
  12389. void SqlConnectionSetup::testConnection()
  12390. {
  12391. QSqlDatabase database =
  12392. QSqlDatabase::addDatabase(driver->itemData(driver->currentIndex()).
  12393. toString());
  12394. database.setConnectOptions("application_name=Typica");
  12395. database.setHostName(hostname->text());
  12396. database.setPort(portnumber->text().toInt());
  12397. database.setDatabaseName(dbname->text());
  12398. database.setUserName(user->text());
  12399. database.setPassword(password->text());
  12400. if(database.open())
  12401. {
  12402. QSettings settings;
  12403. settings.setValue("database/exists", "true");
  12404. settings.setValue("database/driver",
  12405. driver->itemData(driver->currentIndex()).toString());
  12406. settings.setValue("database/hostname", hostname->text());
  12407. settings.setValue("database/portnumber", portnumber->text());
  12408. settings.setValue("database/dbname", dbname->text());
  12409. settings.setValue("database/user", user->text());
  12410. settings.setValue("database/password", password->text());
  12411. AppInstance->setDatabaseConnected(true);
  12412. accept();
  12413. }
  12414. else
  12415. {
  12416. QMessageBox::information(this, tr("Database connection failed"),
  12417. tr("Failed to connect to database."));
  12418. }
  12419. }
  12420. @ In order to prompt for connection information, we simply create a
  12421. |SqlConnectionSetup| object and call |exec()|. When control returns, the
  12422. settings will either contain appropriate connection information or we have to
  12423. give up on getting that information from the user for now.
  12424. @<Prompt for database connection information@>=
  12425. SqlConnectionSetup dialog;
  12426. dialog.exec();
  12427. @ If we have connected to a database in the previous running of the application,
  12428. we try to connect to the same database automatically rather than prompt the
  12429. user. If the connection attempt fails, we can fall back on asking the user for
  12430. help.
  12431. @<Try connecting to the database@>=
  12432. QSqlDatabase database =
  12433. QSqlDatabase::addDatabase(settings.value("database/driver").toString());
  12434. database.setConnectOptions("application_name=Typica");
  12435. database.setHostName(settings.value("database/hostname").toString());
  12436. database.setPort(settings.value("database/portnumber", 5432).toInt());
  12437. database.setDatabaseName(settings.value("database/dbname").toString());
  12438. database.setUserName(settings.value("database/user").toString());
  12439. database.setPassword(settings.value("database/password").toString());
  12440. if(!database.open())
  12441. {
  12442. settings.setValue("database/exists", "false");
  12443. }
  12444. else
  12445. {
  12446. AppInstance->setDatabaseConnected(true);
  12447. }
  12448. @** Viewing a record of batches.
  12449. \noindent It is frequently useful to present a table view with the results of a
  12450. SQL query and have a way of interacting with that view to obtain more details
  12451. related to a given record in that table. For this purpose, \pn{} provides a
  12452. widget based on |QTableView| which presents information from a
  12453. |QSqlQueryModel|. The table emits signals when an entry in the table is double
  12454. clicked. One of these contains the data from the first column of that row and
  12455. is suitable for use when a primary key is presented in that column and this is
  12456. sufficient for the desired drill down. The other signal provides the row number
  12457. which can be used along with a reference to the table to obtain the data in any
  12458. column.
  12459. This class also automatically persists column widths when these are changed.
  12460. @<Class declarations@>=
  12461. class SqlQueryView : public QTableView@/
  12462. {@/
  12463. @[Q_OBJECT@]@;
  12464. public:@/
  12465. SqlQueryView(QWidget *parent = NULL);
  12466. void setQuery(const QString &query);
  12467. bool setHeaderData(int section, Qt::Orientation@, orientation,
  12468. const QVariant &value, int role);
  12469. @[Q_INVOKABLE@,@, QVariant@]@, data(int row, int column,
  12470. int role = Qt::DisplayRole);@t\2\2@>@/
  12471. signals:@/
  12472. void openEntry(QString key);
  12473. void openEntryRow(int row);
  12474. void selectEntry(QString key);
  12475. void selectEntryRow(int row);@/
  12476. protected:@/
  12477. virtual void showEvent(QShowEvent *event);@/
  12478. @[private slots@]:@/
  12479. void openRow(const QModelIndex &index);
  12480. void persistColumnResize(int column, int oldsize, int newsize);
  12481. void selectRow(const QModelIndex &index);@/
  12482. };
  12483. @ The constructor sets up the communication between the model and the view and
  12484. also provides the connection needed to notice when columns change size to
  12485. persist that preference.
  12486. @<SqlQueryView implementation@>=
  12487. SqlQueryView::SqlQueryView(QWidget *parent) : QTableView(parent)
  12488. {
  12489. setModel(new QSqlQueryModel);
  12490. connect(this, SIGNAL(doubleClicked(QModelIndex)),
  12491. this, SLOT(openRow(QModelIndex)));
  12492. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  12493. this, SLOT(persistColumnResize(int, int, int)));
  12494. connect(this, SIGNAL(activated(QModelIndex)),
  12495. this, SLOT(selectRow(QModelIndex)));
  12496. }
  12497. @ Column width persistance requires two methods. First we have a slot
  12498. method which is called when a column width is changed. This is saved with
  12499. |QSettings| under a key utilizing the name of the window, the name of the
  12500. table, and the column number.
  12501. @<SqlQueryView implementation@>=
  12502. void SqlQueryView::persistColumnResize(int column, int, int newsize)
  12503. {
  12504. @<Save updated column size@>@;
  12505. }
  12506. @ The body of this function has been split out so that it can be shared with
  12507. other table views without the need to introduce a new common base class.
  12508. @<Save updated column size@>=
  12509. QSettings settings;
  12510. @<Obtain top level widget@>@;
  12511. settings.setValue(QString("columnWidths/%1/%2/%3").
  12512. arg(topLevelWidget->objectName()).
  12513. arg(objectName()).arg(column),
  12514. QVariant(newsize));
  12515. @ To determine which window a given table is in, we just follow
  12516. |parentWidget()| until there isn'@q'@>t one. It is possible that the table view
  12517. will also be the window, however this is not advised as it is easier for the
  12518. settings key to be non-unique in such a case.
  12519. @<Obtain top level widget@>=
  12520. QWidget *topLevelWidget = this;
  12521. while(topLevelWidget->parentWidget())
  12522. {
  12523. topLevelWidget = topLevelWidget->parentWidget();
  12524. }
  12525. @ We restore column widths in response to a show event. One of these should be
  12526. received just before the widget is shown so the widget should appear correctly.
  12527. @<SqlQueryView implementation@>=
  12528. void SqlQueryView::showEvent(QShowEvent *event)
  12529. {
  12530. @<Restore table column widths@>@;
  12531. event->accept();
  12532. }
  12533. @ Similarly, most of the body of this method has also been split into a chunk
  12534. so that it might be shared with other classes.
  12535. @<Restore table column widths@>=
  12536. QSettings settings;
  12537. @<Obtain top level widget@>
  12538. QString baseKey =
  12539. QString("columnWidths/%1/%2").arg(topLevelWidget->objectName()).
  12540. arg(objectName());
  12541. for(int i = 0; i < model()->columnCount(); i++)
  12542. {
  12543. QString key = QString("%1/%2").arg(baseKey).arg(i);
  12544. if(settings.contains(key))
  12545. {
  12546. setColumnWidth(i, settings.value(key).toInt());
  12547. }
  12548. }
  12549. @ A slot is required for obtaining the information to send out in our signals.
  12550. @<SqlQueryView implementation@>=
  12551. void SqlQueryView::openRow(const QModelIndex &index)
  12552. {
  12553. emit openEntry(((QSqlQueryModel *)model())->record(index.row()).value(0).toString());
  12554. emit openEntryRow(index.row());
  12555. }
  12556. void SqlQueryView::selectRow(const QModelIndex &index)
  12557. {
  12558. emit selectEntry(((QSqlQueryModel *)model())->record(index.row()).value(0).toString());
  12559. emit selectEntryRow(index.row());
  12560. }
  12561. @ The other functions are wrappers around model methods.
  12562. @<SqlQueryView implementation@>=
  12563. void SqlQueryView::setQuery(const QString &query)
  12564. {
  12565. QSqlDatabase database = AppInstance->database();
  12566. database.open();
  12567. QSqlQuery q(query, database);
  12568. ((QSqlQueryModel*)model())->setQuery(q);
  12569. database.close();
  12570. }
  12571. bool SqlQueryView::setHeaderData(int section, Qt::Orientation@, orientation,
  12572. const QVariant &value, int role)
  12573. {
  12574. return model()->setHeaderData(section, orientation, value, role);
  12575. }
  12576. @ A method is also provided to allow scripts to access the data.
  12577. @<SqlQueryView implementation@>=
  12578. QVariant SqlQueryView::data(int row, int column, int role)
  12579. {
  12580. return model()->data(model()->index(row, column), role);
  12581. }
  12582. @ To use this class, it is useful to expose it to the host environment.
  12583. @<Function prototypes for scripting@>=
  12584. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine);
  12585. QScriptValue constructSqlQueryView(QScriptContext *context,
  12586. QScriptEngine *engine);
  12587. QScriptValue SqlQueryView_setQuery(QScriptContext *context,
  12588. QScriptEngine *engine);
  12589. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  12590. QScriptEngine *engine);
  12591. QScriptValue SqlQueryView_rows(QScriptContext *context,
  12592. QScriptEngine *engine);
  12593. @ The script constructor is passed to the host environment.
  12594. @<Set up the scripting engine@>=
  12595. constructor = engine->newFunction(constructSqlQueryView);
  12596. value = engine->newQMetaObject(&SqlQueryView::staticMetaObject, constructor);
  12597. engine->globalObject().setProperty("SqlQueryView", value);
  12598. @ Next we construct the view, add properties to access its methods from the host
  12599. environment, and pass that back.
  12600. @<Functions for scripting@>=
  12601. QScriptValue constructSqlQueryView(QScriptContext *, QScriptEngine *engine)
  12602. {
  12603. QScriptValue object = engine->newQObject(new SqlQueryView);
  12604. setSqlQueryViewProperties(object, engine);
  12605. return object;
  12606. }
  12607. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine)
  12608. {
  12609. setQTableViewProperties(value, engine);
  12610. value.setProperty("setHeaderData",
  12611. engine->newFunction(SqlQueryView_setHeaderData));
  12612. value.setProperty("setQuery", engine->newFunction(SqlQueryView_setQuery));
  12613. value.setProperty("rows", engine->newFunction(SqlQueryView_rows));
  12614. }
  12615. @ The properties added are simplified wrappers around the class methods.
  12616. @<Functions for scripting@>=
  12617. QScriptValue SqlQueryView_setQuery(QScriptContext *context, QScriptEngine *)
  12618. {
  12619. SqlQueryView *self = getself<SqlQueryView *>(context);
  12620. QString query = argument<QString>(0, context);
  12621. self->setQuery(query);
  12622. self->reset();
  12623. return QScriptValue();
  12624. }
  12625. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  12626. QScriptEngine *)
  12627. {
  12628. SqlQueryView *self = getself<SqlQueryView *>(context);
  12629. int section = argument<int>(0, context);
  12630. QString data = argument<QString>(1, context);
  12631. self->setHeaderData(section, Qt::Horizontal, data, Qt::DisplayRole);
  12632. return QScriptValue();
  12633. }
  12634. QScriptValue SqlQueryView_rows(QScriptContext *context, QScriptEngine *)
  12635. {
  12636. SqlQueryView *self = getself<SqlQueryView *>(context);
  12637. return QScriptValue(self->model()->rowCount());
  12638. }
  12639. @** Reporting.
  12640. \noindent \pn{} version 1.4 added a new type of menu which is designed to
  12641. handle reports. This makes extensive use of the previously existing reporting
  12642. system at present which makes modifying existing reports to work with the new
  12643. system very simple. Further changes may be introduced in the future that
  12644. substantially depart from this in order to simplify report files.
  12645. Previously to add a new report to a configuration, you needed to create the
  12646. report, add an {\tt <include>} tag in the main configuration file to bring that
  12647. report into the application configuration, then in any window with a Reports
  12648. menu you would need to add the report to that menu in its configuration file
  12649. and write a small bit of JavaScript to obtain a reference to that new menu
  12650. item and create the report when that menu item is triggered. This is highly
  12651. repetetive, error prone, and with the new approach it is not needed at all.
  12652. To add a new report to a configuration using the new approach one need only
  12653. save the new report file in the appropriate directory and \pn{} will detect
  12654. this, add it to any Reports menus that may exist, and handle all of the details
  12655. of generating these reports on demand.
  12656. The Reports menu is created in a configuration as a {\tt <menu>} element with
  12657. three attributes. The {\tt name} attribute as usual is the name of the menu
  12658. item. The {\tt type} attribute will have a value of {\tt "reports"} and the
  12659. {\tt src} attribute will indicate the directory to search for reports to
  12660. populate that menu. This allows for multiple Reports menus with different
  12661. reports in each menu if desired.
  12662. Reports are added to the menu in the order of the file names in the reports
  12663. directory.
  12664. \danger While it should not be an issue with the limited number of reports
  12665. presently distributed with Typica, the approach taken to implementing this menu
  12666. type is highly inefficient. There are many optimizations available if this
  12667. becomes problematic.\endanger
  12668. When a report menu is generated, the directory used for this is added as a
  12669. search path for the |"reports"| prefix. This is used by the |createReport()|
  12670. script method and is intended to allow access to reports from outside of the
  12671. Report menu.
  12672. @<Populate reports menu@>=
  12673. QSettings settings;
  12674. QString reportDirectory = QString("%1/%2").arg(settings.value("config").
  12675. toString()).
  12676. arg(element.attribute("src"));
  12677. QDir::addSearchPath("reports", reportDirectory);
  12678. QDir directory(reportDirectory);
  12679. directory.setFilter(QDir::Files);
  12680. directory.setSorting(QDir::Name);
  12681. QStringList nameFilter;
  12682. nameFilter << "*.xml";
  12683. directory.setNameFilters(nameFilter);
  12684. QFileInfoList reportFiles = directory.entryInfoList();
  12685. for(int i = 0; i < reportFiles.size(); i++)
  12686. {
  12687. QFileInfo reportFile = reportFiles.at(i);
  12688. @<Add report to reports menu@>@;
  12689. }
  12690. @ The menu items themselves are a subclass of |QAction| which holds all of the
  12691. information needed to respond to its activation by generating the appropriate
  12692. report.
  12693. @<Class declarations@>=
  12694. class ReportAction : public QAction@/
  12695. {@/
  12696. @[Q_OBJECT@]@;
  12697. public:@/
  12698. ReportAction(const QString &fileName, const QString &reportName,
  12699. QObject *parent = NULL);@/
  12700. @[private slots@]:@/
  12701. void createReport();@/
  12702. private:@/
  12703. QString reportFile;@/
  12704. };
  12705. @ The constructor receives the name of the report file which is used to
  12706. generate the report when needed and the name of the report which is used as the
  12707. name presented in the menu.
  12708. @<ReportAction implementation@>=
  12709. ReportAction::ReportAction(const QString &fileName, const QString &reportName,
  12710. QObject *parent) :
  12711. QAction(reportName, parent), reportFile(fileName)
  12712. {
  12713. connect(this, SIGNAL(triggered()), this, SLOT(createReport()));
  12714. }
  12715. @ The slot method is responsible for creating the new report. This is very
  12716. similar to the old approach and reuses much of the same code. Of particular
  12717. note is the |targetID| variable. This is set to facilitate window geometry
  12718. management, though this should probably be set from the {\tt id} attribute
  12719. of the {\tt <window>} element in the file to preserve window geometry
  12720. settings if the configuration is moved to another location in the file
  12721. system.
  12722. @<ReportAction implementation@>=
  12723. void ReportAction::createReport()
  12724. {
  12725. QFile file(reportFile);
  12726. QDomDocument document;
  12727. if(file.open(QIODevice::ReadOnly))
  12728. {
  12729. document.setContent(&file, true);
  12730. QDomElement element = document.documentElement();
  12731. QScriptEngine *engine = AppInstance->engine;
  12732. QScriptContext *context = engine->pushContext();
  12733. QScriptValue object;
  12734. QString targetID = reportFile;
  12735. @<Display the window@>@;
  12736. file.close();
  12737. engine->popContext();
  12738. }
  12739. }
  12740. @ With the |ReportAction| available, we are now ready to add reports to the
  12741. Reports menu. To do this we check each file in the given directory to determine
  12742. if it is a report file, obtain the report title and location within the menu
  12743. hierarchy from the file data, create the actions, and add them to the menu.
  12744. @<Add report to reports menu@>=
  12745. QString path = reportFile.absoluteFilePath();
  12746. QFile file(path);
  12747. if(file.open(QIODevice::ReadOnly))
  12748. {
  12749. QDomDocument document;
  12750. document.setContent(&file, true);
  12751. QDomElement root = document.documentElement();
  12752. QString translationContext = root.attribute("id");
  12753. QDomNode titleNode = root.elementsByTagName("reporttitle").at(0);
  12754. if(!titleNode.isNull())
  12755. {
  12756. QDomElement titleElement = titleNode.toElement();
  12757. QString title = QCoreApplication::translate("configuration",
  12758. titleElement.text().toUtf8().data());
  12759. if(!title.isEmpty())
  12760. {
  12761. QStringList hierarchy = title.split(":->");
  12762. QMenu *insertionPoint = menu;
  12763. @<Traverse report menu hierarchy@>
  12764. ReportAction *action = new ReportAction(path, hierarchy.last());
  12765. insertionPoint->addAction(action);
  12766. }
  12767. }
  12768. }
  12769. @ \pn{} allows the Reports menu to contain arbitrarily deep menu hierarchies.
  12770. It is advised to keep these hierarchies shallow.
  12771. @<Traverse report menu hierarchy@>=
  12772. for(int j = 0; j < hierarchy.size() - 1; j++)
  12773. {
  12774. QObjectList menuList = insertionPoint->children();
  12775. bool menuFound = @[false@];
  12776. for(int k = 0; k < menuList.size(); k++)
  12777. {
  12778. QMenu *currentItem = qobject_cast<QMenu*>(menuList.at(k));
  12779. if(currentItem)
  12780. {
  12781. if(currentItem->title() == hierarchy.at(j))
  12782. {
  12783. menuFound = @[true@];
  12784. insertionPoint = currentItem;
  12785. break;
  12786. }
  12787. }
  12788. }
  12789. if(!menuFound)
  12790. {
  12791. insertionPoint = insertionPoint->addMenu(hierarchy.at(j));
  12792. }
  12793. }
  12794. @ \noindent The reporting functionality in \pn{} is based on the Scribe framework
  12795. in Qt. This brings several benefits, including making it easy to print reports
  12796. or save reports as plain text or HTML.
  12797. Reports are specified in the \pn{}'@q'@>s configuration document and can include both
  12798. static elements and elements that are populated by external data such as the
  12799. result of a SQL query.
  12800. @<Function prototypes for scripting@>=
  12801. void addReportToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  12802. QStack<QLayout *> *layoutStack);
  12803. @ When adding a report to a layout, we must not only add the widget to the
  12804. layout, but also construct the document.
  12805. @<Functions for scripting@>=
  12806. void addReportToLayout(QDomElement element, QStack<QWidget *> *,@|
  12807. QStack<QLayout *> *layoutStack)
  12808. {
  12809. QTextEdit *widget = new QTextEdit;
  12810. if(element.hasAttribute("id"))
  12811. {
  12812. widget->setObjectName(element.attribute("id"));
  12813. }
  12814. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  12815. layout->addWidget(widget);
  12816. QTextDocument *document = new QTextDocument;
  12817. QFont defaultFont;
  12818. defaultFont.setPointSize(11);
  12819. document->setDefaultFont(defaultFont);
  12820. QTextCursor cursor(document);
  12821. @<Construct report document@>@;
  12822. widget->setDocument(document);
  12823. }
  12824. @ Several child elements are allowed under the {\tt <report>} element. These
  12825. should be processed in order to produce the final report document.
  12826. @<Construct report document@>=
  12827. QDomNodeList children = element.childNodes();
  12828. for(int i = 0; i < children.count(); i++)
  12829. {
  12830. QDomNode current;
  12831. QDomElement currentElement;
  12832. current = children.at(i);
  12833. if(current.isElement())
  12834. {
  12835. currentElement = current.toElement();
  12836. @<Process report document elements@>@;
  12837. }
  12838. }
  12839. @ If any custom styling for HTML content is required, a {\tt <style>} element
  12840. should be placed in the report description before any such content.
  12841. @<Process report document elements@>=
  12842. if(currentElement.tagName() == "style")
  12843. {
  12844. document->setDefaultStyleSheet(currentElement.text());
  12845. }
  12846. @ One common need is the ability to insert static text, such as the title of the
  12847. report. In order to simplify formatting, the text can be interpreted as HTML.
  12848. Note that to avoid having HTML tags eaten by the parser, the text of this
  12849. element should be a CDATA section.
  12850. @<Process report document elements@>=
  12851. if(currentElement.tagName() == "html")
  12852. {
  12853. cursor.insertHtml(currentElement.text());
  12854. }
  12855. @ If no special formatting is needed, a plain text element can be used. This
  12856. might be extended in the future to allow attributes for specifying the character
  12857. formatting to be used with the text.
  12858. @<Process report document elements@>=
  12859. if(currentElement.tagName() == "text")
  12860. {
  12861. cursor.insertText(currentElement.text());
  12862. }
  12863. @ One of the more interesting elements of a report is the {\tt <table>} element.
  12864. This is an element which can change its contents in response to changes in user
  12865. controls.
  12866. @<Process report document elements@>=
  12867. if(currentElement.tagName() == "table")
  12868. {
  12869. QTextFrame *frame = cursor.insertFrame(QTextFrameFormat());
  12870. ReportTable *table = new ReportTable(frame, currentElement);
  12871. table->setParent(widget);
  12872. if(currentElement.hasAttribute("id"))
  12873. {
  12874. table->setObjectName(currentElement.attribute("id"));
  12875. }
  12876. }
  12877. @ The |ReportTable| class is responsible for parsing {\tt <table>} child
  12878. elements and inserting the table into the document at the correct location.
  12879. @<Class declarations@>=
  12880. class ReportTable : public QObject@/
  12881. {@t\1@>@/
  12882. Q_OBJECT@;
  12883. QTextFrame *area;
  12884. QDomElement configuration;
  12885. QMap<QString, QVariant> bindings;
  12886. public:@/
  12887. ReportTable(QTextFrame *frame, QDomElement description);
  12888. ~ReportTable();
  12889. @[Q_INVOKABLE@,@, void@]@, bind(QString placeholder, QVariant value);@t\2\2@>@/
  12890. @t\4@>public slots@t\kern-3pt@>:@/
  12891. void refresh();@t\2@>@/
  12892. }@t\kern-3pt@>;
  12893. @ The |ReportTable| class takes a |QTextFrame| and |QDomElement| pointer in
  12894. its constructor. The former is used to establish the bounds of the table within
  12895. a document and the latter is used for generating the table contents.
  12896. @<ReportTable implementation@>=
  12897. ReportTable::ReportTable(QTextFrame *frame, QDomElement description) :
  12898. area(frame), configuration(description)
  12899. {
  12900. refresh();
  12901. }
  12902. ReportTable::~ReportTable()
  12903. {
  12904. }
  12905. @ In order to change the table contents based on user controls, the |bind()|
  12906. method allows a placeholder to be replaced with a value when evaluating a SQL
  12907. query.
  12908. @<ReportTable implementation@>=
  12909. void ReportTable::bind(QString placeholder, QVariant value)
  12910. {
  12911. bindings.insert(placeholder, value);
  12912. }
  12913. @ All of the interesting work is done in the |refresh()| slot. This method
  12914. deletes the current content of the frame and creates a table based on the
  12915. description of the table in the configuration document.
  12916. @<ReportTable implementation@>=
  12917. void ReportTable::refresh()
  12918. {
  12919. @<Delete current report table content@>@;
  12920. int rows = 1;
  12921. int columns = 1;
  12922. int currentRow = 0;
  12923. QTextTable *table = cursor.insertTable(rows, columns);
  12924. @<Set table formatting@>@;
  12925. @<Reconstruct report table content@>@;
  12926. if(rows > 1)
  12927. {
  12928. table->removeRows(0, 1);
  12929. }
  12930. }
  12931. @ Deleting the current content of the table involves using a cursor to select
  12932. everything in the frame and then removing that selection. There are more optimal
  12933. ways to do this but if there are performance problems with this, you may want to
  12934. reconsider what you are trying to do.
  12935. @<Delete current report table content@>=
  12936. QTextCursor cursor = area->firstCursorPosition();
  12937. while(cursor < area->lastCursorPosition())
  12938. {
  12939. cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
  12940. }
  12941. cursor.removeSelectedText();
  12942. @ When creating a new table, we may need to alter the formatting of that table.
  12943. To do this, we get the current format, modify that based on attributes of the
  12944. {\tt <table>} element, and apply the modified copy to the newly constructed
  12945. table.
  12946. @<Set table formatting@>=
  12947. QTextTableFormat format = table->format();
  12948. format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
  12949. if(configuration.hasAttribute("align"))
  12950. {
  12951. if(configuration.attribute("align") == "center")
  12952. {
  12953. format.setAlignment(Qt::AlignHCenter);
  12954. }
  12955. }
  12956. table->setFormat(format);
  12957. @ To reconstruct the table, we need to parse the description of the table.
  12958. @<Reconstruct report table content@>=
  12959. QDomNodeList children = configuration.childNodes();
  12960. for(int i = 0; i < children.count(); i++)
  12961. {
  12962. QDomNode current;
  12963. QDomElement currentElement;
  12964. current = children.at(i);
  12965. if(current.isElement())
  12966. {
  12967. currentElement = current.toElement();
  12968. if(currentElement.tagName() == "query")
  12969. {
  12970. @<Add SQL query results to report table@>@;
  12971. }
  12972. else if(currentElement.tagName() == "row")
  12973. {
  12974. @<Add new row to report table@>@;
  12975. }
  12976. }
  12977. }
  12978. @ The text of a {\tt <query>} element will be the query desired in the table.
  12979. This might include placeholders that must be bound to values before the query is
  12980. executed. If query execution results in an error (as it will if it contains
  12981. placeholders that have not yet had values bound to them), there will be no
  12982. change to the table and the next child element, if any, will be processed.
  12983. @<Add SQL query results to report table@>=
  12984. SqlQueryConnection h;
  12985. QSqlQuery *query = h.operator->();
  12986. query->prepare(currentElement.text());
  12987. foreach(QString key, bindings.uniqueKeys())
  12988. {
  12989. if(currentElement.text().contains(key))
  12990. {
  12991. query->bindValue(key, bindings.value(key));
  12992. }
  12993. }
  12994. query->exec();
  12995. if(!query->next())
  12996. {
  12997. continue;
  12998. }
  12999. if(query->record().count() > columns)
  13000. {
  13001. table->appendColumns(query->record().count() - columns);
  13002. }
  13003. do
  13004. {
  13005. table->appendRows(1);
  13006. rows++;
  13007. currentRow++;
  13008. for(int j = 0; j < query->record().count(); j++)
  13009. {
  13010. QTextTableCell cell = table->cellAt(currentRow, j);
  13011. cursor = cell.firstCursorPosition();
  13012. cursor.insertText(query->value(j).toString());
  13013. }
  13014. } while(query->next());
  13015. @ It is sometimes desirable to add fixed data such as column headers to a table.
  13016. This is done with the {\tt <row>} element.
  13017. Technically, this isn'@q'@>t needed. The same results can be produced by using a
  13018. {\tt <query>} element to select constant data, but this approach saves a trip to
  13019. the database.
  13020. @<Add new row to report table@>=
  13021. table->appendRows(1);
  13022. currentRow++;
  13023. rows++;
  13024. QDomNodeList rowChildren = currentElement.childNodes();
  13025. int currentColumn = 0;
  13026. for(int j = 0; j < rowChildren.count(); j++)
  13027. {
  13028. QDomNode node;
  13029. QDomElement nodeElement;
  13030. node = rowChildren.at(j);
  13031. if(node.isElement())
  13032. {
  13033. nodeElement = node.toElement();
  13034. if(nodeElement.tagName() == "cell")
  13035. {
  13036. if(currentColumn == columns)
  13037. {
  13038. table->appendColumns(1);
  13039. columns++;
  13040. }
  13041. QTextTableCell cell = table->cellAt(currentRow, currentColumn);
  13042. cursor = cell.firstCursorPosition();
  13043. cursor.insertText(nodeElement.text());
  13044. currentColumn++;
  13045. }
  13046. }
  13047. }
  13048. @ In order to expose report printing capabilities, we provide a property on
  13049. |QTextEdit| objects to handle this.
  13050. @<Function prototypes for scripting@>=
  13051. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine);
  13052. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *engine);
  13053. @ This function is a trivial adaptation from the Qt documentation.
  13054. @<Functions for scripting@>=
  13055. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *)
  13056. {
  13057. QTextEdit *self = getself<QTextEdit *>(context);
  13058. QTextDocument *document = self->document();
  13059. QPrinter printer;
  13060. QPrintDialog printwindow(&printer, self);
  13061. if(printwindow.exec() != QDialog::Accepted)
  13062. {
  13063. return QScriptValue();
  13064. }
  13065. document->print(&printer);
  13066. return QScriptValue();
  13067. }
  13068. @ The host environment must be informed of this function.
  13069. @<Functions for scripting@>=
  13070. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine)
  13071. {
  13072. setQAbstractScrollAreaProperties(value, engine);
  13073. value.setProperty("print", engine->newFunction(QTextEdit_print));
  13074. }
  13075. @i plugins.w
  13076. @i daterangeselector.w
  13077. @** An area for repeated user interface elements.
  13078. \noindent There are multiple use cases in which it is useful to specify a
  13079. complex aggregation of user interface elements to be repeated arbitrarily many
  13080. times. For example, placing multiple copies of a cupping form in a single area
  13081. for conveniently entering observations for all coffees in a particular session
  13082. or providing any number of copies of the form for entering coffee purchase
  13083. information. The |FormArray| widget provides this capability, allowing the
  13084. XML portion of the configuration document to specify the form once and allowing
  13085. the host environment to access the copies.
  13086. Slots and the |Q_INVOKABLE| macro are used to simplify the use of this class
  13087. from the host environment.
  13088. @<Class declarations@>=
  13089. class FormArray : public QScrollArea@/
  13090. {@t\1@>@/
  13091. Q_OBJECT@;
  13092. QDomElement configuration;
  13093. QWidget itemContainer;
  13094. QVBoxLayout itemLayout;
  13095. int maxwidth;
  13096. int maxheight;
  13097. public:@/
  13098. FormArray(QDomElement description);
  13099. @[Q_INVOKABLE@,@, QWidget*@] elementAt(int index);@t\2\2@>@/
  13100. @[Q_INVOKABLE@,@, int@] elements();@t\2\2@>@/
  13101. @t\4@>public slots@t\kern-3pt@>:@/
  13102. void addElements(int copies = 1);
  13103. void removeAllElements();
  13104. void setMaximumElementWidth(int width);
  13105. void setMaximumElementHeight(int height);@t\2@>@/
  13106. }@t\kern-3pt@>;
  13107. @ The |FormArray| is just a |QScrollArea| providing a view onto a |QWidget|
  13108. containing a layout which has arbitrarily many copies of a |QWidget| with
  13109. contents determined by the configuration document used to create the
  13110. |FormArray|.
  13111. @<FormArray implementation@>=
  13112. FormArray::FormArray(QDomElement description) : configuration(description),
  13113. maxwidth(-1), maxheight(-1)@/
  13114. {
  13115. setWidget(&itemContainer);
  13116. itemContainer.setLayout(&itemLayout);
  13117. }
  13118. @ The |FormArray| was initially created by an XML element. A copy of this is
  13119. stored in the private variable |configuration|. This can have the same child
  13120. elements as {\tt <widget>}, allowing us to reuse the function for creating
  13121. populating the widget. When adding a new element, we must resize the
  13122. |itemContainer|, otherwise Qt will attempt to cram all widgets in the layout
  13123. into the same vertical space as was previously required. The result is not
  13124. attractive. We also set a minimum width just in case the newly created widget is
  13125. the first one added to the area.
  13126. @<FormArray implementation@>=
  13127. void FormArray::addElements(int copies)
  13128. {
  13129. QStack<QWidget *> *widgetStack = new QStack<QWidget *>;
  13130. QStack<QLayout *> *layoutStack = new QStack<QLayout *>;
  13131. QWidget *widget;
  13132. for(int i = 0; i < copies; i++)
  13133. {
  13134. widget = new QWidget;
  13135. if(maxwidth > -1)
  13136. {
  13137. widget->setMaximumWidth(maxwidth);
  13138. }
  13139. if(maxheight > -1)
  13140. {
  13141. widget->setMaximumHeight(maxheight);
  13142. }
  13143. if(configuration.hasChildNodes())
  13144. {
  13145. widgetStack->push(widget);
  13146. populateWidget(configuration, widgetStack, layoutStack);
  13147. widgetStack->pop();
  13148. widget->setMinimumHeight(widget->sizeHint().height());
  13149. itemLayout.addWidget(widget);
  13150. if(widget->sizeHint().height() > maxheight && maxheight > -1)
  13151. {
  13152. itemContainer.setMinimumHeight(maxheight * elements() + 50);
  13153. }
  13154. else
  13155. {
  13156. itemContainer.setMinimumHeight(itemContainer.sizeHint().height()
  13157. + widget->sizeHint().height());
  13158. }
  13159. if(maxwidth > -1)
  13160. {
  13161. itemContainer.setMinimumWidth(maxwidth + 50);
  13162. }
  13163. else
  13164. {
  13165. itemContainer.setMinimumWidth(widget->sizeHint().width() + 50);
  13166. }
  13167. }
  13168. }
  13169. }
  13170. @ In order to retrieve a widget from the area, we use the |elementAt()| method.
  13171. The pointer returned by this function can be used as the first argument to
  13172. |findChildObject()| in the host environment in order to find any widget in the
  13173. form.
  13174. @<FormArray implementation@>=
  13175. QWidget* FormArray::elementAt(int index)
  13176. {
  13177. if(index < itemLayout.count())
  13178. {
  13179. QLayoutItem *item = itemLayout.itemAt(index);
  13180. return item->widget();
  13181. }
  13182. else
  13183. {
  13184. return NULL;
  13185. }
  13186. }
  13187. @ Removing all elements is trivial, however we must be sure to reset the size of
  13188. |itemContainer|.
  13189. @<FormArray implementation@>=
  13190. void FormArray::removeAllElements()
  13191. {
  13192. while(itemLayout.count() > 0)
  13193. {
  13194. QLayoutItem *item;
  13195. item = itemLayout.itemAt(0);
  13196. item->widget()->hide();
  13197. itemLayout.removeWidget(item->widget());
  13198. }
  13199. itemContainer.setMinimumHeight(0);
  13200. }
  13201. @ This just leaves a method for determining the number of elements already in
  13202. the view. This is equal to the number of items in the layout.
  13203. @<FormArray implementation@>=
  13204. int FormArray::elements()
  13205. {
  13206. return itemLayout.count();
  13207. }
  13208. @ Some widgets do not behave well in a |FormArray| setting and will try to use
  13209. an excess of screen space. In these cases, constraining the size of the elements
  13210. can be beneficial. These just set private member variables which are used when
  13211. adding new elements.
  13212. @<FormArray implementation@>=
  13213. void FormArray::setMaximumElementWidth(int width)
  13214. {
  13215. maxwidth = width;
  13216. }
  13217. void FormArray::setMaximumElementHeight(int height)
  13218. {
  13219. maxheight = height;
  13220. }
  13221. @ In order to create an instance of this class from the configuration document,
  13222. a {\tt <formarray>} element is used. This can be added to any layout.
  13223. @<Function prototypes for scripting@>=
  13224. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  13225. QStack<QLayout *> *layoutStack);
  13226. @ Processing child elements is deferred until a call to
  13227. |FormArray::addElements()| has been made.
  13228. @<Functions for scripting@>=
  13229. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *,@|
  13230. QStack<QLayout *> *layoutStack)
  13231. {
  13232. FormArray *widget = new FormArray(element);
  13233. if(element.hasAttribute("id"))
  13234. {
  13235. widget->setObjectName(element.attribute("id"));
  13236. }
  13237. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13238. layout->addWidget(widget);
  13239. }
  13240. @** Scale widgets.
  13241. \noindent One of the most commonly used methods of documenting the properties of
  13242. a coffee is through a cupping form. Several such forms exist to meet different
  13243. needs, however most involve several scales which can be marked to determine some
  13244. aspect of a particular attribute. Some of these scales are scored values which,
  13245. when considered with other scored values produce a numerical representation of
  13246. the quality of a given coffee. Others are unscored values which serve to provide
  13247. additional documentation of a property. For example, when the SCAA cupping form
  13248. expanded to the current form of ten scored properties with defects subtracted
  13249. from the total, a second scale was added for the acidity property. The scored
  13250. scale is used for marking the quality of the acidity while another unscored
  13251. scale is used for marking the intensity of that acidity.
  13252. Previously, in order to enter cupping information in \pn{}, numeric entry fields
  13253. were used. While this was very efficient for transcribing paper cupping forms
  13254. (and this was, in fact, the principal use case for our prototype cupping form
  13255. database software), it is not a form that lends itself to convenient use at the
  13256. cupping table.
  13257. Two new widgets are therefore introduced which allows a cupper to simply click
  13258. at some point on the scale to record that impression. Unfortunately, this is
  13259. still something of a tradeoff. It is not quite so efficient as using a paper
  13260. form in my experience, however it is faster than transcribing a stack of cupping
  13261. forms, particularly when working with cuppers with ambiguous handwriting. By
  13262. moving data acquisition to the point of data generation, a more useful record
  13263. can be produced for use in aggregate analysis.
  13264. @* The Horizontal Scale.
  13265. \noindent Several cupping forms make use of 10 point scales for the quality of
  13266. various attributes. The |ScaleControl| widget provides such a scale. It
  13267. consists of a bar with major ticks at 0, 5, and 10 and minor ticks at integer
  13268. values within this range. The first click sets both the initial and final value
  13269. of the scale while subsequent clicks adjust only the final value. A pair of
  13270. controls at each end of the scale allows the user to adjust either of these
  13271. values to compensate for imprecision at the point of the click. The two values,
  13272. an initial unscored value and a final scored value, provide some limited
  13273. temporal documentation. That is, it documents how the perception of a coffee
  13274. changes as it cools.
  13275. The widget is implemented as a |QGraphicsView| subclass. Please note that the
  13276. scale widgets are not particularly robust. In order to support a broader range
  13277. of cupping forms, there are plans to extend this class to allow user defined
  13278. range and tick patterns and user defined colors for the indicators.
  13279. @<Class declarations@>=
  13280. class ScaleControl : public QGraphicsView@/
  13281. {@t\1@>@/
  13282. Q_OBJECT@/
  13283. Q_PROPERTY(double initialValue READ initialValue WRITE setInitialValue)@/
  13284. Q_PROPERTY(double finalValue READ finalValue WRITE setFinalValue)@/
  13285. @<ScaleControl private members@>@t\2\2@>@/
  13286. public:@/
  13287. ScaleControl();
  13288. double initialValue(void);
  13289. double finalValue(void);
  13290. virtual QSize sizeHint() const;@/
  13291. @[public slots@]:@/
  13292. void setInitialValue(double value);
  13293. void setFinalValue(double value);@/
  13294. signals:@/
  13295. void initialChanged(double);
  13296. void finalChanged(double);@/
  13297. protected:@/
  13298. virtual void mousePressEvent(QMouseEvent *event);
  13299. virtual void mouseReleaseEvent(QMouseEvent *event);@t\2@>@/
  13300. }@t\kern-4pt@>;
  13301. @ The private variables available to instances of this class are used for
  13302. managing various aspects of the widget.
  13303. @<ScaleControl private members@>=
  13304. QGraphicsScene scene;
  13305. QGraphicsPolygonItem initialDecrement;
  13306. QGraphicsPolygonItem initialIncrement;
  13307. QGraphicsPolygonItem finalDecrement;
  13308. QGraphicsPolygonItem finalIncrement;
  13309. QGraphicsPolygonItem initialIndicator;
  13310. QGraphicsPolygonItem finalIndicator;
  13311. QGraphicsPathItem scaleLine;
  13312. QPolygonF left;
  13313. QPolygonF right;
  13314. QPolygonF down;
  13315. QPolygonF up;
  13316. QPainterPath scalePath;
  13317. QBrush initialBrush;
  13318. QBrush finalBrush;
  13319. double nonScoredValue;
  13320. double scoredValue;
  13321. bool initialSet;
  13322. bool finalSet;
  13323. bool scaleDown;
  13324. @ The constructor sets up the scene displayed by this widget. There is
  13325. considerable room for improvement here.
  13326. @<ScaleControl implementation@>=
  13327. ScaleControl::ScaleControl() : QGraphicsView(NULL, NULL), nonScoredValue(-1),
  13328. scoredValue(-1), initialSet(false), finalSet(false), scaleDown(false)
  13329. {
  13330. left << QPointF(0, 5) << QPointF(10, 0) << QPointF(10, 10) <<
  13331. QPointF(0, 5);
  13332. right << QPointF(10, 5) << QPointF(0, 0) << QPointF(0, 10) <<
  13333. QPointF(10, 5);
  13334. down << QPointF(0, 0) << QPointF(-5, -10) << QPointF(5, -10) <<
  13335. QPointF(0, 0);
  13336. up << QPointF(0, 0) << QPointF(-5, 10) << QPointF(4, 10) << QPointF(0, 0);
  13337. initialBrush.setColor(QColor(170, 170, 255));
  13338. initialBrush.setStyle(Qt::SolidPattern);
  13339. finalBrush.setColor(Qt::blue);
  13340. finalBrush.setStyle(Qt::SolidPattern);
  13341. initialDecrement.setPolygon(left);
  13342. initialDecrement.setBrush(initialBrush);
  13343. initialDecrement.setPos(0, 0);
  13344. scene.addItem(&initialDecrement);
  13345. initialIncrement.setPolygon(right);
  13346. initialIncrement.setBrush(initialBrush);
  13347. initialIncrement.setPos(122, 0);
  13348. scene.addItem(&initialIncrement);
  13349. finalDecrement.setPolygon(left);
  13350. finalDecrement.setBrush(finalBrush);
  13351. finalDecrement.setPos(0, 12);
  13352. scene.addItem(&finalDecrement);
  13353. finalIncrement.setPolygon(right);
  13354. finalIncrement.setBrush(finalBrush);
  13355. finalIncrement.setPos(122, 12);
  13356. scene.addItem(&finalIncrement);
  13357. scalePath.moveTo(0, 10);
  13358. scalePath.lineTo(100, 10);
  13359. scalePath.moveTo(0, 0);
  13360. scalePath.lineTo(0, 20);
  13361. scalePath.moveTo(10, 5);
  13362. scalePath.lineTo(10, 15);
  13363. scalePath.moveTo(20, 5);
  13364. scalePath.lineTo(20, 15);
  13365. scalePath.moveTo(30, 5);
  13366. scalePath.lineTo(30, 15);
  13367. scalePath.moveTo(40, 5);
  13368. scalePath.lineTo(40, 15);
  13369. scalePath.moveTo(50, 0);
  13370. scalePath.lineTo(50, 20);
  13371. scalePath.moveTo(60, 5);
  13372. scalePath.lineTo(60, 15);
  13373. scalePath.moveTo(70, 5);
  13374. scalePath.lineTo(70, 15);
  13375. scalePath.moveTo(80, 5);
  13376. scalePath.lineTo(80, 15);
  13377. scalePath.moveTo(90, 5);
  13378. scalePath.lineTo(90, 15);
  13379. scalePath.moveTo(100, 0);
  13380. scalePath.lineTo(100, 20);
  13381. scaleLine.setPath(scalePath);
  13382. scaleLine.setPos(16, 1);
  13383. scene.addItem(&scaleLine);
  13384. setScene(&scene);
  13385. initialIndicator.setPolygon(down);
  13386. initialIndicator.setBrush(initialBrush);
  13387. finalIndicator.setPolygon(up);
  13388. finalIndicator.setBrush(finalBrush);
  13389. setMinimumSize(sizeHint());
  13390. setMaximumSize(sizeHint());
  13391. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13392. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13393. setMinimumSize(sizeHint());
  13394. }
  13395. @ The size hint forces a smaller representation of the widget, making it easier
  13396. to arrange with other widgets.
  13397. @<ScaleControl implementation@>=
  13398. QSize ScaleControl::sizeHint() const
  13399. {
  13400. return QSize(140, 30);
  13401. }
  13402. @ The methods for setting the values represented on the scale must ensure that
  13403. the appropriate indicator is drawn and position it appropriately.
  13404. @<ScaleControl implementation@>=
  13405. void ScaleControl::setInitialValue(double value)@t\2\2@>@/
  13406. {@t\1@>@/
  13407. if(value >= 0 && value <= 10)@/
  13408. {@t\1@>@/
  13409. nonScoredValue = value;
  13410. if(!initialSet)
  13411. {
  13412. scene.addItem(&initialIndicator);
  13413. }
  13414. initialSet = true;
  13415. initialIndicator.setPos(value * 10 + 16, 10);
  13416. emit initialChanged(value);
  13417. if(!finalSet)
  13418. {
  13419. setFinalValue(value);
  13420. }@t\2@>@/
  13421. }@t\2@>@/
  13422. }@/@/
  13423. void ScaleControl::setFinalValue(double value)@t\2\2@>@/
  13424. {@t\1@>@/
  13425. if(value >= 0 && value <= 10)@/
  13426. {@t\1@>@/
  13427. scoredValue = value;
  13428. if(!finalSet)@/
  13429. {
  13430. scene.addItem(&finalIndicator);
  13431. }
  13432. finalSet = true;
  13433. finalIndicator.setPos(value * 10 + 16, 11);
  13434. emit finalChanged(value);@t\2@>@/
  13435. }@t\2@>@/
  13436. }
  13437. @ These values can, of course, be retrieved programmatically.
  13438. @<ScaleControl implementation@>=
  13439. double ScaleControl::initialValue(void)
  13440. {
  13441. return nonScoredValue;
  13442. }
  13443. double ScaleControl::finalValue(void)
  13444. {
  13445. return scoredValue;
  13446. }
  13447. @ This only leaves the matter of handling interaction with the widget. A future
  13448. version of this class might split the various interface elements in the scene
  13449. into distinct classes capable of using the event propagation capabilities
  13450. provided by the graphics view framework, however with the current design, we
  13451. must do a little more work.
  13452. There are two events which must be accepted in order to register a click on a
  13453. given portion of the scale. One event is generated when the mouse button is
  13454. pressed.
  13455. @<ScaleControl implementation@>=
  13456. void ScaleControl::mousePressEvent(QMouseEvent *event)
  13457. {
  13458. @<Check that the left button was pressed@>@;
  13459. scaleDown = @[true@];
  13460. event->accept();
  13461. }
  13462. @ The primary action button on the mouse is the left button. While there might
  13463. be sensible interactions to provide in response to other buttons, these are not
  13464. presently supported.
  13465. @<Check that the left button was pressed@>=
  13466. if(event->button() != Qt::LeftButton)
  13467. {
  13468. event->ignore();
  13469. return;
  13470. }
  13471. @ Most of the click event handling is done in response to releasing the mouse
  13472. button. In this event handler we must determine if the click occurred in a
  13473. clickable portion of the scale and take the appropriate action in response.
  13474. @<ScaleControl implementation@>=
  13475. void ScaleControl::mouseReleaseEvent(QMouseEvent *event)@t\2\2@>@/
  13476. {@t\1@>@/
  13477. @<Check that the left button was pressed@>@;
  13478. if(!scaleDown)
  13479. {
  13480. event->ignore();
  13481. return;
  13482. }
  13483. scaleDown = false;
  13484. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  13485. @<Handle clicks in the decrement controls@>@;
  13486. @<Handle clicks in the increment controls@>@;
  13487. @<Handle clicks in the scale area@>@;
  13488. event->ignore();
  13489. return;@t\2@>@/
  13490. }
  13491. @ As currently implemented, each horizontal pixel position represents a value
  13492. evenly divisible by $0.1$. It is, however, quite common to see vaues with a
  13493. $.25$ or $.75$ after the whole number on cupping forms. In order to make it
  13494. possible to select such values without vastly increasing the length of the
  13495. scale, the increment and decrement controls adjust the represented value by
  13496. $0.05$.
  13497. @<Handle clicks in the decrement controls@>=
  13498. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 10)
  13499. {
  13500. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13501. {
  13502. if(initialSet)
  13503. {
  13504. setInitialValue(nonScoredValue - 0.05);
  13505. }
  13506. event->accept();
  13507. return;
  13508. }
  13509. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  13510. {
  13511. if(finalSet)
  13512. {
  13513. setFinalValue(scoredValue - 0.05);
  13514. event->accept();
  13515. return;
  13516. }
  13517. }
  13518. }
  13519. @ Incrementing represented values is done in the same manner as decrementing
  13520. them.
  13521. @<Handle clicks in the increment controls@>=
  13522. else if(sceneCoordinate.x() >= 122 && sceneCoordinate.x() <= 132)
  13523. {
  13524. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13525. {
  13526. if(initialSet)
  13527. {
  13528. setInitialValue(nonScoredValue + 0.05);
  13529. event->accept();
  13530. return;
  13531. }
  13532. }
  13533. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  13534. {
  13535. if(finalSet)
  13536. {
  13537. setFinalValue(scoredValue + 0.05);
  13538. event->accept();
  13539. return;
  13540. }
  13541. }
  13542. }
  13543. @ When handling clicks in the scale area, there is a difference between the
  13544. first click and any subsequent click.
  13545. @<Handle clicks in the scale area@>=
  13546. double relativeX = sceneCoordinate.x() - 16;
  13547. if(initialSet)
  13548. {
  13549. if(relativeX >= 0 && relativeX <= 100)
  13550. {
  13551. setFinalValue(relativeX / 10.0);
  13552. event->accept();
  13553. return;
  13554. }
  13555. }
  13556. else
  13557. {
  13558. if(relativeX >= 0 && relativeX <= 100)
  13559. {
  13560. setInitialValue(relativeX / 10.0);
  13561. event->accept();
  13562. return;
  13563. }
  13564. }
  13565. @* The Vertical Scale.
  13566. \noindent In addition to the horizontal scale, there is also a vertical scale.
  13567. The implementation of this class is in some ways a bit simpler as only one value
  13568. must be retained. While there is no prohibition on using this scale for scored
  13569. values (and this might enable a rather compact representation which might be
  13570. useful in some applications), its intent is for unscored values which are less
  13571. likely to change over time. If the dry aroma of a coffee changes significantly
  13572. during a cupping session, you are most likely waiting far too long to pour the
  13573. water.
  13574. @<Class declarations@>=
  13575. class IntensityControl : public QGraphicsView@/
  13576. {@/
  13577. @[Q_OBJECT@]@;
  13578. @[Q_PROPERTY(double value READ value WRITE setValue)@]@;
  13579. QGraphicsScene scene;
  13580. QGraphicsPolygonItem decrement;
  13581. QGraphicsPolygonItem increment;
  13582. QGraphicsPolygonItem indicator;
  13583. QGraphicsPathItem scaleLine;
  13584. QPolygonF left;
  13585. QPolygonF up;
  13586. QPolygonF down;
  13587. QPainterPath scalePath;
  13588. QBrush theBrush;
  13589. double theValue;
  13590. bool valueSet;
  13591. bool scaleDown;
  13592. public:@/
  13593. IntensityControl();
  13594. double value();
  13595. virtual QSize sizeHint() const;@/
  13596. @[public slots@]:@/
  13597. void setValue(double val);@/
  13598. signals:@/
  13599. void valueChanged(double);@/
  13600. protected:@/
  13601. virtual void mousePressEvent(QMouseEvent *event);
  13602. virtual void mouseReleaseEvent(QMouseEvent *event);@/
  13603. };
  13604. @ Note the similarity between this constructor and the the |ScaleControl|
  13605. constructor.
  13606. @<IntensityControl implementation@>=
  13607. IntensityControl::IntensityControl() : QGraphicsView(NULL, NULL), theValue(-1),
  13608. valueSet(false), scaleDown(false)
  13609. {
  13610. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13611. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13612. left << QPointF(0, 0) << QPointF(10, -5) << QPointF(10, 5) << QPointF(0, 0);
  13613. down << QPointF(0, 0) << QPointF(10, 0) << QPointF(5, 10) << QPointF(0, 0);
  13614. up << QPointF(0, 10) << QPointF(10, 10) << QPointF(5, 0) << QPointF(0, 10);
  13615. theBrush.setColor(Qt::blue);
  13616. theBrush.setStyle(Qt::SolidPattern);
  13617. increment.setPolygon(up);
  13618. increment.setBrush(theBrush);
  13619. increment.setPos(0, 0);
  13620. scene.addItem(&increment);
  13621. decrement.setPolygon(down);
  13622. decrement.setBrush(theBrush);
  13623. decrement.setPos(0, 122);
  13624. scene.addItem(&decrement);
  13625. scalePath.moveTo(5, 0);
  13626. scalePath.lineTo(5, 100);
  13627. scalePath.moveTo(0, 0);
  13628. scalePath.lineTo(10, 0);
  13629. scalePath.moveTo(0, 10);
  13630. scalePath.lineTo(10, 10);
  13631. scalePath.moveTo(0, 20);
  13632. scalePath.lineTo(10, 20);
  13633. scalePath.moveTo(0, 30);
  13634. scalePath.lineTo(10, 30);
  13635. scalePath.moveTo(0, 40);
  13636. scalePath.lineTo(10, 40);
  13637. scalePath.moveTo(0, 50);
  13638. scalePath.lineTo(10, 50);
  13639. scalePath.moveTo(0, 60);
  13640. scalePath.lineTo(10, 60);
  13641. scalePath.moveTo(0, 70);
  13642. scalePath.lineTo(10, 70);
  13643. scalePath.moveTo(0, 80);
  13644. scalePath.lineTo(10, 80);
  13645. scalePath.moveTo(0, 90);
  13646. scalePath.lineTo(10, 90);
  13647. scalePath.moveTo(0, 100);
  13648. scalePath.lineTo(10, 100);
  13649. scaleLine.setPath(scalePath);
  13650. scaleLine.setPos(0, 16);
  13651. scene.addItem(&scaleLine);
  13652. setScene(&scene);
  13653. indicator.setPolygon(left);
  13654. indicator.setBrush(theBrush);
  13655. setMinimumSize(sizeHint());
  13656. setMaximumSize(sizeHint());
  13657. }
  13658. @ Once again, the size hint reduces the default size of the widget.
  13659. @<IntensityControl implementation@>=
  13660. QSize IntensityControl::sizeHint() const
  13661. {
  13662. return QSize(25, 160);
  13663. }
  13664. @ To support a more intuitive numerical representation, higher values should map
  13665. to higher positions on the scale. This is contrary to the coordinate system
  13666. provided by Qt, so the code setting the position of the indicator on the scale
  13667. must account for this.
  13668. During testing of this class, I found that it was impossible to select the
  13669. values 0 or 10 either through a click or with the increment or decrement
  13670. controls. Adding two additional execution branches corrects this issue.
  13671. @<IntensityControl implementation@>=
  13672. void IntensityControl::setValue(double val)
  13673. {
  13674. if(val >= 0 && val <= 10)
  13675. {
  13676. theValue = val;
  13677. if(!valueSet)
  13678. {
  13679. scene.addItem(&indicator);
  13680. }
  13681. valueSet = @[true@];
  13682. indicator.setPos(6, (100 - (val * 10)) + 16);
  13683. emit(valueChanged(val));
  13684. }
  13685. else if(val < 1)
  13686. {
  13687. setValue(0);
  13688. }
  13689. else
  13690. {
  13691. setValue(10);
  13692. }
  13693. }
  13694. double IntensityControl::value()
  13695. {
  13696. return theValue;
  13697. }
  13698. @ Mouse event handling is similar as well. The mouse press event simply notes
  13699. that the button has been pressed.
  13700. @<IntensityControl implementation@>=
  13701. void IntensityControl::mousePressEvent(QMouseEvent *event)
  13702. {
  13703. @<Check that the left button was pressed@>@;
  13704. scaleDown = @[true@];
  13705. event->accept();
  13706. }
  13707. @ Since there are fewer clickable areas there are fewer regions to check while
  13708. handling the mouse release event. Just as the |setValue()| method must
  13709. compensate for a mismatch between the scale and the underlying coordinate
  13710. system, so must click handling in the scale area take this into consideration
  13711. when determining which value the click intends.
  13712. @<IntensityControl implementation@>=
  13713. void IntensityControl::mouseReleaseEvent(QMouseEvent *event)
  13714. {
  13715. @<Check that the left button was pressed@>@;
  13716. if(!scaleDown)
  13717. {
  13718. event->ignore();
  13719. return;
  13720. }
  13721. scaleDown = @[false@];
  13722. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  13723. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 16)
  13724. {
  13725. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13726. {
  13727. if(valueSet)
  13728. {
  13729. setValue(theValue + 0.05);
  13730. }
  13731. event->accept();
  13732. return;
  13733. }
  13734. else if(sceneCoordinate.y() >= 122 && sceneCoordinate.y() <= 132)
  13735. {
  13736. if(valueSet)
  13737. {
  13738. setValue(theValue - 0.05);
  13739. }
  13740. event->accept();
  13741. return;
  13742. }
  13743. else if(sceneCoordinate.y() >= 16 && sceneCoordinate.y() <= 116)
  13744. {
  13745. setValue(10 - ((sceneCoordinate.y() - 16) / 10.0));
  13746. event->accept();
  13747. return;
  13748. }
  13749. }
  13750. }
  13751. @* Scripting the Scale Widgets.
  13752. \noindent Scale widgets can be added through the configuration system with
  13753. {\tt <hscale>} and {\tt <vscale>} elements. These can be added to layouts.
  13754. @<Function prototypes for scripting@>=
  13755. void addScaleControlToLayout(QDomElement element,
  13756. QStack<QWidget *> *widgetStack,
  13757. QStack<QLayout *> *layoutStack);
  13758. void addIntensityControlToLayout(QDomElement element,
  13759. QStack<QWidget *> *widgetStack,
  13760. QStack<QLayout *> *layoutStack);
  13761. @ Adding these widgets is done in the same way as adding other widgets.
  13762. @<Functions for scripting@>=
  13763. void addScaleControlToLayout(QDomElement element, QStack<QWidget *> *,
  13764. QStack<QLayout *> *layoutStack)
  13765. {
  13766. ScaleControl *scale = new ScaleControl;
  13767. if(element.hasAttribute("id"))
  13768. {
  13769. scale->setObjectName(element.attribute("id"));
  13770. }
  13771. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13772. layout->addWidget(scale);
  13773. }
  13774. void addIntensityControlToLayout(QDomElement element, QStack<QWidget *> *,
  13775. QStack<QLayout *> *layoutStack)
  13776. {
  13777. IntensityControl *scale = new IntensityControl;
  13778. if(element.hasAttribute("id"))
  13779. {
  13780. scale->setObjectName(element.attribute("id"));
  13781. }
  13782. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13783. layout->addWidget(scale);
  13784. }
  13785. @** Device Configuration.
  13786. \noindent Starting in \pn{} 1.4, all supported measurement hardware is
  13787. available from the same build and it is possible to use multiple devices from
  13788. differernt vendors at the same time. In previous versions, there were very few
  13789. available hardware configurations and a small number of example configuration
  13790. documents covered the needs of most people using the software. As more hardware
  13791. is supported and more people with distinct needs start using \pn{}, that
  13792. approach becomes unsustainable and the need for in-program configuration
  13793. becomes increasingly pronounced.
  13794. Device configuration is coupled to configuration of the logging window and
  13795. it is possible to configure multiple different roasters with different hardware
  13796. and other customizations of the logging window specific to a particular
  13797. machine.
  13798. The core of this is the use of an XML document saved with |QSettings| under
  13799. the |"DeviceConfiguration"| key. Within the root {\tt <DeviceConfiguration>}
  13800. element there are two grouping elements: {\tt <devices>} and
  13801. {\tt <references>}. The terminology was developed at a time when it was
  13802. thought that hardware configuration and logging view configuration would be
  13803. decoupled from each other, however the benefits of combining these far
  13804. outweighed the minor loss of flexibility with this approach.
  13805. Within the {\tt <devices>} tag there are arbitrarily many {\tt <node>} tags
  13806. which themselves may contain {\tt <node>} tags nested to any depth. Each of
  13807. these has two attributes, a {\tt name} attribute which specifies the display
  13808. text used to represent that node and a {\tt reference} attribute with a
  13809. unique value. Typica will generate a UUID for each node to use as the unique
  13810. value but this is not strictly required. The {\tt name} attribute does not
  13811. need to be unique and will generally be supplied by the person using the
  13812. software. The top level {\tt node} elements represent a coffee roaster and
  13813. the sub-elements can represent hardware, annotation controls, and possibly
  13814. other configurable features.
  13815. Within the {\tt <references>} tag there are as many {\tt <reference>} tags as
  13816. there are {\tt <node>} tags. Each of these has an {\tt id} attribute which
  13817. matches the {\tt reference} attribute in a {\tt <node>} tag and a {\tt driver}
  13818. attribute which is used to determine which class should be used to interact
  13819. with these settings. In the case of device configuration, this allows a
  13820. determination of which class should be used to generate an editor for settings
  13821. related to that node. Within each {\tt <reference>} tag is an arbitrary number
  13822. of {\tt <attribute>} tags with {\tt name} and {\tt value} attributes. Code for
  13823. providing the settings widgets and device interfaces can use these for any
  13824. desired purpose, but it is common to have one {\tt <attribute>} tag per setting
  13825. appropriate for a given node and possibly more to identify the concept a
  13826. particular node represents.
  13827. The global |Application| object is extended to maintain a |QDomDocument|
  13828. representation of this XML document.
  13829. @<Application private data members@>=
  13830. QDomDocument deviceConfigurationDocument;
  13831. @ Two methods are also provided for interacting with this document. The
  13832. |deviceConfiguration()| method returns a pointer to the private data member,
  13833. loading the XML from |QSettings| if required and creating a new document with
  13834. no {\tt <node>} tags if the document does not exist in settings. The
  13835. |saveDeviceConfiguration()| method serializes the |QDomDocument| to settings.
  13836. @<Device configuration members@>=
  13837. QDomDocument deviceConfiguration();
  13838. @ The method for saving should be a slot so a model representing this data
  13839. can persist changes through the signals and slots mechanism rather than
  13840. requiring the calls to be explicitn.
  13841. @<Extended Application slots@>=
  13842. void saveDeviceConfiguration();
  13843. @ Serializing the current configuration is trivial.
  13844. @<Application Implementation@>=
  13845. void Application::saveDeviceConfiguration()
  13846. {
  13847. QSettings settings;
  13848. settings.setValue("DeviceConfiguration",
  13849. QVariant(deviceConfigurationDocument.toByteArray()));
  13850. }
  13851. @ Producing a pointer to a loaded configuration only slightly more complicated.
  13852. If the configuration has been previously loaded we just return the pointer.
  13853. Otherwise, we attempt to load the document.
  13854. @<Application Implementation@>=
  13855. QDomDocument Application::deviceConfiguration()
  13856. {
  13857. if(deviceConfigurationDocument.isNull())
  13858. {
  13859. @<Load device configuration document from settings@>@;
  13860. }
  13861. return deviceConfigurationDocument;
  13862. }
  13863. @ In most cases a document will already exist in settings, but we must verify
  13864. this and create a new document if it does not exist. We also clear device
  13865. configuration settings if the configuration document is invalid.
  13866. @<Load device configuration document from settings@>=
  13867. QSettings settings;
  13868. QByteArray document = settings.value("DeviceConfiguration").toByteArray();
  13869. QString etext;
  13870. int eline;
  13871. int ecol;
  13872. if(document.length() == 0)
  13873. {
  13874. qDebug() << "Loaded settings length is 0. Creating new configuration.";
  13875. @<Create device configuration document@>@;
  13876. }
  13877. else
  13878. {
  13879. if(!deviceConfigurationDocument.setContent(document, false,
  13880. &etext, &eline, &ecol))
  13881. {
  13882. @<Report configuration loading error@>@;
  13883. @<Create device configuration document@>@;
  13884. }
  13885. }
  13886. @ Rather than generate the empty device configuration programmatically, we keep
  13887. an empty device configuration document as a resource.
  13888. @<Create device configuration document@>=
  13889. QFile emptyDocument(":/resources/xml/EmptyDeviceConfiguration.xml");
  13890. emptyDocument.open(QIODevice::ReadOnly);
  13891. if(!deviceConfigurationDocument.setContent(&emptyDocument, false,
  13892. &etext, &eline, &ecol))
  13893. {
  13894. @<Report configuration loading error@>@;
  13895. }
  13896. else
  13897. {
  13898. saveDeviceConfiguration();
  13899. }
  13900. @ There isn'@q'@>t really anything that can be done if the device configuration data
  13901. is corrupt, but an error message can be produced if the program happens to have
  13902. access to a debugging console.
  13903. @<Report configuration loading error@>=
  13904. qDebug() << QString(tr("An error occurred loading device configuration."));
  13905. qDebug() << QString(tr("Line %1, Column %2")).arg(eline).arg(ecol);
  13906. qDebug() << etext;
  13907. @* Model and view for device configuration hierarchy.
  13908. \noindent When manipulating device configuration data, it can be useful to
  13909. present the device hierarchy in a tree view. To do this, we use two classes to
  13910. produce a tree model. This is slightly extended and modified from an example
  13911. in the Qt documentation.\nfnote{Simple DOM Model Example:\par\indent\pdfURL{%
  13912. http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}
  13913. {http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}}
  13914. Our model uses the |DeviceTreeModelNode| class to cache the |QDomNode|
  13915. instances with the data we want.
  13916. @<Class declarations@>=
  13917. class DeviceTreeModelNode
  13918. {
  13919. public:
  13920. DeviceTreeModelNode(QDomNode &node, int row,
  13921. DeviceTreeModelNode *parent = NULL);
  13922. ~DeviceTreeModelNode();
  13923. DeviceTreeModelNode *child(int index);
  13924. DeviceTreeModelNode *parent();
  13925. QDomNode node() const;
  13926. int row();
  13927. private:
  13928. QDomNode domNode;
  13929. QHash<int, DeviceTreeModelNode*> children;
  13930. int rowNumber;
  13931. DeviceTreeModelNode *parentItem;
  13932. };
  13933. @ Implementation of this helper class is trivial.
  13934. @<DeviceTreeModelNode implementation@>=
  13935. DeviceTreeModelNode::DeviceTreeModelNode(QDomNode &node, int row,
  13936. DeviceTreeModelNode *parent)
  13937. : domNode(node), rowNumber(row), parentItem(parent)
  13938. {
  13939. /* Nothing needs to be done here. */
  13940. }
  13941. DeviceTreeModelNode::~DeviceTreeModelNode()
  13942. {
  13943. QHash<int, DeviceTreeModelNode *>::iterator@, i;
  13944. for(i = children.begin(); i != children.end(); i++)
  13945. {
  13946. delete i.value();
  13947. }
  13948. }
  13949. DeviceTreeModelNode *DeviceTreeModelNode::parent()
  13950. {
  13951. return parentItem;
  13952. }
  13953. int DeviceTreeModelNode::row()
  13954. {
  13955. return rowNumber;
  13956. }
  13957. QDomNode DeviceTreeModelNode::node() const
  13958. {
  13959. return domNode;
  13960. }
  13961. DeviceTreeModelNode *DeviceTreeModelNode::child(int index)
  13962. {
  13963. if(children.contains(index))
  13964. {
  13965. return children[index];
  13966. }
  13967. if(index >= 0 && index < domNode.childNodes().count())
  13968. {
  13969. QDomNode childNode = domNode.childNodes().item(index);
  13970. DeviceTreeModelNode *childItem = new DeviceTreeModelNode(childNode,
  13971. index, this);
  13972. children[index] = childItem;
  13973. return childItem;
  13974. }
  13975. return NULL;
  13976. }
  13977. @ The model class provides a single column representation of the {\tt devices}
  13978. section of the device configuration document. It provides methods for editing
  13979. the name of any node, for adding new nodes to the model, for deleting any node
  13980. in the model, and for obtaining the {\tt reference} element corresponding to
  13981. a given node.
  13982. @<Class declarations@>=
  13983. class DeviceTreeModel : public QAbstractItemModel@/
  13984. {@/
  13985. @[Q_OBJECT@]@;
  13986. public:@/
  13987. DeviceTreeModel(QObject *parent = NULL);
  13988. ~DeviceTreeModel();
  13989. QVariant data(const QModelIndex &index, int role) const;
  13990. Qt::ItemFlags flags(const QModelIndex &index) const;
  13991. QVariant headerData(int section, Qt::Orientation orientation,
  13992. int role = Qt::DisplayRole) const;
  13993. QModelIndex index(int row, int column,
  13994. const QModelIndex &parent = QModelIndex()) const;
  13995. QModelIndex parent(const QModelIndex &child) const;
  13996. Q_INVOKABLE int rowCount(const QModelIndex &parent = QModelIndex()) const;
  13997. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  13998. bool setData(const QModelIndex &index, const QVariant &value,
  13999. int role);
  14000. bool removeRows(int row, int count, const QModelIndex &parent);
  14001. QDomElement referenceElement(const QString &id);
  14002. @[public slots@]:@/
  14003. void newNode(const QString &name, const QString &driver,
  14004. const QModelIndex &parent);
  14005. private:@/
  14006. QDomDocument document;
  14007. DeviceTreeModelNode *root;
  14008. QDomNode referenceSection;
  14009. QDomNode treeRoot;
  14010. };
  14011. @ In the constructor we locate the {\tt devices} and {\tt references} sections
  14012. of the passed in document. Our tree of cached |QDomNode| elements starts with
  14013. the former and is expanded as needed.
  14014. @<DeviceTreeModel implementation@>=
  14015. DeviceTreeModel::DeviceTreeModel(QObject *parent)
  14016. : QAbstractItemModel(parent)
  14017. {
  14018. document = AppInstance->deviceConfiguration();
  14019. QDomNodeList elements = document.elementsByTagName("devices");
  14020. if(elements.size() != 1)
  14021. {
  14022. qDebug() << "Unexpected result when loading device map.";
  14023. }
  14024. treeRoot = elements.at(0);
  14025. root = new DeviceTreeModelNode(treeRoot, 0);
  14026. elements = document.elementsByTagName("references");
  14027. if(elements.size() != 1)
  14028. {
  14029. qDebug() << "No references section. Creating.";
  14030. referenceSection = document.createElement("references");
  14031. document.appendChild(referenceSection);
  14032. }
  14033. else
  14034. {
  14035. referenceSection = elements.at(0);
  14036. }
  14037. connect(this, SIGNAL(dataChanged(QModelIndex, QModelIndex)),
  14038. AppInstance, SLOT(saveDeviceConfiguration()));
  14039. connect(this, SIGNAL(modelReset()),
  14040. AppInstance, SLOT(saveDeviceConfiguration()));
  14041. connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)),
  14042. AppInstance, SLOT(saveDeviceConfiguration()));
  14043. }
  14044. @ We only provide a single column for our model, so |columnCount()| can simply
  14045. return a constant. The |rowCount()| method can return a variety of values
  14046. depending on the parent node.
  14047. @<DeviceTreeModel implementation@>=
  14048. int DeviceTreeModel::columnCount(const QModelIndex &) const
  14049. {
  14050. return 1;
  14051. }
  14052. int DeviceTreeModel::rowCount(const QModelIndex &parent) const
  14053. {
  14054. if(parent.column() > 0)
  14055. {
  14056. return 0;
  14057. }
  14058. @<Get parent item from index@>@;
  14059. return parentItem->node().childNodes().count();
  14060. }
  14061. @ If an invalid index is passed as the parent index, we assume the parent to
  14062. be the root element.
  14063. @<Get parent item from index@>=
  14064. DeviceTreeModelNode *parentItem;
  14065. if(!parent.isValid())
  14066. {
  14067. parentItem = root;
  14068. }
  14069. else
  14070. {
  14071. parentItem = static_cast<DeviceTreeModelNode *>(parent.internalPointer());
  14072. }
  14073. @ As seen in |rowCount()|, we keep a pointer to the cached node in our model
  14074. indices.
  14075. @<DeviceTreeModel implementation@>=
  14076. QModelIndex DeviceTreeModel::index(int row, int column,
  14077. const QModelIndex &parent) const
  14078. {
  14079. if(!hasIndex(row, column, parent))
  14080. {
  14081. return QModelIndex();
  14082. }
  14083. @<Get parent item from index@>@;
  14084. DeviceTreeModelNode *childItem = parentItem->child(row);
  14085. if(childItem)
  14086. {
  14087. return createIndex(row, column, childItem);
  14088. }
  14089. return QModelIndex();
  14090. }
  14091. @ We can also request an index for the parent of a given index.
  14092. @<DeviceTreeModel implementation@>=
  14093. QModelIndex DeviceTreeModel::parent(const QModelIndex &child) const
  14094. {
  14095. if(!child.isValid())
  14096. {
  14097. return QModelIndex();
  14098. }
  14099. DeviceTreeModelNode *childItem =
  14100. static_cast<DeviceTreeModelNode *>(child.internalPointer());
  14101. DeviceTreeModelNode *parentItem = childItem->parent();
  14102. if(!parentItem || parentItem == root)
  14103. {
  14104. return QModelIndex();
  14105. }
  14106. return createIndex(parentItem->row(), 0, parentItem);
  14107. }
  14108. @ All items should be enabled, selectable, and editable.
  14109. @<DeviceTreeModel implementation@>=
  14110. Qt::ItemFlags DeviceTreeModel::flags(const QModelIndex &index) const
  14111. {
  14112. if(!index.isValid())
  14113. {
  14114. return 0;
  14115. }
  14116. return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
  14117. }
  14118. @ Each node in the model maintains two pieces of information. One is the
  14119. display value for the node which is held in the {\tt name} attribute of the
  14120. corresponding XML element. The other is a reference ID held in the
  14121. {\tt reference} attribute.
  14122. @<DeviceTreeModel implementation@>=
  14123. QVariant DeviceTreeModel::data(const QModelIndex &index, int role) const
  14124. {
  14125. if(!index.isValid())
  14126. {
  14127. return QVariant();
  14128. }
  14129. if(role != Qt::DisplayRole && role != Qt::UserRole && role != Qt::EditRole)
  14130. {
  14131. return QVariant();
  14132. }
  14133. DeviceTreeModelNode *item =
  14134. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  14135. QDomNode node = item->node();
  14136. QDomElement element = node.toElement();
  14137. switch(role)
  14138. {
  14139. case Qt::DisplayRole:@/
  14140. case Qt::EditRole:@/
  14141. return QVariant(element.attribute("name"));
  14142. case Qt::UserRole:@/
  14143. return QVariant(element.attribute("reference"));
  14144. default:@/
  14145. return QVariant();
  14146. }
  14147. return QVariant();
  14148. }
  14149. @ The reference value is managed by the model and should never be changed. The
  14150. display value for a node is, however, editable. These changes must propagate
  14151. back to the XML document underlying the model.
  14152. @<DeviceTreeModel implementation@>=
  14153. bool DeviceTreeModel::setData(const QModelIndex &index,
  14154. const QVariant &value, int)@;@/
  14155. {@t\1@>@/
  14156. if(!index.isValid())@/
  14157. {@t\1@>@/
  14158. return false;@t\2@>@/
  14159. }@/
  14160. DeviceTreeModelNode *item =
  14161. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  14162. QDomNode node = item->node();
  14163. QDomElement element = node.toElement();
  14164. element.setAttribute("name", value.toString());
  14165. emit dataChanged(index, index);@;
  14166. return true;@t\2@>@/
  14167. }
  14168. @ A custom method is provided for adding new nodes to the model. This generates
  14169. the two XML elements needed for the node. The |name| parameter is the display
  14170. name of the new node, the |driver| parameter is used as the value for the
  14171. {\tt driver} attribute in the {\tt reference} element which will be used to
  14172. determine what classes are used to work with that data.
  14173. @<DeviceTreeModel implementation@>=
  14174. void DeviceTreeModel::newNode(const QString &name, const QString &driver,
  14175. const QModelIndex &parent)
  14176. {
  14177. QString referenceID = QUuid::createUuid().toString();
  14178. @<Get parent item from index@>@;
  14179. QDomNode parentNode = parentItem->node();
  14180. int newRowNumber = rowCount(parent);
  14181. beginInsertRows(parent, newRowNumber, newRowNumber);
  14182. QDomElement deviceElement = document.createElement("node");
  14183. deviceElement.setAttribute("name", name);
  14184. deviceElement.setAttribute("reference", referenceID);
  14185. parentNode.appendChild(deviceElement);
  14186. QDomElement referenceElement = document.createElement("reference");
  14187. referenceElement.setAttribute("id", referenceID);
  14188. referenceElement.setAttribute("driver", driver);
  14189. referenceSection.appendChild(referenceElement);
  14190. endInsertRows();
  14191. }
  14192. @ We can also delete nodes. When deleting a node, both XML elements are
  14193. removed and our node cache is invalidated.
  14194. @<DeviceTreeModel implementation@>=
  14195. bool DeviceTreeModel::removeRows(int row, int count, const QModelIndex &parent)@t\2\2@>@/
  14196. {@t\1@>@/
  14197. @<Get parent item from index@>@;
  14198. QDomNode parentNode = parentItem->node();
  14199. QDomNodeList childNodes = parentNode.childNodes();@;
  14200. if(childNodes.size() < row + count)@/
  14201. {@t\1@>@/
  14202. return false;@t\2@>@/
  14203. }@/
  14204. beginRemoveRows(parent, row, row + count - 1);
  14205. QList<QDomElement> removalList;
  14206. for(int i = row; i < row + count; i++)
  14207. {
  14208. removalList.append(childNodes.at(i).toElement());
  14209. }
  14210. QDomElement element;
  14211. QDomElement reference;
  14212. for(int i = 0; i < count; i++)
  14213. {
  14214. element = removalList.at(i);
  14215. if(element.hasAttribute("reference"))
  14216. {
  14217. reference = referenceElement(element.attribute("reference"));
  14218. if(!reference.isNull())
  14219. {
  14220. referenceSection.removeChild(reference);
  14221. }
  14222. }
  14223. parentNode.removeChild(element);
  14224. }
  14225. endRemoveRows();
  14226. beginResetModel();
  14227. delete root;
  14228. root = new DeviceTreeModelNode(treeRoot, 0);
  14229. endResetModel();@;
  14230. return true;@t\2@>@/
  14231. }
  14232. @ Another custom method obtains the {\tt reference} element for a given
  14233. reference ID.
  14234. @<DeviceTreeModel implementation@>=
  14235. QDomElement DeviceTreeModel::referenceElement(const QString &id)
  14236. {
  14237. QDomNodeList childNodes = referenceSection.childNodes();
  14238. QDomElement element;
  14239. for(int i = 0; i < childNodes.size(); i++)
  14240. {
  14241. element = childNodes.at(i).toElement();
  14242. if(element.hasAttribute("id"))
  14243. {
  14244. if(element.attribute("id") == id)
  14245. {
  14246. return element;
  14247. }
  14248. }
  14249. }
  14250. return QDomElement();
  14251. }
  14252. @ We don'@q'@>t want any headers, so |headerData()| is very simple.
  14253. @<DeviceTreeModel implementation@>=
  14254. QVariant DeviceTreeModel::headerData(int, Qt::Orientation, int) const
  14255. {
  14256. return QVariant();
  14257. }
  14258. @ The destructor destroys the node cache. The destructor for the top level node
  14259. will recursively destroy all child nodes.
  14260. @<DeviceTreeModel implementation@>=
  14261. DeviceTreeModel::~DeviceTreeModel()
  14262. {
  14263. delete root;
  14264. }
  14265. @ Exposing this class to the host environment allows a number of interesting
  14266. possibilities. Setting the model to a combo box, for example, allows the
  14267. selection of top level nodes representing a particular coffee roaster. It is
  14268. also useful to have the ability to traverse a specified sub-tree of the model
  14269. to set up a logging view that matches the configuration for such a selected
  14270. roaster.
  14271. @<Function prototypes for scripting@>=
  14272. QScriptValue constructDeviceTreeModel(QScriptContext *context,
  14273. QScriptEngine *engine);
  14274. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine);
  14275. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine);
  14276. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  14277. QScriptEngine *engine);
  14278. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine);
  14279. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine);
  14280. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context, QScriptEngine *engine);
  14281. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context, QScriptEngine *engine);
  14282. @ The constructor is trivial.
  14283. @<Functions for scripting@>=
  14284. QScriptValue constructDeviceTreeModel(QScriptContext *, QScriptEngine *engine)
  14285. {
  14286. QScriptValue object = engine->newQObject(new DeviceTreeModel);
  14287. setDeviceTreeModelProperties(object, engine);
  14288. return object;
  14289. }
  14290. @ As usual the host environment is informed of this constructor.
  14291. @<Set up the scripting engine@>=
  14292. constructor = engine->newFunction(constructDeviceTreeModel);
  14293. value = engine->newQMetaObject(&DeviceTreeModel::staticMetaObject,
  14294. constructor);
  14295. engine->globalObject().setProperty("DeviceTreeModel", value);
  14296. @ A number of properties are set to allow script code to traverse the model.
  14297. Most of these properties are properly members of |QAbstractItemModel| and
  14298. the code is written to allow any models that may be exposed to the host
  14299. environment in the future to make use of these as well. Note that this is not
  14300. a full set of functionality but only what I needed to implement a particular
  14301. feature set.
  14302. @<Functions for scripting@>=
  14303. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine)
  14304. {
  14305. setQAbstractItemModelProperties(value, engine);
  14306. value.setProperty("referenceElement",
  14307. engine->newFunction(DeviceTreeModel_referenceElement));
  14308. }
  14309. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine)
  14310. {
  14311. setQObjectProperties(value, engine);
  14312. value.setProperty("data", engine->newFunction(QAbstractItemModel_data));
  14313. value.setProperty("index", engine->newFunction(QAbstractItemModel_index));
  14314. value.setProperty("rowCount", engine->newFunction(QAbstractItemModel_rowCount));
  14315. value.setProperty("hasChildren", engine->newFunction(QAbstractItemModel_hasChildren));
  14316. }
  14317. @ The wrapped call to |referenceElement| does a little more than might be
  14318. expected. Rather than returning a |QDomElement| and leaving it up to script
  14319. code to traverse the sub-tree, we create a |QVariantMap| which in script code
  14320. is translated as an object with the keys as properties of the object containing
  14321. the values of those keys. This is populated by first specifying a {\tt driver}
  14322. key with its value from the {\tt driver} attribute of the {\tt reference} node.
  14323. We then examine the {\tt <attribute>} sub-elements and use the {\tt name}
  14324. attribute as keys and the {\tt value} attribute as values to fill out the rest
  14325. of the map.
  14326. @<Functions for scripting@>=
  14327. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  14328. QScriptEngine *engine)
  14329. {
  14330. DeviceTreeModel *model = getself<DeviceTreeModel *>(context);
  14331. QDomElement referenceElement = model->referenceElement(argument<QString>(0, context));
  14332. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14333. QDomElement node;
  14334. QVariantMap retval;
  14335. retval.insert("driver", referenceElement.attribute("driver"));
  14336. for(int i = 0; i < configData.size(); i++)
  14337. {
  14338. node = configData.at(i).toElement();
  14339. retval.insert(node.attribute("name"), node.attribute("value"));
  14340. }
  14341. return engine->toScriptValue(retval);
  14342. }
  14343. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine)
  14344. {
  14345. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14346. QModelIndex index = argument<QModelIndex>(0, context);
  14347. int role = argument<int>(1, context);
  14348. return engine->toScriptValue(model->data(index, role));
  14349. }
  14350. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine)
  14351. {
  14352. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14353. int row = 0;
  14354. int column = 0;
  14355. QModelIndex index;
  14356. if(context->argumentCount() > 1)
  14357. {
  14358. row = argument<int>(0, context);
  14359. column = argument<int>(1, context);
  14360. }
  14361. if(context->argumentCount() > 2)
  14362. {
  14363. index = argument<QModelIndex>(2, context);
  14364. }
  14365. QModelIndex retval = model->index(row, column, index);
  14366. return engine->toScriptValue(retval);
  14367. }
  14368. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context,
  14369. QScriptEngine *)
  14370. {
  14371. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14372. QModelIndex index;
  14373. if(context->argumentCount() == 1)
  14374. {
  14375. index = argument<QModelIndex>(0, context);
  14376. }
  14377. return QScriptValue(model->rowCount(index));
  14378. }
  14379. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context,
  14380. QScriptEngine *engine)
  14381. {
  14382. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14383. QModelIndex index;
  14384. if(context->argumentCount() == 1)
  14385. {
  14386. index = argument<QModelIndex>(0, context);
  14387. }
  14388. return QScriptValue(engine, model->hasChildren(index));
  14389. }
  14390. @ Some additional work is needed to handle |QModelIndex| appropriately. First
  14391. we declare that as a metatype.
  14392. @<Class declarations@>=
  14393. Q_DECLARE_METATYPE(QModelIndex)
  14394. @ Next we need a pair of functions to convert |QModelIndex| to and from script
  14395. values.
  14396. @<Function prototypes for scripting@>=
  14397. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index);
  14398. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index);
  14399. @ These are implemented thusly.
  14400. @<Functions for scripting@>=
  14401. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index)
  14402. {
  14403. QVariant var;
  14404. var.setValue(index);
  14405. QScriptValue object = engine->newVariant(var);
  14406. return object;
  14407. }
  14408. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index)
  14409. {
  14410. index = value.toVariant().value<QModelIndex>();
  14411. }
  14412. @ Finally we register this with the engine.
  14413. @<Set up the scripting engine@>=
  14414. qScriptRegisterMetaType(engine, QModelIndex_toScriptValue, QModelIndex_fromScriptValue);
  14415. @* Device Configuration Widgets.
  14416. \noindent Each node in the {\tt devices} section of the |DeviceTreeModel| is
  14417. associated with a {\tt reference} element that provides a driver string which
  14418. can be used to identify the classes used to interact with the device
  14419. configuration data. An example of this is selecting which widget to use when
  14420. selecting a node in a configuration window. These widgets must be registered
  14421. to the appropriate driver string in advance. This is currently handled through
  14422. the |Application| instance, though it would probably be better to split this
  14423. into its own class at some point in the future.
  14424. @<Application private data members@>=
  14425. QHash<QString, QMetaObject> deviceConfigurationWidgets;
  14426. @ Two methods register widgets and retrieve an instance of the appropriate
  14427. widget for a given node in the device configuration model.
  14428. @<Device configuration members@>=
  14429. void registerDeviceConfigurationWidget(QString driver, QMetaObject widget);
  14430. QWidget* deviceConfigurationWidget(DeviceTreeModel *model,
  14431. const QModelIndex &index);
  14432. @ Registration is a simple wrapper around the underlying |QHash|.
  14433. @<Application Implementation@>=
  14434. void Application::registerDeviceConfigurationWidget(QString driver,
  14435. QMetaObject widget)
  14436. {
  14437. deviceConfigurationWidgets.insert(driver, widget);
  14438. }
  14439. @ Obtaining the configuration widget for a given node involves looking up the
  14440. reference element, extracting the driver string, looking up the associated
  14441. meta-object, and returning a new instance of that object.
  14442. As there is no concept of an invalid |QMetaObject| we default to the static
  14443. meta-object for a |QWidget| if a widget for the specified driver string is not
  14444. registered and check for this prior to creating a new instance of the
  14445. configuration widget.
  14446. @<Application Implementation@>=
  14447. QWidget* Application::deviceConfigurationWidget(DeviceTreeModel *model,
  14448. const QModelIndex &index)
  14449. {
  14450. QVariant nodeReference = index.data(Qt::UserRole);
  14451. QDomElement referenceElement = model->referenceElement(
  14452. model->data(index, Qt::UserRole).toString());
  14453. QMetaObject metaObject =
  14454. deviceConfigurationWidgets.value(referenceElement.attribute("driver"),
  14455. QWidget::staticMetaObject);
  14456. QWidget *editor;
  14457. if(metaObject.className() == QWidget::staticMetaObject.className())
  14458. {
  14459. editor = NULL;
  14460. }
  14461. else
  14462. {
  14463. editor = qobject_cast<QWidget *>(
  14464. metaObject.newInstance(Q_ARG(DeviceTreeModel *, model),
  14465. Q_ARG(QModelIndex, index)));
  14466. }
  14467. return editor;
  14468. }
  14469. @ Every node type should have an associated editor and the editors for nodes
  14470. which can have child nodes should be able to handle creating these child nodes.
  14471. This leaves the problem of creating the top level nodes. For this we must have
  14472. a way to register three key pieces of information: the text which should appear
  14473. for selecting a new top level node to add to the configuration, the default
  14474. name for a node of that type, and the registered driver string associated with
  14475. that node type. The most likely use for this information is in constructing a
  14476. menu. |QAction| seems like a good fit, but this cannot pass all of the
  14477. required information. Part of the chosen solution is a |QAction| subclass
  14478. which takes all three pieces of information and provides a new signal to
  14479. supply the information needed to add a new top level node.
  14480. @<Class declarations@>=
  14481. class NodeInserter : public QAction@/
  14482. {@/
  14483. @[Q_OBJECT@]@;
  14484. public:@/
  14485. NodeInserter(const QString &title, const QString &name,
  14486. const QString &driver, QObject *parent = NULL);
  14487. signals:@/
  14488. void triggered(QString name, QString driver);
  14489. @[private slots@]:@/
  14490. void onTriggered();
  14491. private:@/
  14492. QString defaultNodeName;
  14493. QString driverString;
  14494. };
  14495. @ The constructor saves the information that will later be emitted and connects
  14496. the |triggered()| signal from |QAction| to a private slot which emits our new
  14497. |triggered()| signal.
  14498. @<NodeInserter implementation@>=
  14499. NodeInserter::NodeInserter(const QString &title, const QString &name,
  14500. const QString &driver, QObject *parent) :
  14501. QAction(title, parent), defaultNodeName(name), driverString(driver)
  14502. {
  14503. connect(this, SIGNAL(triggered()), this, SLOT(onTriggered()));
  14504. }
  14505. void NodeInserter::onTriggered()
  14506. {
  14507. emit triggered(defaultNodeName, driverString);
  14508. }
  14509. @ An interface for adding top level nodes to the device configuration needs to
  14510. be able to access a list of these actions so we make this available through the
  14511. |Application| instance. Once again, it would be better to split device
  14512. configuration registration data to a separate class and there should be
  14513. accessors around this.
  14514. Note that this terminology was introduced when it was assumed that device
  14515. configuration and logging view configuration would be separate. It is likely
  14516. that a future code cleanup will remove this in favor of handling the top level
  14517. of the device configuration hierarchy (under roaster specification) in the same
  14518. way that sub-nodes are handled.
  14519. @<Device configuration members@>=
  14520. QList<NodeInserter *> topLevelNodeInserters;
  14521. @ With this done, we can now produce a window which allows someone to easily
  14522. edit the device configuration.
  14523. As of version 1.6 this class is no longer a window but just a |QWidget| which
  14524. is inserted into another more general settings window. The name of the class
  14525. should be changed in a future version to reflect this change.
  14526. @<Class declarations@>=
  14527. class DeviceConfigurationWindow : public QWidget
  14528. {
  14529. @[Q_OBJECT@]@;
  14530. public:@/
  14531. DeviceConfigurationWindow();
  14532. @[public slots@]:@/
  14533. void addDevice();
  14534. void removeNode();
  14535. void newSelection(const QModelIndex &index);
  14536. @[private slots@]:@/
  14537. void resizeColumn();
  14538. private:@/
  14539. QDomDocument document;
  14540. DeviceTreeModel *model;
  14541. QTreeView *view;
  14542. QScrollArea *configArea;
  14543. };
  14544. @ This window consists of two main panels separated by a splitter. The left
  14545. panel presents a tree view of the current device configuration and a set of
  14546. controls that allows someone to either add a new top level node to the
  14547. configuration or delete any node in the configuration along with all of its
  14548. child nodes.
  14549. The right panel provides a |QScrollArea|. When a node is selected from the tree
  14550. view, the appropriate configuration widget will be inserted into that area.
  14551. When a configuration widget adds a new node to the device model, the parent
  14552. node (which should be the currently selected node but the code does not assume
  14553. this) is expanded to show the new child node if it has not already been
  14554. expanded.
  14555. @<DeviceConfigurationWindow implementation@>=
  14556. DeviceConfigurationWindow::DeviceConfigurationWindow() : QWidget(NULL),
  14557. view(new QTreeView), configArea(new QScrollArea)
  14558. {
  14559. QSplitter *splitter = new QSplitter;
  14560. QWidget *leftWidget = new QWidget;
  14561. leftWidget->setMinimumWidth(200);
  14562. QVBoxLayout *left = new QVBoxLayout;
  14563. view->setAnimated(true);
  14564. view->setSelectionMode(QAbstractItemView::SingleSelection);
  14565. document = AppInstance->deviceConfiguration();
  14566. model = new DeviceTreeModel;
  14567. view->setModel(model);
  14568. view->setTextElideMode(Qt::ElideNone);
  14569. view->expandAll();
  14570. view->resizeColumnToContents(0);
  14571. connect(model, SIGNAL(modelReset()), view, SLOT(expandAll()));
  14572. QHBoxLayout *treeButtons = new QHBoxLayout;
  14573. QToolButton *addDeviceButton = new QToolButton;
  14574. addDeviceButton->setIcon(QIcon::fromTheme("list-add"));
  14575. addDeviceButton->setToolTip(tr("New Roaster"));
  14576. connect(addDeviceButton, SIGNAL(clicked()),
  14577. this, SLOT(addDevice()));
  14578. QToolButton *removeNodeButton = new QToolButton;
  14579. removeNodeButton->setIcon(QIcon::fromTheme("list-remove"));
  14580. removeNodeButton->setToolTip(tr("Delete Selection"));
  14581. connect(removeNodeButton, SIGNAL(clicked()), this, SLOT(removeNode()));
  14582. treeButtons->addWidget(addDeviceButton);
  14583. treeButtons->addWidget(removeNodeButton);
  14584. left->addWidget(view);
  14585. left->addLayout(treeButtons);
  14586. leftWidget->setLayout(left);
  14587. splitter->addWidget(leftWidget);
  14588. configArea->setMinimumWidth(580);
  14589. configArea->setMinimumHeight(460);
  14590. configArea->setWidgetResizable(true);
  14591. splitter->addWidget(configArea);
  14592. QVBoxLayout *centralLayout = new QVBoxLayout;
  14593. centralLayout->addWidget(splitter);
  14594. setLayout(centralLayout);
  14595. connect(view, SIGNAL(activated(QModelIndex)),
  14596. this, SLOT(newSelection(QModelIndex)));
  14597. connect(view, SIGNAL(clicked(QModelIndex)),
  14598. this, SLOT(newSelection(QModelIndex)));
  14599. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  14600. view, SLOT(expand(QModelIndex)));
  14601. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  14602. this, SLOT(resizeColumn()));
  14603. connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
  14604. this, SLOT(resizeColumn()));
  14605. }
  14606. @ Adding a new top level node to the model is just a matter of extracting the
  14607. required information from the signal requesting that addition.
  14608. @<DeviceConfigurationWindow implementation@>=
  14609. void DeviceConfigurationWindow::addDevice()
  14610. {
  14611. model->newNode(tr("New Roaster"), "roaster", QModelIndex());
  14612. }
  14613. @ Removing the currently selected node is also simple.
  14614. @<DeviceConfigurationWindow implementation@>=
  14615. void DeviceConfigurationWindow::removeNode()
  14616. {
  14617. QModelIndex index = view->currentIndex();
  14618. if(index.isValid())
  14619. {
  14620. int row = index.row();
  14621. QModelIndex parent = index.parent();
  14622. model->removeRow(row, parent);
  14623. }
  14624. }
  14625. @ Due to most of the required logic being implemented in
  14626. |Application::deviceConfigurationWidget()|, inserting the proper editor in the
  14627. right area is also trivial.
  14628. @<DeviceConfigurationWindow implementation@>=
  14629. void DeviceConfigurationWindow::newSelection(const QModelIndex &index)
  14630. {
  14631. QWidget *editor = AppInstance->deviceConfigurationWidget(model, index);
  14632. if(editor)
  14633. {
  14634. configArea->setWidget(editor);
  14635. editor->show();
  14636. }
  14637. }
  14638. @ As nodes are added deeper in the device hierarchy or as nodes obtain longer
  14639. names, the nodes names may be elided by default rather than indicate that the
  14640. view can be scrolled horizontally. There has been feedback that this behavior
  14641. is not preferred so instead as the model data changes we expand the column
  14642. instead.
  14643. @<DeviceConfigurationWindow implementation@>=
  14644. void DeviceConfigurationWindow::resizeColumn()
  14645. {
  14646. view->resizeColumnToContents(0);
  14647. }
  14648. @ At least for the initial testing of this feature it will be useful if we can
  14649. instantiate this from the host environment. For this we at least require a
  14650. constructor.
  14651. Now that this widget is available through a more general settings window it may
  14652. be better to remove direct access to this class from the host environment.
  14653. @<Function prototypes for scripting@>=
  14654. QScriptValue constructDeviceConfigurationWindow(QScriptContext *context,
  14655. QScriptEngine *engine);
  14656. @ The constructor is trivial.
  14657. @<Functions for scripting@>=
  14658. QScriptValue constructDeviceConfigurationWindow(QScriptContext *,
  14659. QScriptEngine *engine)
  14660. {
  14661. QScriptValue object = engine->newQObject(new DeviceConfigurationWindow);
  14662. return object;
  14663. }
  14664. @ Finally we inform the host environment of this constructor.
  14665. @<Set up the scripting engine@>=
  14666. constructor = engine->newFunction(constructDeviceConfigurationWindow);
  14667. value = engine->newQMetaObject(&DeviceConfigurationWindow::staticMetaObject,
  14668. constructor);
  14669. engine->globalObject().setProperty("DeviceConfigurationWindow", value);
  14670. @* A Base Class for Device Configuration Widgets.
  14671. \noindent There are certain operations that are very commonly required
  14672. among device configuration widgets. These common elements have been implemented
  14673. in a base class.
  14674. @<Class declarations@>=
  14675. class BasicDeviceConfigurationWidget : public QWidget
  14676. {
  14677. @[Q_OBJECT@]@;
  14678. public:@/
  14679. BasicDeviceConfigurationWidget(DeviceTreeModel *model,
  14680. const QModelIndex &index);
  14681. @[public slots@]:@/
  14682. void insertChildNode(const QString &name, const QString &driver);
  14683. void updateAttribute(const QString &name, const QString &value);
  14684. protected:@/
  14685. DeviceTreeModel *deviceModel;
  14686. QModelIndex currentNode;
  14687. };
  14688. @ The constructor just passes its arguments to a pair of protected data
  14689. members. These are commonly required in subclasses but need not be exposed
  14690. outside of this branch of the object hierarchy.
  14691. @<BasicDeviceConfigurationWidget implementation@>=
  14692. BasicDeviceConfigurationWidget::BasicDeviceConfigurationWidget(
  14693. DeviceTreeModel *model, const QModelIndex &index)
  14694. : QWidget(NULL), deviceModel(model), currentNode(index)
  14695. {
  14696. /* Nothing needs to be done here. */
  14697. }
  14698. @ The |updateAttribute()| method sets the value property of an attribute
  14699. element of a given name that is a child of the current node, creating the
  14700. element if it does not exist.
  14701. @<BasicDeviceConfigurationWidget implementation@>=
  14702. void BasicDeviceConfigurationWidget::updateAttribute(const QString &name,
  14703. const QString &value)
  14704. {
  14705. QDomElement referenceElement = deviceModel->referenceElement(
  14706. deviceModel->data(currentNode, Qt::UserRole).toString());
  14707. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14708. QDomElement node;
  14709. bool found = @[false@];
  14710. for(int i = 0; i < configData.size(); i++)
  14711. {
  14712. node = configData.at(i).toElement();
  14713. if(node.attribute("name") == name)
  14714. {
  14715. node.setAttribute("value", value);
  14716. found = @[true@];
  14717. break;
  14718. }
  14719. }
  14720. if(!found)
  14721. {
  14722. node = AppInstance->deviceConfiguration().createElement("attribute");
  14723. node.setAttribute("name", name);
  14724. node.setAttribute("value", value);
  14725. referenceElement.appendChild(node);
  14726. }
  14727. AppInstance->saveDeviceConfiguration();
  14728. }
  14729. @ The |insertChildNode()| method constructs a new node with the specified name
  14730. and driver as a child of the current node. Node insertion is a generic
  14731. operation that does not require any knowledge of the configuration options that
  14732. will be presented in that node.
  14733. @<BasicDeviceConfigurationWidget implementation@>=
  14734. void BasicDeviceConfigurationWidget::insertChildNode(const QString &name,
  14735. const QString &driver)
  14736. {
  14737. deviceModel->newNode(name, driver, currentNode);
  14738. }
  14739. @** Configuration of Top Level Roaster Nodes.
  14740. \noindent The first configuration widget required is one for defining a coffee
  14741. roaster. This stores the identification number that will be used for machine
  14742. references in the database and also provides controls for adding all of the
  14743. required child nodes for hardware and configurable elements of the logging
  14744. window that may vary from one machine to the next.
  14745. All of the configuration widgets follow a similar pattern. One important detail
  14746. to note is that these configuration widgets are instantiated through Qt'@q'@>s
  14747. meta-object system. All of these constructors take a |DeviceTreeModel *| and a
  14748. |QModelIndex &| as arguments and they are marked as |Q_INVOKABLE|.
  14749. @<Class declarations@>=
  14750. class RoasterConfWidget : public BasicDeviceConfigurationWidget
  14751. {
  14752. @[Q_OBJECT@]@;
  14753. public:@/
  14754. @[Q_INVOKABLE@]@, RoasterConfWidget(DeviceTreeModel *model,
  14755. const QModelIndex &index);
  14756. @[private slots@]:@/
  14757. void updateRoasterId(int id);
  14758. void updateCapacityCheck(int value);
  14759. void updateCapacity(const QString &value);
  14760. void updateCapacityUnit(const QString &value);
  14761. };
  14762. @ Aside from the ID number used to identify the roaster in the database we also
  14763. need controls to add child nodes. In order to limit the number of options in
  14764. menus for adding child nodes, these are organized into groups that are
  14765. available through different controls.
  14766. @<RoasterConfWidget implementation@>=
  14767. RoasterConfWidget::RoasterConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14768. : BasicDeviceConfigurationWidget(model, index)
  14769. {
  14770. QVBoxLayout *layout = new QVBoxLayout;
  14771. QPushButton *addDeviceButton = new QPushButton(tr("Add Device"));
  14772. QMenu *deviceMenu = new QMenu;
  14773. NodeInserter *insertAction;
  14774. foreach(insertAction, AppInstance->topLevelNodeInserters)
  14775. {
  14776. connect(insertAction, SIGNAL(triggered(QString, QString)),
  14777. this, SLOT(insertChildNode(QString, QString)));
  14778. deviceMenu->addAction(insertAction);
  14779. }
  14780. addDeviceButton->setMenu(deviceMenu);
  14781. layout->addWidget(addDeviceButton);
  14782. QPushButton *addAnnotationControlButton = new QPushButton(tr("Add Annotation Control"));
  14783. QMenu *annotationMenu = new QMenu;
  14784. NodeInserter *basicButtonInserter = new NodeInserter(tr("Annotation Button"), tr("Annotation Button"), "annotationbutton");
  14785. NodeInserter *countingButtonInserter = new NodeInserter(tr("Counting Button"), tr("Counting Button"), "reconfigurablebutton");
  14786. NodeInserter *spinBoxInserter = new NodeInserter(tr("Numeric Entry"), tr("Numeric Entry"), "annotationspinbox");
  14787. NodeInserter *freeAnnotationInserter = new NodeInserter(tr("Free Text"),
  14788. tr("Free Text"),
  14789. "freeannotation");
  14790. annotationMenu->addAction(basicButtonInserter);
  14791. annotationMenu->addAction(countingButtonInserter);
  14792. annotationMenu->addAction(spinBoxInserter);
  14793. annotationMenu->addAction(freeAnnotationInserter);
  14794. connect(basicButtonInserter, SIGNAL(triggered(QString, QString)),
  14795. this, SLOT(insertChildNode(QString, QString)));
  14796. connect(countingButtonInserter, SIGNAL(triggered(QString, QString)),
  14797. this, SLOT(insertChildNode(QString, QString)));
  14798. connect(spinBoxInserter, SIGNAL(triggered(QString, QString)),
  14799. this, SLOT(insertChildNode(QString, QString)));
  14800. connect(freeAnnotationInserter, SIGNAL(triggered(QString, QString)),
  14801. this, SLOT(insertChildNode(QString, QString)));
  14802. @<Add annotation control node inserters@>@;
  14803. addAnnotationControlButton->setMenu(annotationMenu);
  14804. layout->addWidget(addAnnotationControlButton);
  14805. QPushButton *timersButton = new QPushButton(tr("Extra Timers"));
  14806. QMenu *timersMenu = new QMenu;
  14807. NodeInserter *coolingTimerInserter = new NodeInserter(tr("Cooling Timer"), tr("Cooling Timer"), "coolingtimer");
  14808. NodeInserter *rangeTimerInserter = new NodeInserter(tr("Range Timer"), tr("Range Timer"), "rangetimer");
  14809. NodeInserter *multirangeTimerInserter = new NodeInserter(tr("Multi-Range Timer"), tr("Multi-Range Timer"), "multirangetimer");
  14810. timersMenu->addAction(coolingTimerInserter);
  14811. timersMenu->addAction(rangeTimerInserter);
  14812. timersMenu->addAction(multirangeTimerInserter);
  14813. connect(coolingTimerInserter, SIGNAL(triggered(QString, QString)),
  14814. this, SLOT(insertChildNode(QString, QString)));
  14815. connect(rangeTimerInserter, SIGNAL(triggered(QString, QString)),
  14816. this, SLOT(insertChildNode(QString, QString)));
  14817. connect(multirangeTimerInserter, SIGNAL(triggered(QString, QString)),
  14818. this, SLOT(insertChildNode(QString, QString)));
  14819. timersButton->setMenu(timersMenu);
  14820. layout->addWidget(timersButton);
  14821. QPushButton *advancedButton = new QPushButton(tr("Advanced Features"));
  14822. QMenu *advancedMenu = new QMenu;
  14823. NodeInserter *linearsplineinserter = new NodeInserter(tr("Linear Spline Interpolated Series"), tr("Linear Spline Interpolated Series"), "linearspline");
  14824. advancedMenu->addAction(linearsplineinserter);
  14825. NodeInserter *translationinserter = new NodeInserter(tr("Profile Translation"), tr("Profile Translation"), "translation");
  14826. advancedMenu->addAction(translationinserter);
  14827. connect(linearsplineinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  14828. connect(translationinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  14829. @<Add node inserters to advanced features menu@>@;
  14830. advancedButton->setMenu(advancedMenu);
  14831. layout->addWidget(advancedButton);
  14832. QHBoxLayout *idLayout = new QHBoxLayout;
  14833. QLabel *idLabel = new QLabel(tr("Machine ID for database:"));
  14834. idLayout->addWidget(idLabel);
  14835. QSpinBox *id = new QSpinBox;
  14836. idLayout->addWidget(id);
  14837. idLayout->addStretch();
  14838. layout->addLayout(idLayout);
  14839. QHBoxLayout *capacityLayout = new QHBoxLayout;
  14840. QCheckBox *capacityCheckEnabled = new QCheckBox(tr("Maximum batch size:"));
  14841. QDoubleSpinBox *capacity = new QDoubleSpinBox;
  14842. capacity->setMinimum(0.0);
  14843. capacity->setDecimals(3);
  14844. capacity->setMaximum(999999.999);
  14845. QComboBox *capacityUnit = new QComboBox;
  14846. capacityUnit->addItem("g");
  14847. capacityUnit->addItem("Kg");
  14848. capacityUnit->addItem("oz");
  14849. capacityUnit->addItem("Lb");
  14850. capacityUnit->setCurrentIndex(3);
  14851. capacityLayout->addWidget(capacityCheckEnabled);
  14852. capacityLayout->addWidget(capacity);
  14853. capacityLayout->addWidget(capacityUnit);
  14854. capacityLayout->addStretch();
  14855. layout->addLayout(capacityLayout);
  14856. layout->addStretch();
  14857. @<Get device configuration data for current node@>@;
  14858. for(int i = 0; i < configData.size(); i++)
  14859. {
  14860. node = configData.at(i).toElement();
  14861. if(node.attribute("name") == "databaseid")
  14862. {
  14863. id->setValue(node.attribute("value").toInt());
  14864. }
  14865. else if(node.attribute("name") == "checkcapacity")
  14866. {
  14867. capacityCheckEnabled->setChecked(node.attribute("value") == "true");
  14868. }
  14869. else if(node.attribute("name") == "capacity")
  14870. {
  14871. capacity->setValue(node.attribute("value").toDouble());
  14872. }
  14873. else if(node.attribute("name") == "capacityunit")
  14874. {
  14875. capacityUnit->setCurrentIndex(capacityUnit->findText(node.attribute("value")));
  14876. }
  14877. }
  14878. updateRoasterId(id->value());
  14879. connect(id, SIGNAL(valueChanged(int)), this, SLOT(updateRoasterId(int)));
  14880. connect(capacityCheckEnabled, SIGNAL(stateChanged(int)), this, SLOT(updateCapacityCheck(int)));
  14881. connect(capacity, SIGNAL(valueChanged(QString)), this, SLOT(updateCapacity(QString)));
  14882. connect(capacityUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateCapacityUnit(QString)));
  14883. setLayout(layout);
  14884. }
  14885. @ Iterating over the configuration data associated with the current node is
  14886. required in nearly every configuration widget. The specifics of the loop
  14887. vary, but there is likely a better way to generalize that. Until then,
  14888. obtaining a |QDomNodeList| with the required data to iterate over has been
  14889. split off as its own chunk to reduce the risk of errors associated with typing
  14890. the same code many times.
  14891. @<Get device configuration data for current node@>=
  14892. QDomElement referenceElement =
  14893. model->referenceElement(model->data(index, Qt::UserRole).toString());
  14894. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14895. QDomElement node;
  14896. @ We need to propagate changes to the configuration fields to the device
  14897. configuration document. The |updateAttribute()| method in the base class
  14898. makes this trivial.
  14899. @<RoasterConfWidget implementation@>=
  14900. void RoasterConfWidget::updateRoasterId(int id)
  14901. {
  14902. updateAttribute("databaseid", QString("%1").arg(id));
  14903. }
  14904. void RoasterConfWidget::updateCapacityCheck(int value)
  14905. {
  14906. updateAttribute("checkcapacity", value == Qt::Checked ? "true" : "false");
  14907. }
  14908. void RoasterConfWidget::updateCapacity(const QString &value)
  14909. {
  14910. updateAttribute("capacity", value);
  14911. }
  14912. void RoasterConfWidget::updateCapacityUnit(const QString &value)
  14913. {
  14914. updateAttribute("capacityunit", value);
  14915. }
  14916. @ Finally we must register the configuration widget so that it can be
  14917. instantiated at the appropriate time.
  14918. @<Register device configuration widgets@>=
  14919. app.registerDeviceConfigurationWidget("roaster", RoasterConfWidget::staticMetaObject);
  14920. @** Configuration for NI-DAQmx Base devices.
  14921. \noindent The primary concern in supporting hardware that communicates through
  14922. NI-DAQmx Base is in configurations using a single NI USB 9211 (for NI-DAQmx
  14923. Base 2.x) or NI USB 9211A (for NI-DAQmx Base 3.x), but if it is reasonable to
  14924. do so I'@q'@>d like to later add support for multiple device configurations and
  14925. limited support for other devices including the ability to use devices with
  14926. voltage inputs for non-temperature measurement data. The top priority, however,
  14927. is in continuing to support hardware that people are already using with Typica.
  14928. In order to more easily implement these future plans, device configuration is
  14929. handled with three configuration tiers. The top level configuration node
  14930. indicates that we are using NI-DAQmx Base. Here we can add a child node
  14931. representing either a NI USB 9211 or NI USB 9211A. From a configuration
  14932. perspective these are identical with the default node name as the only
  14933. difference. From the device configuration we can specify the device identifier
  14934. and add channels to the device. In the channel nodes we specify the
  14935. thermocouple type.
  14936. @<Class declarations@>=
  14937. class NiDaqMxBaseDriverConfWidget : public BasicDeviceConfigurationWidget
  14938. {
  14939. @[Q_OBJECT@]@;
  14940. public:@/
  14941. @[Q_INVOKABLE@]@, NiDaqMxBaseDriverConfWidget(DeviceTreeModel *model,@|
  14942. const QModelIndex &index);
  14943. };
  14944. @ There is very little to configure here so there isn'@q'@>t much for the
  14945. constructor to do. We do need to keep a reference to the node we are
  14946. configuring so that child nodes can later be added. At present, no real
  14947. configuration data other than the existence of the node is required so
  14948. there is no need to read any configuration data here.
  14949. @<NiDaqMxBaseDriverConfWidget implementation@>=
  14950. NiDaqMxBaseDriverConfWidget::NiDaqMxBaseDriverConfWidget(
  14951. DeviceTreeModel *model, const QModelIndex &index) :
  14952. BasicDeviceConfigurationWidget(model, index)
  14953. {
  14954. QHBoxLayout *layout = new QHBoxLayout;
  14955. QToolButton *addDeviceButton = new QToolButton;
  14956. addDeviceButton->setText(tr("Add Device"));
  14957. NodeInserter *add9211 = new NodeInserter("NI USB 9211", "NI USB 9211",
  14958. "nidaqmxbase9211series");
  14959. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  14960. "nidaqmxbase9211series");
  14961. connect(add9211, SIGNAL(triggered(QString, QString)),
  14962. this, SLOT(insertChildNode(QString, QString)));
  14963. connect(add9211a, SIGNAL(triggered(QString, QString)),
  14964. this, SLOT(insertChildNode(QString, QString)));
  14965. QMenu *deviceMenu = new QMenu;
  14966. deviceMenu->addAction(add9211);
  14967. deviceMenu->addAction(add9211a);
  14968. addDeviceButton->setMenu(deviceMenu);
  14969. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  14970. layout->addWidget(addDeviceButton);
  14971. setLayout(layout);
  14972. }
  14973. @ Both the NI USB 9211 and NI USB 9211A are identical from a configuration
  14974. perspective. The only difference is the version of NI-DAQmx Base required for
  14975. use. As the API does not provide a way of determining which version is
  14976. installed, ensuring that the appropriate software is installed without
  14977. conflicts is left as an exercise for the person attempting to use \pn{}.
  14978. @<Class declarations@>=
  14979. class NiDaqMxBase9211ConfWidget : public BasicDeviceConfigurationWidget
  14980. {
  14981. Q_OBJECT
  14982. public:
  14983. Q_INVOKABLE NiDaqMxBase9211ConfWidget(DeviceTreeModel *device,
  14984. const QModelIndex &index);
  14985. private slots:
  14986. void addChannel();
  14987. void updateDeviceId(const QString &newId);
  14988. };
  14989. @ There are two controls required in a configuration widget for this device.
  14990. The first is the device identifier (for example, "Dev1"), the second is a
  14991. button for adding channels to the device. On a generic device we would also
  14992. need to set the clock rate, but with this hardware it is possible to determine
  14993. the maximum clock rate from the channels defined.
  14994. @<NiDaqMxBase9211ConfWidget implementation@>=
  14995. NiDaqMxBase9211ConfWidget::NiDaqMxBase9211ConfWidget(DeviceTreeModel *model,
  14996. const QModelIndex &index)
  14997. : BasicDeviceConfigurationWidget(model, index)
  14998. {
  14999. QVBoxLayout *layout = new QVBoxLayout;
  15000. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  15001. QLabel *label = new QLabel(tr("Device ID:"));
  15002. QLineEdit *deviceId = new QLineEdit;
  15003. deviceIdLayout->addWidget(label);
  15004. deviceIdLayout->addWidget(deviceId);
  15005. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  15006. layout->addLayout(deviceIdLayout);
  15007. layout->addWidget(addChannelButton);
  15008. @<Get device configuration data for current node@>@;
  15009. for(int i = 0; i < configData.size(); i++)
  15010. {
  15011. node = configData.at(i).toElement();
  15012. if(node.attribute("name") == "deviceID")
  15013. {
  15014. deviceId->setText(node.attribute("value", "Dev1"));
  15015. break;
  15016. }
  15017. }
  15018. updateDeviceId(deviceId->text());
  15019. connect(addChannelButton, SIGNAL(clicked()),
  15020. this, SLOT(addChannel()));
  15021. connect(deviceId, SIGNAL(textEdited(QString)),
  15022. this, SLOT(updateDeviceId(QString)));
  15023. setLayout(layout);
  15024. }
  15025. @ Updating the attribute tag under the reference element associated with the
  15026. current node is handled in the base class so we just need to pass in the
  15027. appropriate name value pair.
  15028. @<NiDaqMxBase9211ConfWidget implementation@>=
  15029. void NiDaqMxBase9211ConfWidget::updateDeviceId(const QString &newId)
  15030. {
  15031. updateAttribute("deviceID", newId);
  15032. }
  15033. @ Adding channels is just like adding any other sort of node.
  15034. @<NiDaqMxBase9211ConfWidget implementation@>=
  15035. void NiDaqMxBase9211ConfWidget::addChannel()
  15036. {
  15037. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  15038. }
  15039. @ Finally, we need a configuration widget to handle our thermocouple channels.
  15040. Ordinarily we would need three pieces of information for each channel. First
  15041. there is the thermocouple channel. Previously this was left implied by the
  15042. order of requests for a new channel, but more flexible configuration options
  15043. become possible with a more explicit specification. Since this widget is device
  15044. specific, all of the options can be easily enumerated to match markings on the
  15045. device. Next is the thermocouple type. Many options are supported, but I would
  15046. like to ensure that the most commonly used choices are listed first. The other
  15047. piece of information that DAQmx or DAQmx Base require is the measurement unit.
  15048. As all of Typica'@q'@>s internal operations are in Fahrenheit there is no need to
  15049. make this configurable so long as everything else that can display temperature
  15050. measurements can perform the appropriate conversions.
  15051. Note that as there are no configuration differences between the various
  15052. device combinations using an NI 9211 module with regard to thermocouple channel
  15053. configuration, we can use this widget with all device combinations that make
  15054. use of such a module.
  15055. @<Class declarations@>=
  15056. class Ni9211TcConfWidget : public BasicDeviceConfigurationWidget
  15057. {@/
  15058. @[Q_OBJECT@]@;
  15059. public:@/
  15060. Q_INVOKABLE@,@, Ni9211TcConfWidget(DeviceTreeModel *device,
  15061. const QModelIndex &index);
  15062. @[private slots@]:@/
  15063. void updateThermocoupleType(const QString &type);
  15064. void updateColumnName(const QString &name);
  15065. void updateHidden(bool hidden);
  15066. };
  15067. @ This follows the same pattern of previous device configuration widgets. The
  15068. constructor provides the required configuration controls and slot methods
  15069. catch configuration changes and update the underlying XML document
  15070. appropriately.
  15071. @<Ni9211TcConfWidget implementation@>=
  15072. Ni9211TcConfWidget::Ni9211TcConfWidget(DeviceTreeModel *model,
  15073. const QModelIndex &index) :
  15074. BasicDeviceConfigurationWidget(model, index)
  15075. {
  15076. QFormLayout *layout = new QFormLayout;
  15077. QLineEdit *columnName = new QLineEdit;
  15078. layout->addRow(tr("Column Name:"), columnName);
  15079. QComboBox *typeSelector = new QComboBox;
  15080. typeSelector->addItem("J");
  15081. typeSelector->addItem("K");
  15082. typeSelector->addItem("T");
  15083. typeSelector->addItem("B");
  15084. typeSelector->addItem("E");
  15085. typeSelector->addItem("N");
  15086. typeSelector->addItem("R");
  15087. typeSelector->addItem("S");
  15088. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  15089. QCheckBox *hideSeries = new QCheckBox("Hide this channel");
  15090. layout->addRow(hideSeries);
  15091. setLayout(layout);
  15092. @<Get device configuration data for current node@>@;
  15093. for(int i = 0; i < configData.size(); i++)
  15094. {
  15095. node = configData.at(i).toElement();
  15096. if(node.attribute("name") == "type")
  15097. {
  15098. typeSelector->setCurrentIndex(
  15099. typeSelector->findText(node.attribute("value")));
  15100. }
  15101. else if(node.attribute("name") == "columnname")
  15102. {
  15103. columnName->setText(node.attribute("value"));
  15104. }
  15105. else if(node.attribute("name") == "hidden")
  15106. {
  15107. hideSeries->setChecked(node.attribute("value") == "true");
  15108. }
  15109. }
  15110. updateThermocoupleType(typeSelector->currentText());
  15111. updateColumnName(columnName->text());
  15112. updateHidden(hideSeries->isChecked());
  15113. connect(typeSelector, SIGNAL(currentIndexChanged(QString)),
  15114. this, SLOT(updateThermocoupleType(QString)));
  15115. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  15116. connect(hideSeries, SIGNAL(toggled(bool)), this, SLOT(updateHidden(bool)));
  15117. }
  15118. @ Two slots are used to pass configuration changes back to the underlying XML
  15119. representation.
  15120. @<Ni9211TcConfWidget implementation@>=
  15121. void Ni9211TcConfWidget::updateThermocoupleType(const QString &type)
  15122. {
  15123. updateAttribute("type", type);
  15124. }
  15125. void Ni9211TcConfWidget::updateColumnName(const QString &name)
  15126. {
  15127. updateAttribute("columnname", name);
  15128. }
  15129. void Ni9211TcConfWidget::updateHidden(bool hidden)
  15130. {
  15131. updateAttribute("hidden", hidden ? "true" : "false");
  15132. }
  15133. @ These three widgets need to be registered so the configuration widget can
  15134. instantiate them when the nodes are selected.
  15135. @<Register device configuration widgets@>=
  15136. app.registerDeviceConfigurationWidget("nidaqmxbase",
  15137. NiDaqMxBaseDriverConfWidget::staticMetaObject);
  15138. app.registerDeviceConfigurationWidget("nidaqmxbase9211series",
  15139. NiDaqMxBase9211ConfWidget::staticMetaObject);
  15140. app.registerDeviceConfigurationWidget("ni9211seriestc",
  15141. Ni9211TcConfWidget::staticMetaObject);
  15142. @ Furthermore, we should create the NodeInserter objects for adding top level
  15143. nodes to the configuration. Preferably we would only allow top level nodes to
  15144. be inserted when all prerequisite software is available.
  15145. @<Register top level device configuration nodes@>=
  15146. NodeInserter *inserter = new NodeInserter(tr("NI DAQmx Base Device"),
  15147. tr("NI DAQmx Base"),
  15148. "nidaqmxbase", NULL);
  15149. topLevelNodeInserters.append(inserter);
  15150. @** Configuration of NI-DAQmx devices.
  15151. \noindent The other main class of hardware currently supported in Typica is a
  15152. small set of devices that require NI-DAQmx. This includes a few combinations of
  15153. the NI 9211 in different carriers and the NI USB TC01. Additional hardware may
  15154. be added to this set in the future.
  15155. The approach here is very similar to the approach used to configure NI-DAQmx
  15156. Base devices, starting with a widget for adding child device nodes.
  15157. @<Class declarations@>=
  15158. class NiDaqMxDriverConfWidget : public BasicDeviceConfigurationWidget
  15159. {
  15160. @[Q_OBJECT@]@;
  15161. public:
  15162. @[Q_INVOKABLE@]@, NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  15163. const QModelIndex &index);
  15164. };
  15165. @ Under our driver node we want to have the ability to insert device specific
  15166. child nodes.
  15167. @<NiDaqMxDriverConfWidget implementation@>=
  15168. NiDaqMxDriverConfWidget::NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  15169. const QModelIndex &index)
  15170. : BasicDeviceConfigurationWidget(model, index)
  15171. {
  15172. QHBoxLayout *layout = new QHBoxLayout;
  15173. QToolButton *addDeviceButton = new QToolButton;
  15174. addDeviceButton->setText(tr("Add Device"));
  15175. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  15176. "nidaqmx9211series");
  15177. NodeInserter *addtc01 = new NodeInserter("NI USB TC01", "NI USB TC01",
  15178. "nidaqmxtc01");
  15179. connect(add9211a, SIGNAL(triggered(QString, QString)),
  15180. this, SLOT(insertChildNode(QString, QString)));
  15181. connect(addtc01, SIGNAL(triggered(QString, QString)),
  15182. this, SLOT(insertChildNode(QString, QString)));
  15183. QMenu *deviceMenu = new QMenu;
  15184. deviceMenu->addAction(add9211a);
  15185. deviceMenu->addAction(addtc01);
  15186. addDeviceButton->setMenu(deviceMenu);
  15187. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  15188. layout->addWidget(addDeviceButton);
  15189. setLayout(layout);
  15190. }
  15191. @ Devices based on the 9211 module are essentially the same aside from device
  15192. naming convention. Configuring these is very similar to configuring similar
  15193. devices when using NI-DAQmx Base.
  15194. @<Class declarations@>=
  15195. class NiDaqMx9211ConfWidget : public BasicDeviceConfigurationWidget
  15196. {
  15197. @[Q_OBJECT@]@;
  15198. public:@/
  15199. @[Q_INVOKABLE@]@, NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  15200. const QModelIndex &index);
  15201. @[private slots@]:@/
  15202. void addChannel();
  15203. void updateDeviceId(const QString &newId);
  15204. };
  15205. @ Implementation is essentially identical to the NI-DAQmx Base class. It is
  15206. likely that there will be differences if this is ever extended to support
  15207. automatic detection of connected hardware. While NI-DAQmx Base does not
  15208. provide a way to query device identifiers, it uses a consistent naming scheme
  15209. by which device identifiers can be discovered. While NI-DAQmx lacks the same
  15210. consistency in device identifiers, it does provide a way to query that
  15211. information.
  15212. @<NiDaqMx9211ConfWidget implementation@>=
  15213. NiDaqMx9211ConfWidget::NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  15214. const QModelIndex &index)
  15215. : BasicDeviceConfigurationWidget(model, index)
  15216. {
  15217. QVBoxLayout *layout = new QVBoxLayout;
  15218. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  15219. QLabel *label = new QLabel(tr("Device ID:"));
  15220. QLineEdit *deviceId = new QLineEdit;
  15221. deviceIdLayout->addWidget(label);
  15222. deviceIdLayout->addWidget(deviceId);
  15223. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  15224. layout->addLayout(deviceIdLayout);
  15225. layout->addWidget(addChannelButton);
  15226. @<Get device configuration data for current node@>@;
  15227. for(int i = 0; i < configData.size(); i++)
  15228. {
  15229. node = configData.at(i).toElement();
  15230. if(node.attribute("name") == "deviceID")
  15231. {
  15232. deviceId->setText(node.attribute("value","Dev1"));
  15233. break;
  15234. }
  15235. }
  15236. updateDeviceId(deviceId->text());
  15237. connect(addChannelButton, SIGNAL(clicked()), this, SLOT(addChannel()));
  15238. connect(deviceId, SIGNAL(textEdited(QString)),
  15239. this, SLOT(updateDeviceId(QString)));
  15240. setLayout(layout);
  15241. }
  15242. void NiDaqMx9211ConfWidget::updateDeviceId(const QString &newId)
  15243. {
  15244. updateAttribute("deviceID", newId);
  15245. }
  15246. void NiDaqMx9211ConfWidget::addChannel()
  15247. {
  15248. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  15249. }
  15250. @ There is no need to create a configuration widget specific to the 9211 module
  15251. used in NI-DAQmx. The widget already used for NI-DAQmx Base can be used without
  15252. modification.
  15253. Configuring Typica for use with the NI USB-TC01 can be slightly simplified as
  15254. the device only has a single thermocouple channel. We can configure this without
  15255. requiring another node.
  15256. @<Class declarations@>=
  15257. class NiDaqMxTc01ConfWidget : public BasicDeviceConfigurationWidget
  15258. {
  15259. @[Q_OBJECT@]@;
  15260. public:@/
  15261. @[Q_INVOKABLE@]@, NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  15262. const QModelIndex &index);
  15263. @[private slots@]:@/
  15264. void updateDeviceId(const QString &newId);
  15265. void updateThermocoupleType(const QString &type);
  15266. void updateColumnName(const QString &name);
  15267. void updateHidden(bool hidden);
  15268. };
  15269. @ The implementation is similar to the other configuration widgets.
  15270. @<NiDaqMxTc01ConfWidget implementation@>=
  15271. NiDaqMxTc01ConfWidget::NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  15272. const QModelIndex &index)
  15273. : BasicDeviceConfigurationWidget(model, index)
  15274. {
  15275. QFormLayout *layout = new QFormLayout;
  15276. QLineEdit *deviceId = new QLineEdit;
  15277. layout->addRow(tr("Device ID:"), deviceId);
  15278. QLineEdit *columnName = new QLineEdit;
  15279. layout->addRow(tr("Column Name:"), columnName);
  15280. QComboBox *typeSelector = new QComboBox;
  15281. typeSelector->addItem("J");
  15282. typeSelector->addItem("K");
  15283. typeSelector->addItem("T");
  15284. typeSelector->addItem("B");
  15285. typeSelector->addItem("E");
  15286. typeSelector->addItem("N");
  15287. typeSelector->addItem("R");
  15288. typeSelector->addItem("S");
  15289. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  15290. QCheckBox *hideSeries = new QCheckBox(tr("Hide this channel"));
  15291. layout->addRow(hideSeries);
  15292. @<Get device configuration data for current node@>@;
  15293. for(int i = 0; i < configData.size(); i++)
  15294. {
  15295. node = configData.at(i).toElement();
  15296. if(node.attribute("name") == "deviceID")
  15297. {
  15298. deviceId->setText(node.attribute("value"));
  15299. }
  15300. else if(node.attribute("name") == "type")
  15301. {
  15302. typeSelector->setCurrentIndex(typeSelector->findText(node.attribute("value")));
  15303. }
  15304. else if(node.attribute("name") == "columnname")
  15305. {
  15306. columnName->setText(node.attribute("value"));
  15307. }
  15308. else if(node.attribute("name") == "hidden")
  15309. {
  15310. hideSeries->setChecked(node.attribute("value") == "true");
  15311. }
  15312. }
  15313. updateDeviceId(deviceId->text());
  15314. updateThermocoupleType(typeSelector->currentText());
  15315. updateColumnName(columnName->text());
  15316. updateHidden(hideSeries->isChecked());
  15317. connect(deviceId, SIGNAL(textEdited(QString)), this, SLOT(updateDeviceId(QString)));
  15318. connect(typeSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateThermocoupleType(QString)));
  15319. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  15320. setLayout(layout);
  15321. connect(hideSeries, SIGNAL(toggled(bool)), this, SLOT(updateHidden(bool)));
  15322. }
  15323. void NiDaqMxTc01ConfWidget::updateDeviceId(const QString &newId)
  15324. {
  15325. updateAttribute("deviceID", newId);
  15326. }
  15327. void NiDaqMxTc01ConfWidget::updateThermocoupleType(const QString &type)
  15328. {
  15329. updateAttribute("type", type);
  15330. }
  15331. void NiDaqMxTc01ConfWidget::updateColumnName(const QString &name)
  15332. {
  15333. updateAttribute("columnname", name);
  15334. }
  15335. void NiDaqMxTc01ConfWidget::updateHidden(bool hidden)
  15336. {
  15337. updateAttribute("hidden", hidden ? "true" : "false");
  15338. }
  15339. @ These configuration widgets need to be registered so they can be instantiated
  15340. in response to node selections.
  15341. @<Register device configuration widgets@>=
  15342. app.registerDeviceConfigurationWidget("nidaqmx", NiDaqMxDriverConfWidget::staticMetaObject);
  15343. app.registerDeviceConfigurationWidget("nidaqmx9211series", NiDaqMx9211ConfWidget::staticMetaObject);
  15344. app.registerDeviceConfigurationWidget("nidaqmxtc01", NiDaqMxTc01ConfWidget::staticMetaObject);
  15345. @ A |NodeInserter| for the driver configuration widget is also needed. Note that
  15346. at present NI DAQmx is only available on Windows so we do not bother to show
  15347. the option on other platforms. It would be generally preferable to replace this
  15348. with a check at runtime to determine if the required library exists. That could
  15349. be done with anything that requires third party installed code, leaving by
  15350. default only those options which have no external dependencies.
  15351. @<Register top level device configuration nodes@>=
  15352. #ifdef Q_OS_WIN32
  15353. inserter = new NodeInserter(tr("NI DAQmx Device"), tr("NI DAQmx"), "nidaqmx", NULL);
  15354. topLevelNodeInserters.append(inserter);
  15355. #endif
  15356. @** Configuration of Serial Port Devices.
  15357. \noindent It is possible to communicate with a number of devices through a
  15358. serial port. To do this, the appropriate settings for opening the port are
  15359. required and the communications protocol understood by the device must be
  15360. known. Serial port communications are provided by QextSerialPort. That
  15361. project was released under the MIT license.\nfnote{See the license text for
  15362. more information.} Additional headers are required.
  15363. @<Header files to include@>=
  15364. #include "qextserialport.h"
  15365. #include "qextserialenumerator.h"
  15366. @ Some custom widgets are provided which allow selecting the relevant
  15367. connection options from combo boxes. First there is a widget for selecting
  15368. the desired serial port. The drop down is pre-populated with any serial ports
  15369. that could be automatically detected, but the field can also be edited to
  15370. other values as may be required if the hardware is not connected during
  15371. configuration.
  15372. @<Class declarations@>=
  15373. class PortSelector : public QComboBox
  15374. {
  15375. Q_OBJECT
  15376. public:
  15377. PortSelector(QWidget *parent = NULL);
  15378. private slots:
  15379. void addDevice(QextPortInfo port);
  15380. private:
  15381. QextSerialEnumerator *lister;
  15382. };
  15383. @ The implementation is trivial.
  15384. @<PortSelector implementation@>=
  15385. PortSelector::PortSelector(QWidget *parent) : QComboBox(parent),
  15386. lister(new QextSerialEnumerator)
  15387. {
  15388. QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
  15389. QextPortInfo port;
  15390. foreach(port, ports)
  15391. {
  15392. #ifdef Q_OS_WIN32
  15393. addItem(port.portName);
  15394. #else
  15395. addItem(port.physName);
  15396. #endif
  15397. }
  15398. lister->setUpNotifications();
  15399. connect(lister, SIGNAL(deviceDiscovered(QextPortInfo)),
  15400. this, SLOT(addDevice(QextPortInfo)));
  15401. setEditable(true);
  15402. }
  15403. void PortSelector::addDevice(QextPortInfo port)
  15404. {
  15405. addItem(port.portName);
  15406. }
  15407. @ Next is a widget which allows selecting the baud rate. Only rates supported
  15408. by the current operating system are available to select.
  15409. A later version of QextSerialPort than is used by \pn{} provides a helper
  15410. class which can be used more conveniently to create this sort of control. As
  15411. this is not yet available to \pn{}, we instead copy the |enum| specifying
  15412. the appropriate values into the class and use Qt'@q'@>s meta-object system to
  15413. populate the combo box based on the values in that |enum|.
  15414. @<Class declarations@>=
  15415. class BaudSelector : public QComboBox
  15416. {
  15417. Q_OBJECT
  15418. Q_ENUMS(BaudRateType)
  15419. public:
  15420. BaudSelector(QWidget *parent = NULL);
  15421. enum BaudRateType
  15422. {
  15423. #if defined(Q_OS_UNIX) || defined(qdoc)
  15424. BAUD50 = 50, //POSIX ONLY
  15425. BAUD75 = 75, //POSIX ONLY
  15426. BAUD134 = 134, //POSIX ONLY
  15427. BAUD150 = 150, //POSIX ONLY
  15428. BAUD200 = 200, //POSIX ONLY
  15429. BAUD1800 = 1800, //POSIX ONLY
  15430. #if defined(B76800) || defined(qdoc)
  15431. BAUD76800 = 76800, //POSIX ONLY
  15432. #endif
  15433. #if (defined(B230400) && defined(B4000000)) || defined(qdoc)
  15434. BAUD230400 = 230400, //POSIX ONLY
  15435. BAUD460800 = 460800, //POSIX ONLY
  15436. BAUD500000 = 500000, //POSIX ONLY
  15437. BAUD576000 = 576000, //POSIX ONLY
  15438. BAUD921600 = 921600, //POSIX ONLY
  15439. BAUD1000000 = 1000000, //POSIX ONLY
  15440. BAUD1152000 = 1152000, //POSIX ONLY
  15441. BAUD1500000 = 1500000, //POSIX ONLY
  15442. BAUD2000000 = 2000000, //POSIX ONLY
  15443. BAUD2500000 = 2500000, //POSIX ONLY
  15444. BAUD3000000 = 3000000, //POSIX ONLY
  15445. BAUD3500000 = 3500000, //POSIX ONLY
  15446. BAUD4000000 = 4000000, //POSIX ONLY
  15447. #endif
  15448. #endif
  15449. #if defined(Q_OS_WIN) || defined(qdoc)
  15450. BAUD14400 = 14400, //WINDOWS ONLY
  15451. BAUD56000 = 56000, //WINDOWS ONLY
  15452. BAUD128000 = 128000, //WINDOWS ONLY
  15453. BAUD256000 = 256000, //WINDOWS ONLY
  15454. #endif
  15455. BAUD110 = 110,
  15456. BAUD300 = 300,
  15457. BAUD600 = 600,
  15458. BAUD1200 = 1200,
  15459. BAUD2400 = 2400,
  15460. BAUD4800 = 4800,
  15461. BAUD9600 = 9600,
  15462. BAUD19200 = 19200,
  15463. BAUD38400 = 38400,
  15464. BAUD57600 = 57600,
  15465. BAUD115200 = 115200
  15466. };
  15467. };
  15468. @ As the |enum| values are identical to the baud rates represented, we only
  15469. the numeric values, ignoring the names which are rather ugly.
  15470. @<BaudSelector implementation@>=
  15471. BaudSelector::BaudSelector(QWidget *parent) : QComboBox(parent)
  15472. {
  15473. QMetaObject meta = BaudSelector::staticMetaObject;
  15474. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("BaudRateType"));
  15475. for(int i = 0; i < type.keyCount(); i++)
  15476. {
  15477. addItem(QString("%1").arg(type.value(i)));
  15478. }
  15479. }
  15480. @ This same technique is used in a widget for selecting parity.
  15481. @<Class declarations@>=
  15482. class ParitySelector : public QComboBox
  15483. {
  15484. Q_OBJECT
  15485. Q_ENUMS(ParityType)
  15486. public:
  15487. ParitySelector(QWidget *parent = NULL);
  15488. enum ParityType
  15489. {
  15490. PAR_NONE,
  15491. PAR_ODD,
  15492. PAR_EVEN,
  15493. #if defined(Q_OS_WIN) || defined(qdoc)
  15494. PAR_MARK, //WINDOWS ONLY
  15495. #endif
  15496. PAR_SPACE
  15497. };
  15498. };
  15499. @ Implementation is similar to |BaudSelector| but as the values have no
  15500. apparent relation to what is represented we present the value names, placing
  15501. the corresponding value in the user data space associated with each entry.
  15502. The names here are ugly and not amenable to localization so this approach
  15503. should be reconsidered later.
  15504. @<ParitySelector implementation@>=
  15505. ParitySelector::ParitySelector(QWidget *parent) : QComboBox(parent)
  15506. {
  15507. QMetaObject meta = ParitySelector::staticMetaObject;
  15508. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("ParityType"));
  15509. for(int i = 0; i < type.keyCount(); i++)
  15510. {
  15511. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15512. }
  15513. }
  15514. @ Similarly, we have a widget for selecting a method for flow control.
  15515. @<Class declarations@>=
  15516. class FlowSelector : public QComboBox
  15517. {
  15518. @[Q_OBJECT@]@;
  15519. @[Q_ENUMS(FlowType)@]@;
  15520. public:@/
  15521. FlowSelector(QWidget *parent = NULL);
  15522. enum FlowType
  15523. {
  15524. FLOW_OFF,
  15525. FLOW_HARDWARE,
  15526. FLOW_XONXOFF
  15527. };
  15528. };
  15529. @ Implementation follows the same pattern as in |ParitySelector|.
  15530. @<FlowSelector implementation@>=
  15531. FlowSelector::FlowSelector(QWidget *parent) : QComboBox(parent)
  15532. {
  15533. QMetaObject meta = FlowSelector::staticMetaObject;
  15534. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("FlowType"));
  15535. for(int i = 0; i < type.keyCount(); i++)
  15536. {
  15537. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15538. }
  15539. }
  15540. @ We assume that the number of data bits will always be 8, though it may be
  15541. useful to later provide a control for selecting this for use with other devices
  15542. where this may not be assumed or for the sake of completion. This only leaves
  15543. specifying the number of stop bits.
  15544. @<Class declarations@>=
  15545. class StopSelector : public QComboBox
  15546. {
  15547. @[Q_OBJECT@]@;
  15548. @[Q_ENUMS(StopBitsType)@]@;
  15549. public:@/
  15550. StopSelector(QWidget *parent = NULL);
  15551. enum StopBitsType
  15552. {
  15553. STOP_1,
  15554. #if defined(Q_OS_WIN) || defined(qdoc)
  15555. STOP_1_5, //WINDOWS ONLY
  15556. #endif
  15557. STOP_2
  15558. };
  15559. };
  15560. @ Implementation should be familiar by now.
  15561. @<StopSelector implementation@>=
  15562. StopSelector::StopSelector(QWidget *parent) : QComboBox(parent)
  15563. {
  15564. QMetaObject meta = StopSelector::staticMetaObject;
  15565. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("StopBitsType"));
  15566. for(int i = 0; i < type.keyCount(); i++)
  15567. {
  15568. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15569. }
  15570. }
  15571. @** Configuration of Serial Devices Using Modbus RTU.
  15572. \noindent The following sections contain the details of older code related to
  15573. Modbus RTU support. While the various selector widgets are shared with the new
  15574. code, the configuration widgets and device interfaces are being replaced.
  15575. One protocol that is used across a broad class of devices is called
  15576. Modbus RTU. This protocol allows multiple devices to be chained together on a
  15577. two wire bus which can be connected to a single serial port. The communication
  15578. protocol involves a single message which is sent from a master device (in this
  15579. case the computer running Typica) to a slave device (the device we would like
  15580. to obtain information from) which is followed by a response message from the
  15581. slave to the master. After a brief wait the master can then send another
  15582. message to any slave on the bus and this process repeats. Every outgoing
  15583. message provides a station address to identify which slave on the bus should
  15584. respond, a function code to identify which of a broad class of operations has
  15585. been requested, the required data for the function specified, and a cyclic
  15586. redundancy check to validate the message.
  15587. @** A Spin Box with Hexadecimal Representation.
  15588. \noindent Common convention for communications documentation for devices that
  15589. use Modbus RTU is that relative addresses are specified in hexadecimal
  15590. representation. In order to simplify initial device configuration, it would be
  15591. best that input widgets both accept input in base 16 and display values as a
  15592. four digit hexadecimal value.
  15593. @<Class declarations@>=
  15594. class ShortHexSpinBox : public QSpinBox
  15595. {
  15596. @[Q_OBJECT@]@;
  15597. public:@/
  15598. ShortHexSpinBox(QWidget *parent = NULL);
  15599. virtual QValidator::State validate(QString &input, int &pos) const;@/
  15600. protected:@/
  15601. virtual int valueFromText(const QString &text) const;
  15602. virtual QString textFromValue(int value) const;@/
  15603. };
  15604. @ For this we can set some new defaults in the constructor and must override
  15605. three methods.
  15606. @<ShortHexSpinBox implementation@>=
  15607. ShortHexSpinBox::ShortHexSpinBox(QWidget *parent) : QSpinBox(parent)
  15608. {
  15609. setMinimum(0);
  15610. setMaximum(0xFFFF);
  15611. setPrefix("0x");
  15612. setMinimumWidth(65);
  15613. }
  15614. QValidator::State ShortHexSpinBox::validate(QString &input, int &) const
  15615. {
  15616. if(input.size() == 2)
  15617. {
  15618. return QValidator::Intermediate;
  15619. }
  15620. bool okay;
  15621. input.toInt(&okay, 16);
  15622. if(okay)
  15623. {
  15624. return QValidator::Acceptable;
  15625. }
  15626. return QValidator::Invalid;
  15627. }
  15628. int ShortHexSpinBox::valueFromText(const QString &text) const
  15629. {
  15630. return text.toInt(NULL, 16);
  15631. }
  15632. QString ShortHexSpinBox::textFromValue(int value) const
  15633. {
  15634. QString retval;
  15635. retval.setNum(value, 16);
  15636. while(retval.size() < 4)
  15637. {
  15638. retval.prepend("0");
  15639. }
  15640. return retval.toUpper();
  15641. }
  15642. @** Configuration Widgets for Modbus RTU Devices.
  15643. \noindent While the top level configuration widgets seen so far have not had
  15644. any configuration details beyond the ability to add devices under the driver,
  15645. in the case of a serial port with Modbus RTU devices it is reasonable to
  15646. provide the connection details which will be shared by all devices on the bus.
  15647. @<Class declarations@>=
  15648. class ModbusRtuPortConfWidget : public BasicDeviceConfigurationWidget
  15649. {
  15650. @[Q_OBJECT@]@;
  15651. public:
  15652. @[Q_INVOKABLE@]@, ModbusRtuPortConfWidget(DeviceTreeModel *model,
  15653. const QModelIndex &index);
  15654. @[private slots@]:@/
  15655. void updatePort(const QString &newPort);
  15656. void updateBaudRate(const QString &newRate);
  15657. void updateParity(const QString &newParity);
  15658. void updateFlowControl(const QString &newFlow);
  15659. void updateStopBits(const QString &newStopBits);
  15660. };
  15661. @ Aside from the extra information compared with other configuration widgets
  15662. previously described, there is nothing surprising about the implementation.
  15663. @<ModbusRtuPortConfWidget implementation@>=
  15664. ModbusRtuPortConfWidget::ModbusRtuPortConfWidget(DeviceTreeModel *model,
  15665. const QModelIndex &index)
  15666. : BasicDeviceConfigurationWidget(model, index)
  15667. {
  15668. QFormLayout *layout = new QFormLayout;
  15669. QToolButton *addDeviceButton = new QToolButton;
  15670. addDeviceButton->setText(tr("Add Device"));
  15671. NodeInserter *addModbusRtuDevice = new NodeInserter("Modbus RTU Device",
  15672. "Modbus RTU Device",
  15673. "modbusrtudevice");
  15674. connect(addModbusRtuDevice, SIGNAL(triggered(QString, QString)),
  15675. this, SLOT(insertChildNode(QString, QString)));
  15676. QMenu *deviceMenu = new QMenu;
  15677. deviceMenu->addAction(addModbusRtuDevice);
  15678. addDeviceButton->setMenu(deviceMenu);
  15679. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  15680. layout->addRow(QString(), addDeviceButton);
  15681. PortSelector *port = new PortSelector;
  15682. layout->addRow(tr("Port:"), port);
  15683. connect(port, SIGNAL(currentIndexChanged(QString)),
  15684. this, SLOT(updatePort(QString)));
  15685. connect(port, SIGNAL(editTextChanged(QString)),
  15686. this, SLOT(updatePort(QString)));
  15687. BaudSelector *rate = new BaudSelector;
  15688. layout->addRow(tr("Baud:"), rate);
  15689. connect(rate, SIGNAL(currentIndexChanged(QString)),
  15690. this, SLOT(updateBaudRate(QString)));
  15691. ParitySelector *parity = new ParitySelector;
  15692. layout->addRow(tr("Parity:"), parity);
  15693. connect(parity, SIGNAL(currentIndexChanged(QString)),
  15694. this, SLOT(updateParity(QString)));
  15695. FlowSelector *flow = new FlowSelector;
  15696. layout->addRow(tr("Flow Control:"), flow);
  15697. connect(flow, SIGNAL(currentIndexChanged(QString)),
  15698. this, SLOT(updateFlowControl(QString)));
  15699. StopSelector *stop = new StopSelector;
  15700. layout->addRow(tr("Stop Bits:"), stop);
  15701. connect(stop, SIGNAL(currentIndexChanged(QString)),
  15702. this, SLOT(updateStopBits(QString)));
  15703. @<Get device configuration data for current node@>@;
  15704. for(int i = 0; i < configData.size(); i++)
  15705. {
  15706. node = configData.at(i).toElement();
  15707. if(node.attribute("name") == "port")
  15708. {
  15709. int j = port->findText(node.attribute("value"));
  15710. if(j >= 0)
  15711. {
  15712. port->setCurrentIndex(j);
  15713. }
  15714. else
  15715. {
  15716. port->insertItem(0, node.attribute("value"));
  15717. port->setCurrentIndex(0);
  15718. }
  15719. }
  15720. else if(node.attribute("name") == "baudrate")
  15721. {
  15722. rate->setCurrentIndex(rate->findText(node.attribute("value")));
  15723. }
  15724. else if(node.attribute("name") == "parity")
  15725. {
  15726. parity->setCurrentIndex(parity->findText(node.attribute("value")));
  15727. }
  15728. else if(node.attribute("name") == "flowcontrol")
  15729. {
  15730. flow->setCurrentIndex(flow->findText(node.attribute("value")));
  15731. }
  15732. else if(node.attribute("name") == "stopbits")
  15733. {
  15734. stop->setCurrentIndex(stop->findText(node.attribute("value")));
  15735. }
  15736. }
  15737. updatePort(port->currentText());
  15738. updateBaudRate(rate->currentText());
  15739. updateParity(parity->currentText());
  15740. updateFlowControl(flow->currentText());
  15741. updateStopBits(stop->currentText());
  15742. setLayout(layout);
  15743. }
  15744. void ModbusRtuPortConfWidget::updatePort(const QString &newPort)
  15745. {
  15746. updateAttribute("port", newPort);
  15747. }
  15748. void ModbusRtuPortConfWidget::updateBaudRate(const QString &newRate)
  15749. {
  15750. updateAttribute("baudrate", newRate);
  15751. }
  15752. void ModbusRtuPortConfWidget::updateParity(const QString &newParity)
  15753. {
  15754. updateAttribute("parity", newParity);
  15755. }
  15756. void ModbusRtuPortConfWidget::updateFlowControl(const QString &newFlow)
  15757. {
  15758. updateAttribute("flowcontrol", newFlow);
  15759. }
  15760. void ModbusRtuPortConfWidget::updateStopBits(const QString &newStopBits)
  15761. {
  15762. updateAttribute("stopbits", newStopBits);
  15763. }
  15764. @ From here we need to provide a widget for configuring a particular device.
  15765. At a minimum this would require setting the station number to a value between
  15766. 0 and 255. Zero is typically the broadcast address which reaches all devices
  15767. on the bus and is not generally recommended for use except in particular
  15768. circumstances. There are, however, a number of settings that influence all of
  15769. the currently supported child nodes and these settings are in the device
  15770. configuration widget instead of requiring that information to be duplicated
  15771. across multiple child nodes.
  15772. The Modbus RTU protocol is very general in scope and leaves many of the
  15773. details of how to do certain things up to the manufacturer. For rudimentary
  15774. support of devices using this protocol, the documentation for several devices
  15775. was consulted and a test rig with one device was set up. There are a number of
  15776. assumptions made for this initial support and to better support additional
  15777. device classes it may become necessary to expand on what is provided initially.
  15778. The primary focus presently is on the use of PID controllers as temperature
  15779. indicators with the ability to modify a set value in the case where this is
  15780. used as a controller rather than just a display.
  15781. All of the devices studied prior to adding this support made use of scaled
  15782. integer representation. In order to correctly determine the measured process
  15783. value it is necessary to know the unit of the measurement and the position of
  15784. the decimal point. It is generally possible to query this information, however
  15785. it may be useful to provide a way to specify fixed values in the event that a
  15786. device exposes these details in a way that is incompatible with my assumptions.
  15787. @<Class declarations@>=
  15788. class ModbusRtuDeviceConfWidget : public BasicDeviceConfigurationWidget
  15789. {
  15790. @[Q_OBJECT@]@;
  15791. public:@/
  15792. @[Q_INVOKABLE@]@, ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  15793. const QModelIndex &index);
  15794. @[private slots@]:@/
  15795. void updateStationNumber(int newStation);
  15796. void updateFixedUnit(bool newFixed);
  15797. void updateFixedDecimal(bool newFixed);
  15798. void updateUnit(const QString &newUnit);
  15799. void updateUnitAddress(int newAddress);
  15800. void updateValueF(int newValue);
  15801. void updateValueC(int newValue);
  15802. void updatePrecisionAddress(int newAddress);
  15803. void updatePrecisionValue(int newValue);
  15804. private:@/
  15805. QStackedLayout *unitSpecificationLayout;
  15806. QStackedLayout *decimalSpecificationLayout;
  15807. };
  15808. @ This widget has a number of differences from previous configuration widgets.
  15809. Perhaps most significantly there are controls which do not provide a text based
  15810. signal on state change. We also set certain controls as disabled when the
  15811. provided values are not relevant to operations such as when switching between
  15812. fixed decimal position and looking up decimal position from the device. Aside
  15813. from these details the widget operates according to the same principles as the
  15814. other widgets already seen.
  15815. @<ModbusRtuDeviceConfWidget implementation@>=
  15816. ModbusRtuDeviceConfWidget::ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  15817. const QModelIndex &index)
  15818. : BasicDeviceConfigurationWidget(model, index),
  15819. unitSpecificationLayout(new QStackedLayout),
  15820. decimalSpecificationLayout(new QStackedLayout)
  15821. {
  15822. QVBoxLayout *layout = new QVBoxLayout;
  15823. QToolButton *addChannelButton = new QToolButton;
  15824. addChannelButton->setText(tr("Add Channel"));
  15825. NodeInserter *addTemperaturePV = new NodeInserter("Temperature Process Value",
  15826. "Temperature Process Value",
  15827. "modbustemperaturepv");
  15828. NodeInserter *addTemperatureSV = new NodeInserter("Temperature Set Value",
  15829. "Temperature Set Value",
  15830. "modbustemperaturesv");
  15831. connect(addTemperaturePV, SIGNAL(triggered(QString, QString)),
  15832. this, SLOT(insertChildNode(QString, QString)));
  15833. connect(addTemperatureSV, SIGNAL(triggered(QString, QString)),
  15834. this, SLOT(insertChildNode(QString, QString)));
  15835. QMenu *channelMenu = new QMenu;
  15836. channelMenu->addAction(addTemperaturePV);
  15837. channelMenu->addAction(addTemperatureSV);
  15838. addChannelButton->setMenu(channelMenu);
  15839. addChannelButton->setPopupMode(QToolButton::InstantPopup);
  15840. layout->addWidget(addChannelButton);
  15841. QHBoxLayout *stationLayout = new QHBoxLayout;
  15842. QLabel *stationLabel = new QLabel(tr("Station:"));
  15843. QSpinBox *stationNumber = new QSpinBox;
  15844. stationNumber->setMinimum(0);
  15845. stationNumber->setMaximum(255);
  15846. stationLayout->addWidget(stationLabel);
  15847. stationLayout->addWidget(stationNumber);
  15848. layout->addLayout(stationLayout);
  15849. QCheckBox *fixedUnit = new QCheckBox(tr("Fixed Temperature Unit"));
  15850. layout->addWidget(fixedUnit);
  15851. QWidget *fixedUnitPlaceholder = new QWidget(this);
  15852. QHBoxLayout *fixedUnitLayout = new QHBoxLayout;
  15853. QLabel *fixedUnitLabel = new QLabel(tr("Temperature Unit:"));
  15854. QComboBox *fixedUnitSelector = new QComboBox;
  15855. fixedUnitSelector->addItem("Fahrenheit");
  15856. fixedUnitSelector->addItem("Celsius");
  15857. fixedUnitLayout->addWidget(fixedUnitLabel);
  15858. fixedUnitLayout->addWidget(fixedUnitSelector);
  15859. fixedUnitPlaceholder->setLayout(fixedUnitLayout);
  15860. unitSpecificationLayout->addWidget(fixedUnitPlaceholder);
  15861. QWidget *queriedUnitPlaceholder = new QWidget(this);
  15862. QFormLayout *queriedUnitLayout = new QFormLayout;
  15863. ShortHexSpinBox *unitAddress = new ShortHexSpinBox;
  15864. queriedUnitLayout->addRow(tr("Function 0x03 Unit Address:"), unitAddress);
  15865. QSpinBox *valueF = new QSpinBox;
  15866. valueF->setMinimum(0);
  15867. valueF->setMaximum(65535);
  15868. queriedUnitLayout->addRow(tr("Value for Fahrenheit"), valueF);
  15869. QSpinBox *valueC = new QSpinBox;
  15870. valueC->setMinimum(0);
  15871. valueC->setMaximum(65535);
  15872. queriedUnitLayout->addRow(tr("Value for Celsius"), valueC);
  15873. queriedUnitPlaceholder->setLayout(queriedUnitLayout);
  15874. unitSpecificationLayout->addWidget(queriedUnitPlaceholder);
  15875. layout->addLayout(unitSpecificationLayout);
  15876. QCheckBox *fixedPrecision = new QCheckBox(tr("Fixed Precision"));
  15877. layout->addWidget(fixedPrecision);
  15878. QWidget *fixedPrecisionPlaceholder = new QWidget(this);
  15879. QFormLayout *fixedPrecisionLayout = new QFormLayout;
  15880. QSpinBox *fixedPrecisionValue = new QSpinBox;
  15881. fixedPrecisionValue->setMinimum(0);
  15882. fixedPrecisionValue->setMaximum(9);
  15883. fixedPrecisionLayout->addRow("Places after the decimal point:",
  15884. fixedPrecisionValue);
  15885. fixedPrecisionPlaceholder->setLayout(fixedPrecisionLayout);
  15886. decimalSpecificationLayout->addWidget(fixedPrecisionPlaceholder);
  15887. QWidget *queriedPrecisionPlaceholder = new QWidget(this);
  15888. QFormLayout *queriedPrecisionLayout = new QFormLayout;
  15889. ShortHexSpinBox *precisionAddress = new ShortHexSpinBox;
  15890. queriedPrecisionLayout->addRow("Function 0x03 Decimal Position Address:",
  15891. precisionAddress);
  15892. queriedPrecisionPlaceholder->setLayout(queriedPrecisionLayout);
  15893. decimalSpecificationLayout->addWidget(queriedPrecisionPlaceholder);
  15894. layout->addLayout(decimalSpecificationLayout);
  15895. @<Get device configuration data for current node@>@;
  15896. for(int i = 0; i < configData.size(); i++)
  15897. {
  15898. node = configData.at(i).toElement();
  15899. if(node.attribute("name") == "station")
  15900. {
  15901. stationNumber->setValue(node.attribute("value").toInt());
  15902. }
  15903. else if(node.attribute("name") == "fixedunit")
  15904. {
  15905. if(node.attribute("value") == "true")
  15906. {
  15907. fixedUnit->setCheckState(Qt::Checked);
  15908. }
  15909. else if(node.attribute("value") == "false")
  15910. {
  15911. fixedUnit->setCheckState(Qt::Unchecked);
  15912. }
  15913. }
  15914. else if(node.attribute("name") == "fixedprecision")
  15915. {
  15916. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  15917. }
  15918. else if(node.attribute("name") == "unit")
  15919. {
  15920. fixedUnitSelector->setCurrentIndex(fixedUnitSelector->findText(node.attribute("value")));
  15921. }
  15922. else if(node.attribute("name") == "unitaddress")
  15923. {
  15924. unitAddress->setValue(node.attribute("value").toInt());
  15925. }
  15926. else if(node.attribute("name") == "fvalue")
  15927. {
  15928. valueF->setValue(node.attribute("value").toInt());
  15929. }
  15930. else if(node.attribute("name") == "cvalue")
  15931. {
  15932. valueC->setValue(node.attribute("value").toInt());
  15933. }
  15934. else if(node.attribute("name") == "precisionaddress")
  15935. {
  15936. precisionAddress->setValue(node.attribute("value").toInt());
  15937. }
  15938. else if(node.attribute("name") == "precision")
  15939. {
  15940. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  15941. }
  15942. }
  15943. updateStationNumber(stationNumber->value());
  15944. updateFixedUnit(fixedUnit->isChecked());
  15945. updateFixedDecimal(fixedPrecision->isChecked());
  15946. updateUnit(fixedUnitSelector->currentText());
  15947. updateUnitAddress(unitAddress->value());
  15948. updateValueF(valueF->value());
  15949. updateValueC(valueC->value());
  15950. updatePrecisionAddress(precisionAddress->value());
  15951. updatePrecisionValue(fixedPrecisionValue->value());
  15952. connect(stationNumber, SIGNAL(valueChanged(int)),
  15953. this, SLOT(updateStationNumber(int)));
  15954. connect(fixedUnitSelector, SIGNAL(currentIndexChanged(QString)),
  15955. this, SLOT(updateUnit(QString)));
  15956. connect(unitAddress, SIGNAL(valueChanged(int)),
  15957. this, SLOT(updateUnitAddress(int)));
  15958. connect(valueF, SIGNAL(valueChanged(int)),
  15959. this, SLOT(updateValueF(int)));
  15960. connect(valueC, SIGNAL(valueChanged(int)),
  15961. this, SLOT(updateValueC(int)));
  15962. connect(fixedUnit, SIGNAL(toggled(bool)),
  15963. this, SLOT(updateFixedUnit(bool)));
  15964. connect(fixedPrecision, SIGNAL(toggled(bool)),
  15965. this, SLOT(updateFixedDecimal(bool)));
  15966. connect(fixedPrecisionValue, SIGNAL(valueChanged(int)),
  15967. this, SLOT(updatePrecisionValue(int)));
  15968. connect(precisionAddress, SIGNAL(valueChanged(int)),
  15969. this, SLOT(updatePrecisionAddress(int)));
  15970. setLayout(layout);
  15971. }
  15972. void ModbusRtuDeviceConfWidget::updateStationNumber(int newStation)
  15973. {
  15974. updateAttribute("station", QString("%1").arg(newStation));
  15975. }
  15976. void ModbusRtuDeviceConfWidget::updateFixedUnit(bool newFixed)
  15977. {
  15978. if(newFixed)
  15979. {
  15980. unitSpecificationLayout->setCurrentIndex(0);
  15981. updateAttribute("fixedunit", "true");
  15982. }
  15983. else
  15984. {
  15985. unitSpecificationLayout->setCurrentIndex(1);
  15986. updateAttribute("fixedunit", "false");
  15987. }
  15988. }
  15989. void ModbusRtuDeviceConfWidget::updateFixedDecimal(bool newFixed)
  15990. {
  15991. if(newFixed)
  15992. {
  15993. decimalSpecificationLayout->setCurrentIndex(0);
  15994. updateAttribute("fixedprecision", "true");
  15995. }
  15996. else
  15997. {
  15998. decimalSpecificationLayout->setCurrentIndex(1);
  15999. updateAttribute("fixedprecision", "false");
  16000. }
  16001. }
  16002. void ModbusRtuDeviceConfWidget::updateUnit(const QString &newUnit)
  16003. {
  16004. updateAttribute("unit", newUnit);
  16005. }
  16006. void ModbusRtuDeviceConfWidget::updateUnitAddress(int newAddress)
  16007. {
  16008. updateAttribute("unitaddress", QString("%1").arg(newAddress));
  16009. }
  16010. void ModbusRtuDeviceConfWidget::updateValueF(int newValue)
  16011. {
  16012. updateAttribute("fvalue", QString("%1").arg(newValue));
  16013. }
  16014. void ModbusRtuDeviceConfWidget::updateValueC(int newValue)
  16015. {
  16016. updateAttribute("cvalue", QString("%1").arg(newValue));
  16017. }
  16018. void ModbusRtuDeviceConfWidget::updatePrecisionAddress(int newAddress)
  16019. {
  16020. updateAttribute("precisionaddress", QString("%1").arg(newAddress));
  16021. }
  16022. void ModbusRtuDeviceConfWidget::updatePrecisionValue(int newValue)
  16023. {
  16024. updateAttribute("precision", QString("%1").arg(newValue));
  16025. }
  16026. @ Initial Modbus RTU support is very limited and only considers temperature
  16027. process and set values. While in some cases it would be possible to cleverly
  16028. adapt this support to broader categories this is an area that must be extended
  16029. later to cover at least unitless control values and on/off status values. It
  16030. would be ideal to cover a broad range of useful properties. To read process
  16031. values we need to know the address that the current process value can be read
  16032. from.
  16033. @<Class declarations@>=
  16034. class ModbusRtuDeviceTPvConfWidget : public BasicDeviceConfigurationWidget
  16035. {
  16036. @[Q_OBJECT@]@/
  16037. public:@/
  16038. @[Q_INVOKABLE@]@, ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  16039. const QModelIndex &index);
  16040. @[private slots@]:@/
  16041. void updateAddress(int newAddress);
  16042. };
  16043. @ This requires only a single field to store the address to query the current
  16044. process value.
  16045. @<ModbusRtuDeviceTPvConfWidget implementation@>=
  16046. ModbusRtuDeviceTPvConfWidget::ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  16047. const QModelIndex &index)
  16048. : BasicDeviceConfigurationWidget(model, index)
  16049. {
  16050. QFormLayout *layout = new QFormLayout;
  16051. ShortHexSpinBox *address = new ShortHexSpinBox;
  16052. layout->addRow(tr("Function 0x04 Process Value Address"), address);
  16053. @<Get device configuration data for current node@>@;
  16054. for(int i = 0; i < configData.size(); i++)
  16055. {
  16056. node = configData.at(i).toElement();
  16057. if(node.attribute("name") == "address")
  16058. {
  16059. address->setValue(node.attribute("value").toInt());
  16060. break;
  16061. }
  16062. }
  16063. updateAddress(address->value());
  16064. connect(address, SIGNAL(valueChanged(int)), this, SLOT(updateAddress(int)));
  16065. setLayout(layout);
  16066. }
  16067. void ModbusRtuDeviceTPvConfWidget::updateAddress(int newAddress)
  16068. {
  16069. updateAttribute("address", QString("%1").arg(newAddress));
  16070. }
  16071. @ Set values are slightly more complicated as we may want either a fixed range
  16072. or the ability to query the device for its current allowed range, but nothing
  16073. is here that hasn'@q'@>t been seen elsewhere.
  16074. @<Class declarations@>=
  16075. class ModbusRtuDeviceTSvConfWidget : public BasicDeviceConfigurationWidget@/
  16076. {@/
  16077. @[Q_OBJECT@]@;
  16078. public:@/
  16079. Q_INVOKABLE@, ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  16080. const QModelIndex &index);
  16081. @[private slots@]:@/
  16082. void updateReadAddress(int newAddress);
  16083. void updateWriteAddress(int newAddress);
  16084. void updateFixedRange(bool fixed);
  16085. void updateLower(const QString &lower);
  16086. void updateUpper(const QString &upper);
  16087. void updateLowerAddress(int newAddress);
  16088. void updateUpperAddress(int newAddress);@/
  16089. private:@/
  16090. QStackedLayout *boundsLayout;
  16091. };
  16092. @ Upper and lower bounds when operating on a fixed range are still subject to
  16093. decimal position rules in the parent node. It may be a good idea to enforce
  16094. this, however at present the person configuring the system is trusted to know
  16095. what they are doing.
  16096. @<ModbusRtuDeviceTSvConfWidget implementation@>=
  16097. ModbusRtuDeviceTSvConfWidget::ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  16098. const QModelIndex &index)
  16099. : BasicDeviceConfigurationWidget(model, index), boundsLayout(new QStackedLayout)
  16100. {
  16101. QVBoxLayout *layout = new QVBoxLayout;
  16102. QFormLayout *addressLayout = new QFormLayout;
  16103. ShortHexSpinBox *readAddress = new ShortHexSpinBox;
  16104. ShortHexSpinBox *writeAddress = new ShortHexSpinBox;
  16105. addressLayout->addRow(tr("Function 0x04 Read Set Value Address:"), readAddress);
  16106. addressLayout->addRow(tr("Function 0x06 Write Set Value Address:"), writeAddress);
  16107. layout->addLayout(addressLayout);
  16108. QCheckBox *fixedRange = new QCheckBox(tr("Fixed Set Value Range"));
  16109. layout->addWidget(fixedRange);
  16110. QWidget *queriedRangePlaceholder = new QWidget(this);
  16111. QFormLayout *queriedRangeLayout = new QFormLayout;
  16112. ShortHexSpinBox *lowerAddress = new ShortHexSpinBox;
  16113. ShortHexSpinBox *upperAddress = new ShortHexSpinBox;
  16114. queriedRangeLayout->addRow(tr("Function 0x03 Minimum Set Value Address"),
  16115. lowerAddress);
  16116. queriedRangeLayout->addRow(tr("Function 0x03 Maximum Set Value Address"),
  16117. upperAddress);
  16118. queriedRangePlaceholder->setLayout(queriedRangeLayout);
  16119. boundsLayout->addWidget(queriedRangePlaceholder);
  16120. QWidget *fixedRangePlaceholder = new QWidget(this);
  16121. QFormLayout *fixedRangeLayout = new QFormLayout;
  16122. QLineEdit *fixedLower = new QLineEdit;
  16123. QLineEdit *fixedUpper = new QLineEdit;
  16124. fixedRangeLayout->addRow(tr("Minimum Set Value:"), fixedLower);
  16125. fixedRangeLayout->addRow(tr("Maximum Set Value:"), fixedUpper);
  16126. fixedRangePlaceholder->setLayout(fixedRangeLayout);
  16127. boundsLayout->addWidget(fixedRangePlaceholder);
  16128. layout->addLayout(boundsLayout);
  16129. @<Get device configuration data for current node@>@;
  16130. for(int i = 0; i < configData.size(); i++)
  16131. {
  16132. node = configData.at(i).toElement();
  16133. if(node.attribute("name") == "readaddress")
  16134. {
  16135. readAddress->setValue(node.attribute("value").toInt());
  16136. }
  16137. else if(node.attribute("name") == "writeaddress")
  16138. {
  16139. writeAddress->setValue(node.attribute("value").toInt());
  16140. }
  16141. else if(node.attribute("name") == "fixedrange")
  16142. {
  16143. if(node.attribute("value") == "true")
  16144. {
  16145. fixedRange->setCheckState(Qt::Checked);
  16146. }
  16147. else if(node.attribute("value") == "false")
  16148. {
  16149. fixedRange->setCheckState(Qt::Unchecked);
  16150. }
  16151. }
  16152. else if(node.attribute("name") == "fixedlower")
  16153. {
  16154. fixedLower->setText(node.attribute("value"));
  16155. }
  16156. else if(node.attribute("name") == "fixedupper")
  16157. {
  16158. fixedUpper->setText(node.attribute("value"));
  16159. }
  16160. else if(node.attribute("name") == "loweraddress")
  16161. {
  16162. lowerAddress->setValue(node.attribute("value").toInt());
  16163. }
  16164. else if(node.attribute("name") == "upperaddress")
  16165. {
  16166. upperAddress->setValue(node.attribute("value").toInt());
  16167. }
  16168. }
  16169. updateReadAddress(readAddress->value());
  16170. updateWriteAddress(writeAddress->value());
  16171. updateFixedRange(fixedRange->isChecked());
  16172. updateLower(fixedLower->text());
  16173. updateUpper(fixedUpper->text());
  16174. updateLowerAddress(lowerAddress->value());
  16175. updateUpperAddress(upperAddress->value());
  16176. connect(readAddress, SIGNAL(valueChanged(int)),
  16177. this, SLOT(updateReadAddress(int)));
  16178. connect(writeAddress, SIGNAL(valueChanged(int)),
  16179. this, SLOT(updateWriteAddress(int)));
  16180. connect(fixedRange, SIGNAL(toggled(bool)), this, SLOT(updateFixedRange(bool)));
  16181. connect(fixedLower, SIGNAL(textChanged(QString)),
  16182. this, SLOT(updateLower(QString)));
  16183. connect(fixedUpper, SIGNAL(textChanged(QString)),
  16184. this, SLOT(updateUpper(QString)));
  16185. connect(lowerAddress, SIGNAL(valueChanged(int)),
  16186. this, SLOT(updateLowerAddress(int)));
  16187. connect(upperAddress, SIGNAL(valueChanged(int)),
  16188. this, SLOT(updateUpperAddress(int)));
  16189. setLayout(layout);
  16190. }
  16191. void ModbusRtuDeviceTSvConfWidget::updateReadAddress(int newAddress)
  16192. {
  16193. updateAttribute("readaddress", QString("%1").arg(newAddress));
  16194. }
  16195. void ModbusRtuDeviceTSvConfWidget::updateWriteAddress(int newAddress)
  16196. {
  16197. updateAttribute("writeaddress", QString("%1").arg(newAddress));
  16198. }
  16199. void ModbusRtuDeviceTSvConfWidget::updateFixedRange(bool fixed)
  16200. {
  16201. if(fixed)
  16202. {
  16203. updateAttribute("fixedrange", "true");
  16204. boundsLayout->setCurrentIndex(1);
  16205. }
  16206. else
  16207. {
  16208. updateAttribute("fixedrange", "false");
  16209. boundsLayout->setCurrentIndex(0);
  16210. }
  16211. }
  16212. void ModbusRtuDeviceTSvConfWidget::updateLower(const QString &lower)
  16213. {
  16214. updateAttribute("fixedlower", lower);
  16215. }
  16216. void ModbusRtuDeviceTSvConfWidget::updateUpper(const QString &upper)
  16217. {
  16218. updateAttribute("fixedupper", upper);
  16219. }
  16220. void ModbusRtuDeviceTSvConfWidget::updateLowerAddress(int newAddress)
  16221. {
  16222. updateAttribute("loweraddress", QString("%1").arg(newAddress));
  16223. }
  16224. void ModbusRtuDeviceTSvConfWidget::updateUpperAddress(int newAddress)
  16225. {
  16226. updateAttribute("upperaddress", QString("%1").arg(newAddress));
  16227. }
  16228. @ The configuration widgets need to be registered.
  16229. @<Register device configuration widgets@>=
  16230. app.registerDeviceConfigurationWidget("modbusrtuport", ModbusRtuPortConfWidget::staticMetaObject);
  16231. app.registerDeviceConfigurationWidget("modbusrtudevice", ModbusRtuDeviceConfWidget::staticMetaObject);
  16232. app.registerDeviceConfigurationWidget("modbustemperaturepv", ModbusRtuDeviceTPvConfWidget::staticMetaObject);
  16233. app.registerDeviceConfigurationWidget("modbustemperaturesv", ModbusRtuDeviceTSvConfWidget::staticMetaObject);
  16234. @ A |NodeInserter| for the driver configuration widget is also needed. Note
  16235. that this is temporarily disabled. These configuration widgets will become
  16236. useful when I rearchitect the Modbus RTU support in a future release.
  16237. @<Register top level device configuration nodes@>=
  16238. #if 0
  16239. inserter = new NodeInserter(tr("Modbus RTU Port"), tr("Modbus RTU Port"), "modbusrtuport", NULL);
  16240. topLevelNodeInserters.append(inserter);
  16241. #endif
  16242. @** Configuration of Annotation Controls.
  16243. \noindent Aside from the details of hardware devices, the logging view must
  16244. also be able to set up log annotation controls. A few different control types
  16245. are offered. These include simple push buttons which insert a fixed annotation
  16246. when activated, push buttons which insert a value that includes a number which
  16247. is incremented every time the button is pressed, free text entry fields, and
  16248. numeric entry fields.
  16249. The basic push button control should allow configuration of both the button
  16250. text and the annotation text.
  16251. @<Class declarations@>=
  16252. class AnnotationButtonConfWidget : public BasicDeviceConfigurationWidget
  16253. {
  16254. @[Q_OBJECT@]@;
  16255. public:@/
  16256. @[Q_INVOKABLE@]@, AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16257. @[private slots@]:@/
  16258. void updateButtonText(const QString &text);
  16259. void updateAnnotationText(const QString &text);
  16260. };
  16261. @ The constructor sets up the controls for editing this data.
  16262. @<AnnotationButtonConfWidget implementation@>=
  16263. AnnotationButtonConfWidget::AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16264. : BasicDeviceConfigurationWidget(model, index)
  16265. {
  16266. QFormLayout *layout = new QFormLayout;
  16267. QLineEdit *buttonTextEdit = new QLineEdit;
  16268. QLineEdit *annotationTextEdit = new QLineEdit;
  16269. layout->addRow(tr("Button Text:"), buttonTextEdit);
  16270. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  16271. @<Get device configuration data for current node@>@;
  16272. for(int i = 0; i < configData.size(); i++)
  16273. {
  16274. node = configData.at(i).toElement();
  16275. if(node.attribute("name") == "buttontext")
  16276. {
  16277. buttonTextEdit->setText(node.attribute("value"));
  16278. }
  16279. else if(node.attribute("name") == "annotationtext")
  16280. {
  16281. annotationTextEdit->setText(node.attribute("value"));
  16282. }
  16283. }
  16284. updateButtonText(buttonTextEdit->text());
  16285. updateAnnotationText(annotationTextEdit->text());
  16286. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  16287. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  16288. setLayout(layout);
  16289. }
  16290. @ The slots are implemented trivially.
  16291. @<AnnotationButtonConfWidget implementation@>=
  16292. void AnnotationButtonConfWidget::updateButtonText(const QString &text)
  16293. {
  16294. updateAttribute("buttontext", text);
  16295. }
  16296. void AnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  16297. {
  16298. updateAttribute("annotationtext", text);
  16299. }
  16300. @ The control must be registered.
  16301. @<Register device configuration widgets@>=
  16302. app.registerDeviceConfigurationWidget("annotationbutton", AnnotationButtonConfWidget::staticMetaObject);
  16303. @ Closely related to the previous control is one which provides parameterized
  16304. text. Technically this is not needed as both this and the previous
  16305. configuration control map to the same widget in the logging view and
  16306. parameterized annotation text can be used with either. The reason for
  16307. separating these is to indicate that it should be possible to change the text
  16308. and reset the number without altering the default configuration or requiring a
  16309. reinitialization of the logging view.
  16310. @<Class declarations@>=
  16311. class ReconfigurableAnnotationButtonConfWidget : public BasicDeviceConfigurationWidget@/
  16312. {@/
  16313. @[Q_OBJECT@]@;
  16314. public:@/
  16315. Q_INVOKABLE ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16316. @[private slots@]:@/
  16317. void updateButtonText(const QString &text);
  16318. void updateAnnotationText(const QString &text);
  16319. };
  16320. @ The key difference in implementation is the addition of some documentation on
  16321. how to specify a numeric placeholder in the annotation text.
  16322. @<AnnotationButtonConfWidget implementation@>=
  16323. ReconfigurableAnnotationButtonConfWidget::ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16324. : BasicDeviceConfigurationWidget(model, index)
  16325. {
  16326. QFormLayout *layout = new QFormLayout;
  16327. QLineEdit *buttonTextEdit = new QLineEdit;
  16328. QLineEdit *annotationTextEdit = new QLineEdit;
  16329. annotationTextEdit->setText("%A-%1");
  16330. layout->addRow(tr("Button Text:"), buttonTextEdit);
  16331. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  16332. @<Get device configuration data for current node@>@;
  16333. for(int i = 0; i < configData.size(); i++)
  16334. {
  16335. node = configData.at(i).toElement();
  16336. if(node.attribute("name") == "buttontext")
  16337. {
  16338. buttonTextEdit->setText(node.attribute("value"));
  16339. }
  16340. else if(node.attribute("name") == "annotationtext")
  16341. {
  16342. annotationTextEdit->setText(node.attribute("value"));
  16343. }
  16344. }
  16345. updateButtonText(buttonTextEdit->text());
  16346. updateAnnotationText(annotationTextEdit->text());
  16347. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  16348. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  16349. QTextEdit *documentation = new QTextEdit;
  16350. 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."));
  16351. documentation->setReadOnly(true);
  16352. layout->addRow("", documentation);
  16353. setLayout(layout);
  16354. }
  16355. void ReconfigurableAnnotationButtonConfWidget::updateButtonText(const QString &text)
  16356. {
  16357. updateAttribute("buttontext", text);
  16358. }
  16359. void ReconfigurableAnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  16360. {
  16361. updateAttribute("annotationtext", text);
  16362. }
  16363. @ The control must be registered as usual.
  16364. @<Register device configuration widgets@>=
  16365. app.registerDeviceConfigurationWidget("reconfigurablebutton", ReconfigurableAnnotationButtonConfWidget::staticMetaObject);
  16366. @ While it is generally better to have all measurements logged automatically,
  16367. many roasters would like to keep track of infrequently altered control
  16368. variables which have not been set up for automated logging. A reading from the
  16369. manometer after a fuel adjustment, for example, is frequently not available by
  16370. automated means. In cases such as this, providing for numeric annotation entry
  16371. may be desired. The |AnnotationSpinBox| provides for this. There are a few
  16372. details that are important in this. First is a label to better indicate to the
  16373. operator what values in this control represent. The range of allowed values and
  16374. the number of decimal places is important. This control also allows the
  16375. specification of text to precede and/or follow the numeric value and this must
  16376. be configurable.
  16377. @<Class declarations@>=
  16378. class NoteSpinConfWidget : public BasicDeviceConfigurationWidget
  16379. {
  16380. @[Q_OBJECT@]@;
  16381. public:@/
  16382. @[Q_INVOKABLE@]@, NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16383. @[private slots@]:@/
  16384. void updateLabel(const QString &text);
  16385. void updateMinimum(const QString &minimum);
  16386. void updateMaximum(const QString &maximum);
  16387. void updatePrecision(int precision);
  16388. void updatePretext(const QString &text);
  16389. void updatePosttext(const QString &text);
  16390. };
  16391. @ There is nothing new in the implementation of note.
  16392. @<NoteSpinConfWidget implementation@>=
  16393. NoteSpinConfWidget::NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16394. : BasicDeviceConfigurationWidget(model, index)
  16395. {
  16396. QFormLayout *layout = new QFormLayout;
  16397. QLineEdit *labelEdit = new QLineEdit;
  16398. layout->addRow(tr("Control Label: "), labelEdit);
  16399. QLineEdit *minimumEdit = new QLineEdit;
  16400. layout->addRow(tr("Minimum Value: "), minimumEdit);
  16401. QLineEdit *maximumEdit = new QLineEdit;
  16402. layout->addRow(tr("Maximum Value: "), maximumEdit);
  16403. QSpinBox *precisionEdit = new QSpinBox;
  16404. precisionEdit->setMinimum(0);
  16405. precisionEdit->setMaximum(9);
  16406. layout->addRow(tr("Precision"), precisionEdit);
  16407. QLineEdit *pretext = new QLineEdit;
  16408. layout->addRow(tr("Prefix text"), pretext);
  16409. QLineEdit *posttext = new QLineEdit;
  16410. layout->addRow(tr("Suffix text"), posttext);
  16411. @<Get device configuration data for current node@>@;
  16412. for(int i = 0; i < configData.size(); i++)
  16413. {
  16414. node = configData.at(i).toElement();
  16415. if(node.attribute("name") == "label")
  16416. {
  16417. labelEdit->setText(node.attribute("value"));
  16418. }
  16419. else if(node.attribute("name") == "minimum")
  16420. {
  16421. minimumEdit->setText(node.attribute("value"));
  16422. }
  16423. else if(node.attribute("name") == "maximum")
  16424. {
  16425. maximumEdit->setText(node.attribute("value"));
  16426. }
  16427. else if(node.attribute("name") == "precision")
  16428. {
  16429. precisionEdit->setValue(node.attribute("value").toInt());
  16430. }
  16431. else if(node.attribute("name") == "pretext")
  16432. {
  16433. pretext->setText(node.attribute("value"));
  16434. }
  16435. else if(node.attribute("name") == "posttext")
  16436. {
  16437. posttext->setText(node.attribute("value"));
  16438. }
  16439. }
  16440. updateLabel(labelEdit->text());
  16441. updateMinimum(minimumEdit->text());
  16442. updateMaximum(maximumEdit->text());
  16443. updatePrecision(precisionEdit->value());
  16444. updatePretext(pretext->text());
  16445. updatePosttext(posttext->text());
  16446. connect(labelEdit, SIGNAL(textEdited(QString)), this, SLOT(updateLabel(QString)));
  16447. connect(minimumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMinimum(QString)));
  16448. connect(maximumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMaximum(QString)));
  16449. connect(precisionEdit, SIGNAL(valueChanged(int)), this, SLOT(updatePrecision(int)));
  16450. connect(pretext, SIGNAL(textEdited(QString)), this, SLOT(updatePretext(QString)));
  16451. connect(posttext, SIGNAL(textEdited(QString)), this, SLOT(updatePosttext(QString)));
  16452. setLayout(layout);
  16453. }
  16454. void NoteSpinConfWidget::updateLabel(const QString &text)
  16455. {
  16456. updateAttribute("label", text);
  16457. }
  16458. void NoteSpinConfWidget::updateMinimum(const QString &minimum)
  16459. {
  16460. updateAttribute("minimum", minimum);
  16461. }
  16462. void NoteSpinConfWidget::updateMaximum(const QString &maximum)
  16463. {
  16464. updateAttribute("maximum", maximum);
  16465. }
  16466. void NoteSpinConfWidget::updatePrecision(int precision)
  16467. {
  16468. updateAttribute("precision", QString("%1").arg(precision));
  16469. }
  16470. void NoteSpinConfWidget::updatePretext(const QString &text)
  16471. {
  16472. updateAttribute("pretext", text);
  16473. }
  16474. void NoteSpinConfWidget::updatePosttext(const QString &text)
  16475. {
  16476. updateAttribute("posttext", text);
  16477. }
  16478. @ Configuration widget registration is as usual.
  16479. @<Register device configuration widgets@>=
  16480. app.registerDeviceConfigurationWidget("annotationspinbox", NoteSpinConfWidget::staticMetaObject);
  16481. @i freeannotation.w
  16482. @i settings.w
  16483. @** Communicating with a Device through Modbus RTU.
  16484. \noindent The classes described here need to be further generalized to support
  16485. communications with multiple devices on the same port. The interface is based
  16486. on the |DAQ| class but extended to support additional functionality.
  16487. @<Class declarations@>=
  16488. class ModbusRTUDevice : public QObject
  16489. {
  16490. @[Q_OBJECT@]@;
  16491. public:@/
  16492. ModbusRTUDevice(DeviceTreeModel *model, const QModelIndex &index);
  16493. ~ModbusRTUDevice();
  16494. void queueMessage(QByteArray request, QObject *object, const char *callback);
  16495. @[Q_INVOKABLE@,@, double@]@, SVLower();@t\2\2@>@/
  16496. @[Q_INVOKABLE@,@, double@]@, SVUpper();@t\2\2@>@/
  16497. @[Q_INVOKABLE@,@, int@]@, decimals();@t\2\2@>@/
  16498. QList<Channel*> channels;@/
  16499. @[public slots@]:@/
  16500. void outputSV(double sv);@/
  16501. signals:@/
  16502. void SVLowerChanged(double);
  16503. void SVUpperChanged(double);
  16504. void SVDecimalChanged(int);
  16505. void queueEmpty();@/
  16506. @[private slots@]:@/
  16507. void dataAvailable();
  16508. void sendNextMessage();
  16509. void decimalResponse(QByteArray response);
  16510. void unitResponse(QByteArray response);
  16511. void svlResponse(QByteArray response);
  16512. void svuResponse(QByteArray response);
  16513. void requestMeasurement();
  16514. void mResponse(QByteArray response);
  16515. void ignore(QByteArray response);
  16516. void timeout();@/
  16517. private:@/
  16518. QextSerialPort *port;
  16519. QByteArray responseBuffer;
  16520. QList<QByteArray> messageQueue;
  16521. QList<QObject *> retObjQueue;
  16522. QList<char *> callbackQueue;
  16523. quint16 calculateCRC(QByteArray data);
  16524. QTimer *messageDelayTimer;
  16525. QTimer *commTimeout;
  16526. int delayTime;
  16527. char station;
  16528. int decimalPosition;
  16529. int valueF;
  16530. int valueC;
  16531. bool unitIsF;
  16532. double outputSVLower;
  16533. double outputSVUpper;
  16534. QByteArray outputSVStub;
  16535. QByteArray pvStub;
  16536. QByteArray svStub;
  16537. QByteArray mStub;
  16538. quint16 pvaddress;
  16539. quint16 svaddress;
  16540. bool svenabled;
  16541. bool readingsv;
  16542. double savedpv;
  16543. bool waiting;
  16544. };
  16545. @ The constructor reads its configuration from the configuration sub-tree of the
  16546. port node. This was adapted from a prototype implementation which used
  16547. |QSettings| to store this data. Note that this will only process the first
  16548. device specified on the port, the first process value on that device, and the
  16549. first set value on that device. A much more versatile architecture has been
  16550. planned for a future release which allows multiple devices per bus and
  16551. arbitrarily many monitored addresses per device. Communications are initiated
  16552. immediately upon construction.
  16553. @<ModbusRTUDevice implementation@>=
  16554. ModbusRTUDevice::ModbusRTUDevice(DeviceTreeModel *model,@| const QModelIndex &index)
  16555. : QObject(NULL), messageDelayTimer(new QTimer), commTimeout(new QTimer), unitIsF(@[true@]), readingsv(@[false@]),
  16556. waiting(@[false@])@/
  16557. {@/
  16558. QDomElement portReferenceElement = model->referenceElement(model->data(index,
  16559. Qt::UserRole).toString());
  16560. QDomNodeList portConfigData = portReferenceElement.elementsByTagName("attribute");
  16561. QDomElement node;
  16562. QVariantMap attributes;
  16563. for(int i = 0; i < portConfigData.size(); i++)
  16564. {
  16565. node = portConfigData.at(i).toElement();
  16566. attributes.insert(node.attribute("name"), node.attribute("value"));
  16567. }
  16568. port = new QextSerialPort(attributes.value("port").toString(),
  16569. QextSerialPort::EventDriven);
  16570. int baudRate = attributes.value("baud").toInt();
  16571. port->setBaudRate((BaudRateType)baudRate);
  16572. double temp = ((double)(1) / (double)(baudRate)) * 48;
  16573. delayTime = (int)(temp * 3000);
  16574. messageDelayTimer->setSingleShot(true);
  16575. commTimeout->setSingleShot(true);
  16576. connect(messageDelayTimer, SIGNAL(timeout()), this, SLOT(sendNextMessage()));
  16577. connect(commTimeout, SIGNAL(timeout()), this, SLOT(timeout()));
  16578. port->setDataBits(DATA_8);
  16579. port->setParity((ParityType)attributes.value("parity").toInt());
  16580. port->setStopBits((StopBitsType)attributes.value("stop").toInt());
  16581. port->setFlowControl((FlowType)attributes.value("flow").toInt());
  16582. connect(port, SIGNAL(readyRead()), this, SLOT(dataAvailable()));
  16583. port->open(QIODevice::ReadWrite);
  16584. station = (char)attributes.value("station").toInt();
  16585. if(attributes.value("decimalQuery") == "true")
  16586. {
  16587. decimalPosition = 0;
  16588. QByteArray message;
  16589. message.append(station);
  16590. message.append((char)0x03);
  16591. quint16 address = (quint16)attributes.value("decimalAddress").toInt();
  16592. char *addressBytes = (char*)&address;
  16593. message.append(addressBytes[1]);
  16594. message.append(addressBytes[0]);
  16595. message.append((char)0x00);
  16596. message.append((char)0x01);
  16597. queueMessage(message, this, "decimalResponse(QByteArray)");
  16598. }
  16599. else
  16600. {
  16601. decimalPosition = attributes.value("decimalPosition").toInt();
  16602. }
  16603. valueF = attributes.value("valueF").toInt();
  16604. valueC = attributes.value("valueC").toInt();
  16605. if(attributes.value("unitQuery") == "true")
  16606. {
  16607. QByteArray message;
  16608. message.append(station);
  16609. message.append((char)0x03);
  16610. quint16 address = (quint16)attributes.value("unitAddress").toInt();
  16611. char *addressBytes = (char*)&address;
  16612. message.append(addressBytes[1]);
  16613. message.append(addressBytes[0]);
  16614. message.append((char)0x00);
  16615. message.append((char)0x01);
  16616. queueMessage(message, this, "unitResponse(QByteArray)");
  16617. }
  16618. else
  16619. {
  16620. if(attributes.value("fixedUnit") == "Celsius")
  16621. {
  16622. unitIsF = @[false@];
  16623. }
  16624. }
  16625. if(attributes.value("sVWritable") == "true")
  16626. {
  16627. if(attributes.value("deviceLimit") == "true")
  16628. {
  16629. QByteArray lmessage;
  16630. lmessage.append(station);
  16631. lmessage.append((char)0x03);
  16632. quint16 laddress = (quint16)attributes.value("sVLowerAddr").toInt();
  16633. char *addressBytes = (char*)&laddress;
  16634. lmessage.append(addressBytes[1]);
  16635. lmessage.append(addressBytes[0]);
  16636. lmessage.append((char)0x00);
  16637. lmessage.append((char)0x01);
  16638. queueMessage(lmessage, this, "svlResponse(QByteArray)");
  16639. QByteArray umessage;
  16640. umessage.append(station);
  16641. umessage.append((char)0x03);
  16642. quint16 uaddress = (quint16)attributes.value("sVUpperAddr").toInt();
  16643. addressBytes = (char*)&uaddress;
  16644. umessage.append(addressBytes[1]);
  16645. umessage.append(addressBytes[0]);
  16646. umessage.append((char)0x00);
  16647. umessage.append((char)0x01);
  16648. queueMessage(umessage, this, "svuResponse(QByteArray)");
  16649. }
  16650. else
  16651. {
  16652. outputSVLower = attributes.value("sVLower").toDouble();
  16653. outputSVUpper = attributes.value("sVUpper").toDouble();
  16654. }
  16655. outputSVStub.append(station);
  16656. outputSVStub.append((char)0x06);
  16657. quint16 address = (quint16)attributes.value("sVOutputAddr").toInt();
  16658. char *addressBytes = (char*)&address;
  16659. outputSVStub.append(addressBytes[1]);
  16660. outputSVStub.append(addressBytes[0]);
  16661. }
  16662. Channel *pv = new Channel;
  16663. channels.append(pv);
  16664. pvStub.append(station);
  16665. pvStub.append((char)0x04);
  16666. pvaddress = (quint16)attributes.value("pVAddress").toInt();
  16667. char *pvac = (char*)&pvaddress;
  16668. pvStub.append(pvac[1]);
  16669. pvStub.append(pvac[0]);
  16670. pvStub.append((char)0x00);
  16671. pvStub.append((char)0x01);
  16672. svenabled = attributes.value("sVEnabled").toBool();
  16673. if(svenabled)
  16674. {
  16675. Channel *sv = new Channel;
  16676. channels.append(sv);
  16677. svStub.append(station);
  16678. svStub.append((char)0x04);
  16679. svaddress = (quint16)attributes.value("sVReadAddress").toInt();
  16680. char *svac = (char*)&svaddress;
  16681. svStub.append(svac[1]);
  16682. svStub.append(svac[0]);
  16683. svStub.append((char)0x00);
  16684. svStub.append((char)0x01);
  16685. if(svaddress - pvaddress == 1)
  16686. {
  16687. mStub.append(station);
  16688. mStub.append((char)0x04);
  16689. mStub.append(pvac[1]);
  16690. mStub.append(pvac[0]);
  16691. mStub.append((char)0x00);
  16692. mStub.append((char)0x02);
  16693. }
  16694. }
  16695. connect(this, SIGNAL(queueEmpty()), this, SLOT(requestMeasurement()));
  16696. requestMeasurement();
  16697. }
  16698. double ModbusRTUDevice::SVLower()
  16699. {
  16700. return outputSVLower;
  16701. }
  16702. double ModbusRTUDevice::SVUpper()
  16703. {
  16704. return outputSVUpper;
  16705. }
  16706. int ModbusRTUDevice::decimals()
  16707. {
  16708. return decimalPosition;
  16709. }
  16710. void ModbusRTUDevice::decimalResponse(QByteArray response)
  16711. {
  16712. quint16 temp;
  16713. char *tchar = (char*)&temp;
  16714. tchar[1] = response.at(3);
  16715. tchar[0] = response.at(4);
  16716. decimalPosition = temp;
  16717. emit SVDecimalChanged(decimalPosition);
  16718. }
  16719. void ModbusRTUDevice::unitResponse(QByteArray response)
  16720. {
  16721. quint16 temp;
  16722. char *tchar = (char*)&temp;
  16723. tchar[1] = response.at(3);
  16724. tchar[0] = response.at(4);
  16725. int value = temp;
  16726. if(value == valueF)
  16727. {
  16728. unitIsF = @[true@];
  16729. }
  16730. else
  16731. {
  16732. unitIsF = @[false@];
  16733. }
  16734. }
  16735. void ModbusRTUDevice::svlResponse(QByteArray response)
  16736. {
  16737. quint16 temp;
  16738. char *tchar = (char*)&temp;
  16739. tchar[1] = response.at(3);
  16740. tchar[0] = response.at(4);
  16741. outputSVLower = (double)temp;
  16742. for(int i = 0; i < decimalPosition; i++)
  16743. {
  16744. outputSVLower /= 10;
  16745. }
  16746. emit SVLowerChanged(outputSVLower);
  16747. }
  16748. void ModbusRTUDevice::svuResponse(QByteArray response)
  16749. {
  16750. quint16 temp;
  16751. char *tchar = (char*)&temp;
  16752. tchar[1] = response.at(3);
  16753. tchar[0] = response.at(4);
  16754. outputSVUpper = (double)temp;
  16755. for(int i = 0; i < decimalPosition; i++)
  16756. {
  16757. outputSVUpper /= 10;
  16758. }
  16759. emit SVUpperChanged(outputSVUpper);
  16760. }
  16761. void ModbusRTUDevice::requestMeasurement()
  16762. {
  16763. if(mStub.length() > 0)
  16764. {
  16765. queueMessage(mStub, this, "mResponse(QByteArray)");
  16766. }
  16767. else
  16768. {
  16769. queueMessage(pvStub, this, "mResponse(QByteArray)");
  16770. if(svenabled)
  16771. {
  16772. queueMessage(svStub, this, "mResponse(QByteArray)");
  16773. }
  16774. }
  16775. }
  16776. void ModbusRTUDevice::mResponse(QByteArray response)
  16777. {
  16778. QTime time = QTime::currentTime();
  16779. if(response.at(2) == 0x04)
  16780. {
  16781. @<Process PV and SV@>@;
  16782. }
  16783. else
  16784. {
  16785. @<Process PV or SV@>@;
  16786. }
  16787. }
  16788. @ There are two ways that we might request measurement data. All of the
  16789. devices I'@q'@>ve seen documented provide function 0x4 addresses for PV and SV
  16790. such that SV can be obtained from the address immediately after the address
  16791. from which we obtain PV. In this case we request both values at the same time.
  16792. @<Process PV and SV@>=
  16793. quint16 pv;
  16794. quint16 sv;
  16795. char *pvBytes = (char*)&pv;
  16796. char *svBytes = (char*)&sv;
  16797. pvBytes[1] = response.at(3);
  16798. pvBytes[0] = response.at(4);
  16799. svBytes[1] = response.at(5);
  16800. svBytes[0] = response.at(6);
  16801. double pvOut = (double)pv;
  16802. double svOut = (double)sv;
  16803. for(int i = 0; i < decimalPosition; i++)
  16804. {
  16805. pvOut /= 10;
  16806. svOut /= 10;
  16807. }
  16808. if(!unitIsF)
  16809. {
  16810. pvOut = pvOut * 9 / 5 + 32;
  16811. svOut = svOut * 9 / 5 + 32;
  16812. }
  16813. Measurement pvm(pvOut, time, Units::Fahrenheit);
  16814. Measurement svm(svOut, time, Units::Fahrenheit);
  16815. channels.at(0)->input(pvm);
  16816. channels.at(1)->input(svm);
  16817. @ When not measuring PV and SV at the same time, there are two possibilities.
  16818. One possibility is that SV is not enabled and we will only be reading from PV.
  16819. The other possibility is that we are alternating between reading PV and SV.
  16820. @<Process PV or SV@>=
  16821. quint16 value;
  16822. char *valueBytes = (char*)&value;
  16823. valueBytes[1] = response.at(3);
  16824. valueBytes[0] = response.at(4);
  16825. double valueOut = (double)value;
  16826. for(int i = 0; i < decimalPosition; i++)
  16827. {
  16828. valueOut /= 10;
  16829. }
  16830. if(!unitIsF)
  16831. {
  16832. valueOut = valueOut * 9 / 5 + 32;
  16833. }
  16834. if(!svenabled)
  16835. {
  16836. Measurement vm(valueOut, time, Units::Fahrenheit);
  16837. channels.at(0)->input(vm);
  16838. }
  16839. else
  16840. {
  16841. if(readingsv)
  16842. {
  16843. Measurement pvm(savedpv, time, Units::Fahrenheit);
  16844. Measurement svm(valueOut, time, Units::Fahrenheit);
  16845. channels.at(0)->input(pvm);
  16846. channels.at(1)->input(svm);
  16847. readingsv = false;
  16848. }
  16849. else
  16850. {
  16851. savedpv = valueOut;
  16852. readingsv = true;
  16853. }
  16854. }
  16855. @ The destructor should close the port.
  16856. @<ModbusRTUDevice implementation@>=
  16857. ModbusRTUDevice::~ModbusRTUDevice()
  16858. {
  16859. commTimeout->stop();
  16860. messageDelayTimer->stop();
  16861. port->close();
  16862. }
  16863. @ When data is available it should be read into a buffer. The start of the
  16864. buffer should always be the start of a response and there should never be
  16865. more than one response in the buffer at a time. It is, however, likely that
  16866. this buffer will have incomplete data. This means that we must determine when
  16867. the full response is available before passing the complete response along to
  16868. the appropriate method. If the response has not been received in full, nothing
  16869. is done. We'@q'@>ll be notified of more data shortly.
  16870. When the message we see the response for was queued, a callback was also
  16871. registered to handle the response. Once we have the complete message, we pass
  16872. the response along to the callback that was registered for that message,
  16873. remove the message and callback information from the message queue, and start
  16874. a timer which will trigger sending the next message after a safe amount of
  16875. time has passed.
  16876. If a response is received with an invalid CRC, we do not pass that message
  16877. out. Instead, the message handling queues are kept as they are and the previous
  16878. command will be sent again once the message delay timer is finished.
  16879. @<ModbusRTUDevice implementation@>=
  16880. void ModbusRTUDevice::dataAvailable()
  16881. {
  16882. if(messageDelayTimer->isActive())
  16883. {
  16884. messageDelayTimer->stop();
  16885. }
  16886. responseBuffer.append(port->readAll());
  16887. @<Check Modbus RTU message size@>@;
  16888. commTimeout->stop();
  16889. if(calculateCRC(responseBuffer) == 0)
  16890. {
  16891. QObject *object = retObjQueue.at(0);
  16892. char *method = callbackQueue.at(0);
  16893. QMetaMethod metamethod = @| object->metaObject()->
  16894. method(object->metaObject()->
  16895. indexOfMethod(@|QMetaObject::normalizedSignature(method)));
  16896. metamethod.invoke(object, Qt::QueuedConnection,
  16897. Q_ARG(QByteArray, responseBuffer));
  16898. messageQueue.removeAt(0);
  16899. retObjQueue.removeAt(0);
  16900. callbackQueue.removeAt(0);
  16901. }
  16902. else
  16903. {
  16904. qDebug() << "CRC failed";
  16905. }
  16906. messageDelayTimer->start(delayTime);
  16907. waiting = @[false@];
  16908. responseBuffer.clear();
  16909. }
  16910. @ In Modbus RTU, a response message starts with one byte identifying the device
  16911. the message was sent from, one byte indicating the function, a variable number
  16912. of bytes with the response data, and two bytes used to verify that the response
  16913. was correctly received. In the event of a normal response, messages will be at
  16914. least six bytes long, but in the event of an error it is possible for a message
  16915. to be five bytes long.
  16916. Messages with a function number of 0x01 or 0x02 will be 6 bytes in length.
  16917. Messages with a function number of 0x03 or 0x04 will be at least 7 bytes in
  16918. length with the total length determined by the sum of 5 and the value in the
  16919. fifth byte. Messages with a function number of 0x05, 0x06, or 0x10 will be 8
  16920. bytes in length. Messages with a function number greater than 0x80 will be five
  16921. bytes in length.
  16922. @<Check Modbus RTU message size@>=
  16923. if(responseBuffer.size() < 5)
  16924. {
  16925. return;
  16926. }
  16927. switch(responseBuffer.at(1))
  16928. {
  16929. case 0x01:
  16930. case 0x02:
  16931. if(responseBuffer.size() < 6)
  16932. {
  16933. return;
  16934. }
  16935. responseBuffer = responseBuffer.left(6);
  16936. break;
  16937. case 0x03:
  16938. case 0x04:
  16939. if(responseBuffer.size() < 5 + responseBuffer.at(2))
  16940. {
  16941. return;
  16942. }
  16943. responseBuffer = responseBuffer.left(5 + responseBuffer.at(2));
  16944. break;
  16945. case 0x05:
  16946. case 0x06:
  16947. case 0x10:
  16948. if(responseBuffer.size() < 8)
  16949. {
  16950. return;
  16951. }
  16952. responseBuffer = responseBuffer.left(8);
  16953. break;
  16954. }
  16955. @ When sending and receiving messages, it is necessary to calculate a 16 bit
  16956. cyclic redundancy check code. The algorithm used to calculate this is specified
  16957. by the Modbus RTU protocol documentation. When sending a message, |data| should
  16958. be the message to send except for the CRC bytes which will be appended once
  16959. this method calculates them. When receiving a message, passing the complete
  16960. message back through this method should result in a return value of |0|. Any
  16961. other value indicates an error.
  16962. @<ModbusRTUDevice implementation@>=
  16963. quint16 ModbusRTUDevice::calculateCRC(QByteArray data)
  16964. {
  16965. quint16 retval = 0xFFFF;
  16966. int i = 0;
  16967. while(i < data.size())
  16968. {
  16969. retval ^= 0x00FF & (quint16)data.at(i);
  16970. for(int j = 0; j < 8; j++)
  16971. {
  16972. if(retval & 1)
  16973. {
  16974. retval = (retval >> 1) ^ 0xA001;
  16975. }
  16976. else
  16977. {
  16978. retval >>= 1;
  16979. }
  16980. }
  16981. i++;
  16982. }
  16983. return retval;
  16984. }
  16985. @ When preparing an instance of ModbusRTUDevice, several messages may need to
  16986. be sent to the device in order to determine important details such as how
  16987. measurement data should be interpreted. During normal operation, messages
  16988. might be sent interactively between regular messages to acquire data. When
  16989. queueing a message, we also specify an object and method the response should be
  16990. sent to.
  16991. @<ModbusRTUDevice implementation@>=
  16992. void ModbusRTUDevice::queueMessage(QByteArray request, QObject *object,
  16993. const char *callback)
  16994. {
  16995. messageQueue.append(request);
  16996. retObjQueue.append(object);
  16997. callbackQueue.append(const_cast<char*>(callback));
  16998. if(messageQueue.size() == 1 && !(messageDelayTimer->isActive()))
  16999. {
  17000. sendNextMessage();
  17001. }
  17002. }
  17003. void ModbusRTUDevice::sendNextMessage()
  17004. {
  17005. if(messageQueue.size() > 0 && !waiting)
  17006. {
  17007. QByteArray message = messageQueue.at(0);
  17008. quint16 crc = calculateCRC(message);
  17009. char *check = (char*)&crc;
  17010. message.append(check[0]);
  17011. message.append(check[1]);
  17012. port->write(message);
  17013. commTimeout->start(2000);
  17014. messageDelayTimer->start(delayTime);
  17015. waiting = @[true@];
  17016. }
  17017. else
  17018. {
  17019. emit queueEmpty();
  17020. }
  17021. }
  17022. void ModbusRTUDevice::outputSV(double value)
  17023. {
  17024. for(int i = 0; i < decimalPosition; i++)
  17025. {
  17026. value *= 10;
  17027. }
  17028. quint16 outval = (quint16)value;
  17029. QByteArray message(outputSVStub);
  17030. char *valBytes = (char*)&outval;
  17031. message.append(valBytes[1]);
  17032. message.append(valBytes[0]);
  17033. queueMessage(message, this, "ignore(QByteArray)");
  17034. }
  17035. @ We don'@q'@>t care about the response when sending a new SV.
  17036. @<ModbusRTUDevice implementation@>=
  17037. void ModbusRTUDevice::ignore(QByteArray)
  17038. {
  17039. return;
  17040. }
  17041. @ Sometimes a communications failure will occur in which a response to a
  17042. command is never received. To reset communications we set a timer whenever a
  17043. command is sent and stop that once a full response is received. If the timer
  17044. times out, we should clear the response buffer and attempt to re-establish
  17045. communications. Currently this timeout is hard coded at 2 seconds, however
  17046. this should be configurable and smaller values may well be acceptable.
  17047. @<ModbusRTUDevice implementation@>=
  17048. void ModbusRTUDevice::timeout()
  17049. {
  17050. qDebug() << "Communications timeout.";
  17051. responseBuffer.clear();
  17052. waiting = false;
  17053. messageDelayTimer->start();
  17054. }
  17055. @ This class must be exposed to the host environment.
  17056. @<Function prototypes for scripting@>=
  17057. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine);
  17058. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine);
  17059. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine);
  17060. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine);
  17061. @ The host environment is informed of the constructor.
  17062. @<Set up the scripting engine@>=
  17063. constructor = engine->newFunction(constructModbusRTUDevice);
  17064. value = engine->newQMetaObject(&ModbusRTUDevice::staticMetaObject, constructor);
  17065. engine->globalObject().setProperty("ModbusRTUDevice", value);
  17066. @ The constructor takes the configuration model and the index to the device of
  17067. interest as arguments rather than provide a large number of property setters to
  17068. handle initialization.
  17069. @<Functions for scripting@>=
  17070. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine)
  17071. {
  17072. QScriptValue object;
  17073. if(context->argumentCount() == 2)
  17074. {
  17075. object = engine->newQObject(new ModbusRTUDevice(argument<DeviceTreeModel *>(0, context),
  17076. argument<QModelIndex>(1, context)),
  17077. QScriptEngine::ScriptOwnership);
  17078. setModbusRTUDeviceProperties(object, engine);
  17079. }
  17080. else
  17081. {
  17082. context->throwError("Incorrect number of arguments passed to "@|
  17083. "ModbusRTUDevice constructor. This takes the configuration model "@|
  17084. "and an index.");
  17085. }
  17086. return object;
  17087. }
  17088. @ The host environment needs a way to gain access to the channel objects.
  17089. @<Functions for scripting@>=
  17090. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine)
  17091. {
  17092. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  17093. QScriptValue object;
  17094. if(self)
  17095. {
  17096. if(self->channels.size() > 0)
  17097. {
  17098. object = engine->newQObject(self->channels.at(0));
  17099. setChannelProperties(object, engine);
  17100. }
  17101. }
  17102. return object;
  17103. }
  17104. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine)
  17105. {
  17106. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  17107. QScriptValue object;
  17108. if(self)
  17109. {
  17110. if(self->channels.size() > 1)
  17111. {
  17112. object = engine->newQObject(self->channels.at(1));
  17113. setChannelProperties(object, engine);
  17114. }
  17115. }
  17116. return object;
  17117. }
  17118. @ These methods are set as properties when the object is created.
  17119. @<Functions for scripting@>=
  17120. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine)
  17121. {
  17122. setQObjectProperties(value, engine);
  17123. value.setProperty("pVChannel", engine->newFunction(ModbusRTUDevice_pVChannel));
  17124. value.setProperty("sVChannel", engine->newFunction(ModbusRTUDevice_sVChannel));
  17125. }
  17126. @* Modbus RTU device configuration widget.
  17127. \noindent This class was minimally adapted from a prototype implementation to
  17128. use the new configuration system introduced in \pn{} 1.4.
  17129. With all of the custom widgets for specifying a device configuration in place,
  17130. we can proceed to combine these in a form. As all of the options might use more
  17131. screen space than is available we make this scrollable. Some reorganization of
  17132. this will be done prior to release to enable the use of multiple devices on the
  17133. port which may obviate the need for this, but as there are those who prefer to
  17134. have a small screen it may be better to leave the scroll area in place even
  17135. after such a change.
  17136. @<Class declarations@>=
  17137. class ModbusConfigurator : public BasicDeviceConfigurationWidget
  17138. {
  17139. @[Q_OBJECT@]@;
  17140. public:@/
  17141. Q_INVOKABLE@,@, ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index);@/
  17142. @[private slots@]:@/
  17143. void updatePort(const QString &newPort);
  17144. void updateBaudRate(const QString &newRate);
  17145. void updateParity(const QString &newParity);
  17146. void updateFlowControl(const QString &newFlow);
  17147. void updateStopBits(const QString &newStopBits);
  17148. void updateStation(int station);
  17149. void updateFixedDecimal(bool fixed);
  17150. void updateDecimalAddress(int address);
  17151. void updateDecimalPosition(int position);
  17152. void updateFixedUnit(bool fixed);
  17153. void updateUnitAddress(int address);
  17154. void updateValueForF(int value);
  17155. void updateValueForC(int value);
  17156. void updateUnit(const QString &newUnit);
  17157. void updatePVAddress(int address);
  17158. void updateSVEnabled(bool enabled);
  17159. void updateSVReadAddress(int address);
  17160. void updateDeviceLimit(bool query);
  17161. void updateSVLowerAddress(int address);
  17162. void updateSVUpperAddress(int address);
  17163. void updateSVLower(double value);
  17164. void updateSVUpper(double value);
  17165. void updateSVWritable(bool canWriteSV);
  17166. void updateSVWriteAddress(int address);
  17167. void updatePVColumnName(const QString &name);
  17168. void updateSVColumnName(const QString &name);
  17169. void updatePVHidden(bool hidden);
  17170. void updateSVHidden(bool hidden);@/
  17171. private:@/
  17172. PortSelector *port;
  17173. BaudSelector *baud;
  17174. ParitySelector *parity;
  17175. FlowSelector *flow;
  17176. StopSelector *stop;
  17177. QSpinBox *station;
  17178. QCheckBox *decimalQuery;
  17179. ShortHexSpinBox *decimalAddress;
  17180. QSpinBox *decimalPosition;
  17181. QCheckBox *unitQuery;
  17182. ShortHexSpinBox *unitAddress;
  17183. QSpinBox *valueF;
  17184. QSpinBox *valueC;
  17185. QComboBox *fixedUnit;
  17186. ShortHexSpinBox *pVAddress;
  17187. QCheckBox *sVEnabled;
  17188. ShortHexSpinBox *sVReadAddress;
  17189. QCheckBox *deviceLimit;
  17190. ShortHexSpinBox *sVLowerAddr;
  17191. ShortHexSpinBox *sVUpperAddr;
  17192. QDoubleSpinBox *sVLower;
  17193. QDoubleSpinBox *sVUpper;
  17194. QCheckBox *sVWritable;
  17195. ShortHexSpinBox *sVOutputAddr;
  17196. QLineEdit *pVColumnName;
  17197. QLineEdit *sVColumnName;
  17198. };
  17199. @ Implementation.
  17200. @<ModbusConfigurator implementation@>=
  17201. ModbusConfigurator::ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index)
  17202. : BasicDeviceConfigurationWidget(model, index),
  17203. port(new PortSelector), baud(new BaudSelector), parity(new ParitySelector),
  17204. flow(new FlowSelector), stop(new StopSelector), station(new QSpinBox),
  17205. decimalQuery(new QCheckBox(tr("Enable"))),
  17206. decimalAddress(new ShortHexSpinBox), decimalPosition(new QSpinBox),
  17207. unitQuery(new QCheckBox(tr("Enable"))),
  17208. unitAddress(new ShortHexSpinBox), valueF(new QSpinBox),
  17209. valueC(new QSpinBox), fixedUnit(new QComboBox),
  17210. pVAddress(new ShortHexSpinBox),
  17211. sVEnabled(new QCheckBox(tr("Enable"))),
  17212. sVReadAddress(new ShortHexSpinBox),
  17213. deviceLimit(new QCheckBox(tr("Enable"))),
  17214. sVLowerAddr(new ShortHexSpinBox), sVUpperAddr(new ShortHexSpinBox),
  17215. sVLower(new QDoubleSpinBox), sVUpper(new QDoubleSpinBox),
  17216. sVWritable(new QCheckBox(tr("Enable"))),
  17217. sVOutputAddr(new ShortHexSpinBox),
  17218. pVColumnName(new QLineEdit), sVColumnName(new QLineEdit)
  17219. {
  17220. QHBoxLayout *layout = new QHBoxLayout;
  17221. QWidget *form = new QWidget;
  17222. QHBoxLayout *masterLayout = new QHBoxLayout;
  17223. QVBoxLayout *portAndDeviceLayout = new QVBoxLayout;
  17224. QVBoxLayout *seriesLayout = new QVBoxLayout;
  17225. QFormLayout *serialSection = new QFormLayout;
  17226. serialSection->addRow(QString(tr("Port:")), port);
  17227. serialSection->addRow(QString(tr("Baud rate:")), baud);
  17228. serialSection->addRow(QString(tr("Parity:")), parity);
  17229. serialSection->addRow(QString(tr("Flow control:")), flow);
  17230. serialSection->addRow(QString(tr("Stop bits:")), stop);
  17231. QGroupBox *serialSectionBox = new QGroupBox(tr("Serial Port Configuration"));
  17232. serialSectionBox->setLayout(serialSection);
  17233. portAndDeviceLayout->addWidget(serialSectionBox);
  17234. QFormLayout *deviceSection = new QFormLayout;
  17235. station->setMinimum(1);
  17236. station->setMaximum(255);
  17237. decimalPosition->setMinimum(0);
  17238. decimalPosition->setMaximum(9);
  17239. valueF->setMinimum(0);
  17240. valueF->setMaximum(0xFFFF);
  17241. valueC->setMinimum(0);
  17242. valueC->setMaximum(0xFFFF);
  17243. fixedUnit->addItem(tr("Fahrenheit"), QVariant(QString("F")));
  17244. fixedUnit->addItem(tr("Celsius"), QVariant(QString("C")));
  17245. deviceSection->addRow(tr("Station:"), station);
  17246. deviceSection->addRow(tr("Decimal position from device:"), decimalQuery);
  17247. deviceSection->addRow(tr("Decimal position relative address:"), decimalAddress);
  17248. deviceSection->addRow(tr("Fixed decimal position:"), decimalPosition);
  17249. deviceSection->addRow(tr("Measurement unit from device:"), unitQuery);
  17250. deviceSection->addRow(tr("Current unit relative address:"), unitAddress);
  17251. deviceSection->addRow(tr("Value for Fahrenheit:"), valueF);
  17252. deviceSection->addRow(tr("Value for Celsius:"), valueC);
  17253. deviceSection->addRow(tr("Fixed unit:"), fixedUnit);
  17254. QGroupBox *deviceSectionBox = new QGroupBox(tr("Device Configuration"));
  17255. deviceSectionBox->setLayout(deviceSection);
  17256. portAndDeviceLayout->addWidget(deviceSectionBox);
  17257. QFormLayout *pVSection = new QFormLayout;
  17258. pVSection->addRow(tr("Value relative address:"), pVAddress);
  17259. pVSection->addRow(tr("PV column name:"), pVColumnName);
  17260. QCheckBox *pVHideBox = new QCheckBox(tr("Hide this channel"));
  17261. pVSection->addRow(pVHideBox);
  17262. QGroupBox *processValueBox = new QGroupBox(tr("Process Value"));
  17263. processValueBox->setLayout(pVSection);
  17264. seriesLayout->addWidget(processValueBox);
  17265. QFormLayout *sVSection = new QFormLayout;
  17266. sVLower->setDecimals(1);
  17267. sVLower->setMinimum(0.0);
  17268. sVLower->setMaximum(999.9);
  17269. sVUpper->setDecimals(1);
  17270. sVUpper->setMinimum(0.0);
  17271. sVUpper->setMaximum(999.9);
  17272. sVSection->addRow(tr("Set value:"), sVEnabled);
  17273. sVSection->addRow(tr("Read relative address:"), sVReadAddress);
  17274. sVSection->addRow(tr("SV column name:"), sVColumnName);
  17275. sVSection->addRow(tr("Limits from device:"), deviceLimit);
  17276. sVSection->addRow(tr("Lower limit relative address:"), sVLowerAddr);
  17277. sVSection->addRow(tr("Upper limit relative address:"), sVUpperAddr);
  17278. sVSection->addRow(tr("Lower limit:"), sVLower);
  17279. sVSection->addRow(tr("Upper limit:"), sVUpper);
  17280. sVSection->addRow(tr("Output set value:"), sVWritable);
  17281. sVSection->addRow(tr("Output relative address:"), sVOutputAddr);
  17282. QCheckBox *sVHideBox = new QCheckBox(tr("Hide this channel"));
  17283. sVSection->addRow(sVHideBox);
  17284. QGroupBox *setValueBox = new QGroupBox(tr("Set Value"));
  17285. setValueBox->setLayout(sVSection);
  17286. seriesLayout->addWidget(setValueBox);
  17287. masterLayout->addLayout(portAndDeviceLayout);
  17288. masterLayout->addLayout(seriesLayout);
  17289. form->setLayout(masterLayout);
  17290. @<Get device configuration data for current node@>@;
  17291. for(int i = 0; i < configData.size(); i++)
  17292. {
  17293. node = configData.at(i).toElement();
  17294. if(node.attribute("name") == "port")
  17295. {
  17296. QString portname = node.attribute("value");
  17297. int idx = port->findText(portname);
  17298. if(idx >= 0)
  17299. {
  17300. port->setCurrentIndex(idx);
  17301. }
  17302. else
  17303. {
  17304. port->addItem(portname);
  17305. }
  17306. }
  17307. else if(node.attribute("name") == "baud")
  17308. {
  17309. baud->setCurrentIndex(baud->findText(node.attribute("value")));
  17310. }
  17311. else if(node.attribute("name") == "parity")
  17312. {
  17313. parity->setCurrentIndex(parity->findData(node.attribute("value")));
  17314. }
  17315. else if(node.attribute("name") == "flow")
  17316. {
  17317. flow->setCurrentIndex(flow->findData(node.attribute("value")));
  17318. }
  17319. else if(node.attribute("name") == "stop")
  17320. {
  17321. stop->setCurrentIndex(stop->findData(node.attribute("value")));
  17322. }
  17323. else if(node.attribute("name") == "station")
  17324. {
  17325. station->setValue(node.attribute("value").toInt());
  17326. }
  17327. else if(node.attribute("name") == "decimalQuery")
  17328. {
  17329. if(node.attribute("value") == "true")
  17330. {
  17331. decimalQuery->setChecked(true);
  17332. }
  17333. else
  17334. {
  17335. decimalQuery->setChecked(false);
  17336. }
  17337. }
  17338. else if(node.attribute("name") == "decimalAddress")
  17339. {
  17340. decimalAddress->setValue(node.attribute("value").toInt());
  17341. }
  17342. else if(node.attribute("name") == "decimalPosition")
  17343. {
  17344. decimalPosition->setValue(node.attribute("value").toInt());
  17345. }
  17346. else if(node.attribute("name") == "unitQuery")
  17347. {
  17348. if(node.attribute("value") == "true")
  17349. {
  17350. unitQuery->setChecked(true);
  17351. }
  17352. else
  17353. {
  17354. unitQuery->setChecked(false);
  17355. }
  17356. }
  17357. else if(node.attribute("name") == "unitAddress")
  17358. {
  17359. unitAddress->setValue(node.attribute("value").toInt());
  17360. }
  17361. else if(node.attribute("name") == "valueF")
  17362. {
  17363. valueF->setValue(node.attribute("value").toInt());
  17364. }
  17365. else if(node.attribute("name") == "valueC")
  17366. {
  17367. valueC->setValue(node.attribute("value").toInt());
  17368. }
  17369. else if(node.attribute("name") == "fixedUnit")
  17370. {
  17371. fixedUnit->setCurrentIndex(fixedUnit->findText(node.attribute("value")));
  17372. }
  17373. else if(node.attribute("name") == "pVAddress")
  17374. {
  17375. pVAddress->setValue(node.attribute("value").toInt());
  17376. }
  17377. else if(node.attribute("name") == "sVEnabled")
  17378. {
  17379. if(node.attribute("value") == "true")
  17380. {
  17381. sVEnabled->setChecked(true);
  17382. }
  17383. else
  17384. {
  17385. sVEnabled->setChecked(false);
  17386. }
  17387. }
  17388. else if(node.attribute("name") == "sVReadAddress")
  17389. {
  17390. sVReadAddress->setValue(node.attribute("value").toInt());
  17391. }
  17392. else if(node.attribute("name") == "deviceLimit")
  17393. {
  17394. if(node.attribute("value") == "true")
  17395. {
  17396. deviceLimit->setChecked(true);
  17397. }
  17398. else
  17399. {
  17400. deviceLimit->setChecked(false);
  17401. }
  17402. }
  17403. else if(node.attribute("name") == "sVLowerAddr")
  17404. {
  17405. sVLowerAddr->setValue(node.attribute("value").toInt());
  17406. }
  17407. else if(node.attribute("name") == "sVUpperAddr")
  17408. {
  17409. sVUpperAddr->setValue(node.attribute("value").toInt());
  17410. }
  17411. else if(node.attribute("name") == "sVLower")
  17412. {
  17413. sVLower->setValue(node.attribute("value").toDouble());
  17414. }
  17415. else if(node.attribute("name") == "sVUpper")
  17416. {
  17417. sVUpper->setValue(node.attribute("value").toDouble());
  17418. }
  17419. else if(node.attribute("name") == "sVWritable")
  17420. {
  17421. if(node.attribute("value") == "true")
  17422. {
  17423. sVWritable->setChecked(true);
  17424. }
  17425. else
  17426. {
  17427. sVWritable->setChecked(false);
  17428. }
  17429. }
  17430. else if(node.attribute("name") == "sVOutputAddr")
  17431. {
  17432. sVOutputAddr->setValue(node.attribute("value").toInt());
  17433. }
  17434. else if(node.attribute("name") == "pvcolname")
  17435. {
  17436. pVColumnName->setText(node.attribute("value"));
  17437. }
  17438. else if(node.attribute("name") == "svcolname")
  17439. {
  17440. sVColumnName->setText(node.attribute("value"));
  17441. }
  17442. else if(node.attribute("name") == "pvhidden")
  17443. {
  17444. pVHideBox->setChecked(node.attribute("value") == "true");
  17445. }
  17446. else if(node.attribute("name") == "svhidden")
  17447. {
  17448. sVHideBox->setChecked(node.attribute("value") == "true");
  17449. }
  17450. }
  17451. updatePort(port->currentText());
  17452. updateBaudRate(baud->currentText());
  17453. updateParity(parity->itemData(parity->currentIndex()).toString());
  17454. updateFlowControl(flow->itemData(flow->currentIndex()).toString());
  17455. updateStopBits(stop->itemData(stop->currentIndex()).toString());
  17456. updateStation(station->value());
  17457. updateFixedDecimal(decimalQuery->isChecked());
  17458. updateDecimalAddress(decimalAddress->value());
  17459. updateDecimalPosition(decimalPosition->value());
  17460. updateFixedUnit(unitQuery->isChecked());
  17461. updateUnitAddress(unitAddress->value());
  17462. updateValueForF(valueF->value());
  17463. updateValueForC(valueC->value());
  17464. updateUnit(fixedUnit->currentText());
  17465. updatePVAddress(pVAddress->value());
  17466. updateSVEnabled(sVEnabled->isChecked());
  17467. updateSVReadAddress(sVReadAddress->value());
  17468. updateDeviceLimit(deviceLimit->isChecked());
  17469. updateSVLowerAddress(sVLowerAddr->value());
  17470. updateSVUpperAddress(sVUpperAddr->value());
  17471. updateSVLower(sVLower->value());
  17472. updateSVUpper(sVUpper->value());
  17473. updateSVWritable(sVWritable->isChecked());
  17474. updateSVWriteAddress(sVOutputAddr->value());
  17475. updatePVColumnName(pVColumnName->text());
  17476. updateSVColumnName(sVColumnName->text());
  17477. updatePVHidden(pVHideBox->isChecked());
  17478. updateSVHidden(sVHideBox->isChecked());
  17479. connect(port, SIGNAL(currentIndexChanged(QString)), this, SLOT(updatePort(QString)));
  17480. connect(port, SIGNAL(editTextChanged(QString)), this, SLOT(updatePort(QString)));
  17481. connect(baud, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateBaudRate(QString)));
  17482. connect(parity, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateParity(QString)));
  17483. connect(flow, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateFlowControl(QString)));
  17484. connect(stop, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateStopBits(QString)));
  17485. connect(station, SIGNAL(valueChanged(int)), this, SLOT(updateStation(int)));
  17486. connect(decimalQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedDecimal(bool)));
  17487. connect(decimalAddress, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalAddress(int)));
  17488. connect(decimalPosition, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalPosition(int)));
  17489. connect(unitQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedUnit(bool)));
  17490. connect(unitAddress, SIGNAL(valueChanged(int)), this, SLOT(updateUnitAddress(int)));
  17491. connect(valueF, SIGNAL(valueChanged(int)), this, SLOT(updateValueForF(int)));
  17492. connect(valueC, SIGNAL(valueChanged(int)), this, SLOT(updateValueForC(int)));
  17493. connect(fixedUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateUnit(QString)));
  17494. connect(pVAddress, SIGNAL(valueChanged(int)), this, SLOT(updatePVAddress(int)));
  17495. connect(sVEnabled, SIGNAL(toggled(bool)), this, SLOT(updateSVEnabled(bool)));
  17496. connect(sVReadAddress, SIGNAL(valueChanged(int)), this, SLOT(updateSVReadAddress(int)));
  17497. connect(deviceLimit, SIGNAL(toggled(bool)), this, SLOT(updateDeviceLimit(bool)));
  17498. connect(sVLowerAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVLowerAddress(int)));
  17499. connect(sVUpperAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVUpperAddress(int)));
  17500. connect(sVLower, SIGNAL(valueChanged(double)), this, SLOT(updateSVLower(double)));
  17501. connect(sVUpper, SIGNAL(valueChanged(double)), this, SLOT(updateSVUpper(double)));
  17502. connect(sVWritable, SIGNAL(toggled(bool)), this, SLOT(updateSVWritable(bool)));
  17503. connect(sVOutputAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVWriteAddress(int)));
  17504. connect(pVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updatePVColumnName(QString)));
  17505. connect(sVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updateSVColumnName(QString)));
  17506. connect(pVHideBox, SIGNAL(toggled(bool)), this, SLOT(updatePVHidden(bool)));
  17507. connect(sVHideBox, SIGNAL(toggled(bool)), this, SLOT(updateSVHidden(bool)));
  17508. layout->addWidget(form);
  17509. setLayout(layout);
  17510. }
  17511. void ModbusConfigurator::updatePort(const QString &newPort)
  17512. {
  17513. updateAttribute("port", newPort);
  17514. }
  17515. void ModbusConfigurator::updateBaudRate(const QString &newRate)
  17516. {
  17517. updateAttribute("baud", newRate);
  17518. }
  17519. void ModbusConfigurator::updateParity(const QString &)
  17520. {
  17521. updateAttribute("parity", parity->itemData(parity->currentIndex()).toString());
  17522. }
  17523. void ModbusConfigurator::updateFlowControl(const QString &)
  17524. {
  17525. updateAttribute("flow", flow->itemData(flow->currentIndex()).toString());
  17526. }
  17527. void ModbusConfigurator::updateStopBits(const QString &)
  17528. {
  17529. updateAttribute("stop", stop->itemData(stop->currentIndex()).toString());
  17530. }
  17531. void ModbusConfigurator::updateStation(int station)
  17532. {
  17533. updateAttribute("station", QString("%1").arg(station));
  17534. }
  17535. void ModbusConfigurator::updateFixedDecimal(bool fixed)
  17536. {
  17537. updateAttribute("decimalQuery", fixed ? "true" : "false");
  17538. }
  17539. void ModbusConfigurator::updateDecimalAddress(int address)
  17540. {
  17541. updateAttribute("decimalAddress", QString("%1").arg(address));
  17542. }
  17543. void ModbusConfigurator::updateDecimalPosition(int position)
  17544. {
  17545. updateAttribute("decimalPosition", QString("%1").arg(position));
  17546. }
  17547. void ModbusConfigurator::updateFixedUnit(bool fixed)
  17548. {
  17549. updateAttribute("unitQuery", fixed ? "true" : "false");
  17550. }
  17551. void ModbusConfigurator::updateUnitAddress(int address)
  17552. {
  17553. updateAttribute("unitAddress", QString("%1").arg(address));
  17554. }
  17555. void ModbusConfigurator::updateValueForF(int value)
  17556. {
  17557. updateAttribute("valueF", QString("%1").arg(value));
  17558. }
  17559. void ModbusConfigurator::updateValueForC(int value)
  17560. {
  17561. updateAttribute("valueC", QString("%1").arg(value));
  17562. }
  17563. void ModbusConfigurator::updateUnit(const QString &newUnit)
  17564. {
  17565. updateAttribute("fixedUnit", newUnit);
  17566. }
  17567. void ModbusConfigurator::updatePVAddress(int address)
  17568. {
  17569. updateAttribute("pVAddress", QString("%1").arg(address));
  17570. }
  17571. void ModbusConfigurator::updateSVEnabled(bool enabled)
  17572. {
  17573. updateAttribute("sVEnabled", enabled ? "true" : "false");
  17574. }
  17575. void ModbusConfigurator::updateSVReadAddress(int address)
  17576. {
  17577. updateAttribute("sVReadAddress", QString("%1").arg(address));
  17578. }
  17579. void ModbusConfigurator::updateDeviceLimit(bool query)
  17580. {
  17581. updateAttribute("deviceLimit", query ? "true" : "false");
  17582. }
  17583. void ModbusConfigurator::updateSVLowerAddress(int address)
  17584. {
  17585. updateAttribute("sVLowerAddr", QString("%1").arg(address));
  17586. }
  17587. void ModbusConfigurator::updateSVUpperAddress(int address)
  17588. {
  17589. updateAttribute("sVUpperAddr", QString("%1").arg(address));
  17590. }
  17591. void ModbusConfigurator::updateSVLower(double value)
  17592. {
  17593. updateAttribute("sVLower", QString("%1").arg(value));
  17594. }
  17595. void ModbusConfigurator::updateSVUpper(double value)
  17596. {
  17597. updateAttribute("sVUpper", QString("%1").arg(value));
  17598. }
  17599. void ModbusConfigurator::updateSVWritable(bool canWriteSV)
  17600. {
  17601. updateAttribute("sVWritable", canWriteSV ? "true" : "false");
  17602. }
  17603. void ModbusConfigurator::updateSVWriteAddress(int address)
  17604. {
  17605. updateAttribute("sVOutputAddr", QString("%1").arg(address));
  17606. }
  17607. void ModbusConfigurator::updatePVColumnName(const QString &name)
  17608. {
  17609. updateAttribute("pvcolname", name);
  17610. }
  17611. void ModbusConfigurator::updateSVColumnName(const QString &name)
  17612. {
  17613. updateAttribute("svcolname", name);
  17614. }
  17615. void ModbusConfigurator::updatePVHidden(bool hidden)
  17616. {
  17617. updateAttribute("pvhidden", hidden ? "true" : "false");
  17618. }
  17619. void ModbusConfigurator::updateSVHidden(bool hidden)
  17620. {
  17621. updateAttribute("svhidden", hidden ? "true" : "false");
  17622. }
  17623. @ This is registered with the configuration system.
  17624. @<Register device configuration widgets@>=
  17625. app.registerDeviceConfigurationWidget("modbusrtu", ModbusConfigurator::staticMetaObject);
  17626. @ A |NodeInserter| for the driver configuration widget is also needed.
  17627. @<Register top level device configuration nodes@>=
  17628. inserter = new NodeInserter(tr("Modbus RTU Device"), tr("Modbus RTU Device"), "modbusrtu", NULL);
  17629. topLevelNodeInserters.append(inserter);
  17630. @i modbus.w
  17631. @i unsupportedserial.w
  17632. @i phidgets.w
  17633. @i phidget22.w
  17634. @* Configuration widget for a calibrated data series.
  17635. \noindent This control is used for adding a |LinearSplineInterpolator| to the
  17636. logging view.
  17637. @<Class declarations@>=
  17638. class LinearSplineInterpolationConfWidget : public BasicDeviceConfigurationWidget
  17639. {
  17640. @[Q_OBJECT@]@/
  17641. public:@/
  17642. @[Q_INVOKABLE@]@, LinearSplineInterpolationConfWidget(DeviceTreeModel *model,
  17643. const QModelIndex &index);
  17644. @[private slots@]:@/
  17645. void updateSourceColumn(const QString &source);
  17646. void updateDestinationColumn(const QString &dest);
  17647. void updateKnots();
  17648. private:@/
  17649. SaltModel *tablemodel;
  17650. };
  17651. @ This is configured by specifying a source column name, a destination column
  17652. name, and a two column table. Note that while we only have one widget handling
  17653. the mapping data, we store each column of the table in its own attribute.
  17654. @<LinearSplineInterpolationConfWidget implementation@>=
  17655. LinearSplineInterpolationConfWidget::LinearSplineInterpolationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  17656. : BasicDeviceConfigurationWidget(model, index), tablemodel(new SaltModel(2))
  17657. {
  17658. QFormLayout *layout = new QFormLayout;
  17659. QLineEdit *source = new QLineEdit;
  17660. layout->addRow(tr("Source column name:"), source);
  17661. QLineEdit *destination = new QLineEdit;
  17662. layout->addRow(tr("Destination column name:"), destination);
  17663. tablemodel->setHeaderData(0, Qt::Horizontal, "Input");
  17664. tablemodel->setHeaderData(1, Qt::Horizontal, "Output");
  17665. QTableView *mappingTable = new QTableView;
  17666. mappingTable->setModel(tablemodel);
  17667. NumericDelegate *delegate = new NumericDelegate;
  17668. mappingTable->setItemDelegate(delegate);
  17669. layout->addRow(tr("Mapping data:"), mappingTable);
  17670. @<Get device configuration data for current node@>@;
  17671. for(int i = 0; i < configData.size(); i++)
  17672. {
  17673. node = configData.at(i).toElement();
  17674. if(node.attribute("name") == "source")
  17675. {
  17676. source->setText(node.attribute("value"));
  17677. }
  17678. else if(node.attribute("name") == "destination")
  17679. {
  17680. destination->setText(node.attribute("value"));
  17681. }
  17682. else if(node.attribute("name") == "sourcevalues")
  17683. {
  17684. @<Convert numeric array literal to list@>@;
  17685. int column = 0;
  17686. @<Populate model column from list@>@;
  17687. }
  17688. else if(node.attribute("name") == "destinationvalues")
  17689. {
  17690. @<Convert numeric array literal to list@>@;
  17691. int column = 1;
  17692. @<Populate model column from list@>@;
  17693. }
  17694. }
  17695. updateSourceColumn(source->text());
  17696. updateDestinationColumn(destination->text());
  17697. updateKnots();
  17698. connect(source, SIGNAL(textEdited(QString)), this, SLOT(updateSourceColumn(QString)));
  17699. connect(destination, SIGNAL(textEdited(QString)), this, SLOT(updateDestinationColumn(QString)));
  17700. connect(tablemodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateKnots()));
  17701. setLayout(layout);
  17702. }
  17703. @ The saved data will have come from a previous call to
  17704. |SaltModel::arrayLiteral()| to repopulate the model we need to strip off the
  17705. the start and end of the strings and split them back into separate elements.
  17706. @<Convert numeric array literal to list@>=
  17707. QString data = node.attribute("value");
  17708. if(data.length() > 3)
  17709. {
  17710. data.chop(2);
  17711. data = data.remove(0, 2);
  17712. }
  17713. QStringList itemList = data.split(",");
  17714. @ Once the saved string has been split, the values can be inserted into the
  17715. model.
  17716. @<Populate model column from list@>=
  17717. for(int j = 0; j < itemList.size(); j++)
  17718. {
  17719. tablemodel->setData(tablemodel->index(j, column),
  17720. QVariant(itemList.at(j).toDouble()),
  17721. Qt::DisplayRole);
  17722. }
  17723. @ When data in the table is changed we simply overwrite any previously saved
  17724. data with the current data.
  17725. @<LinearSplineInterpolationConfWidget implementation@>=
  17726. void LinearSplineInterpolationConfWidget::updateKnots()
  17727. {
  17728. updateAttribute("sourcevalues", tablemodel->arrayLiteral(0, Qt::DisplayRole));
  17729. updateAttribute("destinationvalues", tablemodel->arrayLiteral(1, Qt::DisplayRole));
  17730. }
  17731. void LinearSplineInterpolationConfWidget::updateSourceColumn(const QString &source)
  17732. {
  17733. updateAttribute("source", source);
  17734. }
  17735. void LinearSplineInterpolationConfWidget::updateDestinationColumn(const QString &dest)
  17736. {
  17737. updateAttribute("destination", dest);
  17738. }
  17739. @ The widget is registered with the configuration system.
  17740. @<Register device configuration widgets@>=
  17741. app.registerDeviceConfigurationWidget("linearspline", LinearSplineInterpolationConfWidget::staticMetaObject);
  17742. @* Additional Timers.
  17743. \noindent \pn{} 1.6.4 adds support for more timer indicators than just the
  17744. default batch timer. Three new timer types are supported. The first is a
  17745. cooling timer. This is a timer that is initially set to 0, but at the end of a
  17746. batch this is set to a configured time and starts counting down. There are no
  17747. data logging requirements and this is purely a convenience feature, but one
  17748. that supports product and personnel safety best practices as it helps to
  17749. eliminate the practice of a person reaching into the cooling tray as it
  17750. agitates to test if the coffee has cooled.
  17751. @<Class declarations@>=
  17752. class CoolingTimerConfWidget : public BasicDeviceConfigurationWidget
  17753. {
  17754. @[Q_OBJECT@]@/
  17755. public:@/
  17756. @[Q_INVOKABLE@]@, CoolingTimerConfWidget(DeviceTreeModel *model,
  17757. const QModelIndex &index);
  17758. @[private slots@]:@/
  17759. void updateResetTime(QTime time);
  17760. };
  17761. @ The only configurable detail is the vaue the timer should reset to. For this
  17762. a |QTimeEdit| is fine.
  17763. @<CoolingTimerConfWidget implementation@>=
  17764. CoolingTimerConfWidget::CoolingTimerConfWidget(DeviceTreeModel *model,
  17765. const QModelIndex &index)
  17766. : BasicDeviceConfigurationWidget(model, index)
  17767. {
  17768. QHBoxLayout *layout = new QHBoxLayout;
  17769. QLabel *label = new QLabel(tr("Cooling Time: "));
  17770. QTimeEdit *editor = new QTimeEdit;
  17771. editor->setDisplayFormat("mm:ss");
  17772. @<Get device configuration data for current node@>@;
  17773. for(int i = 0; i < configData.size(); i++)
  17774. {
  17775. node = configData.at(i).toElement();
  17776. if(node.attribute("name") == "reset")
  17777. {
  17778. editor->setTime(QTime::fromString(node.attribute("value"), "mm:ss"));
  17779. }
  17780. }
  17781. updateResetTime(editor->time());
  17782. connect(editor, SIGNAL(timeChanged(QTime)),
  17783. this, SLOT(updateResetTime(QTime)));
  17784. layout->addWidget(label);
  17785. layout->addWidget(editor);
  17786. setLayout(layout);
  17787. }
  17788. void CoolingTimerConfWidget::updateResetTime(QTime time)
  17789. {
  17790. updateAttribute("reset", time.toString("mm:ss"));
  17791. }
  17792. @ The widget is registered with the configuration system.
  17793. @<Register device configuration widgets@>=
  17794. app.registerDeviceConfigurationWidget("coolingtimer",
  17795. CoolingTimerConfWidget::staticMetaObject);
  17796. @ The implementation chunk for now is in the main source file.
  17797. @<Class implementations@>=
  17798. @<CoolingTimerConfWidget implementation@>
  17799. @ The other two timer types are intended for measuring ranges of interest
  17800. within a batch. These have more configuration options. First is the range
  17801. timer. Someone setting this up needs to decide how the timer is started.
  17802. Sensible options include starting the timer at the start of the batch,
  17803. starting the timer when a button is pressed, or starting the timer when a set
  17804. point is reached on the ascent of a named data series. Stopping the timer is
  17805. also a configurable concern. This will be stopped at the end of the batch,
  17806. but it might be stopped sooner on reaching some threshold or when a button is
  17807. pressed. There are also questions of how the information is persisted with the
  17808. roasting records.
  17809. @<Class declarations@>=
  17810. class RangeTimerConfWidget : public BasicDeviceConfigurationWidget
  17811. {
  17812. @[Q_OBJECT@]@;
  17813. public:@/
  17814. @[Q_INVOKABLE@]@, RangeTimerConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  17815. @[private slots@]:@/
  17816. void updateStartButtonText(const QString &text);
  17817. void updateStopButtonText(const QString &text);
  17818. void updateStartColumnName(const QString &text);
  17819. void updateStopColumnName(const QString &text);
  17820. void updateStartValue(const QString &text);
  17821. void updateStopValue(const QString &text);
  17822. void updateStartTrigger(int option);
  17823. void updateStopTrigger(int option);
  17824. };
  17825. @ The constructor sets up controls for configuring these details.
  17826. @<RangeTimerConfWidget implementation@>=
  17827. RangeTimerConfWidget::RangeTimerConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  17828. : BasicDeviceConfigurationWidget(model, index)
  17829. {
  17830. QVBoxLayout *layout = new QVBoxLayout;
  17831. QGroupBox *startConfigurationGroup = new QGroupBox(tr("Start trigger"));
  17832. QRadioButton *startBatchOption = new QRadioButton(tr("Start of batch"));
  17833. QRadioButton *buttonOption = new QRadioButton(tr("Manual"));
  17834. QRadioButton *thresholdOption = new QRadioButton(tr("At temperature"));
  17835. QButtonGroup *startOptionGroup = new QButtonGroup;
  17836. startOptionGroup->addButton(startBatchOption, 1);
  17837. startOptionGroup->addButton(buttonOption, 2);
  17838. startOptionGroup->addButton(thresholdOption, 3);
  17839. startBatchOption->setChecked(true);
  17840. QGridLayout *startOptions = new QGridLayout;
  17841. startOptions->addWidget(startBatchOption, 0, 0);
  17842. startOptions->addWidget(buttonOption, 1, 0);
  17843. startOptions->addWidget(thresholdOption, 2, 0);
  17844. QLabel *buttonTextLabel = new QLabel(tr("Button Text: "));
  17845. QLineEdit *buttonTextEdit = new QLineEdit;
  17846. QHBoxLayout *buttonTextOptions = new QHBoxLayout;
  17847. buttonTextOptions->addWidget(buttonTextLabel);
  17848. buttonTextOptions->addWidget(buttonTextEdit);
  17849. startOptions->addLayout(buttonTextOptions, 1, 1);
  17850. QFormLayout *thresholdOptions = new QFormLayout;
  17851. QLineEdit *startColumnName = new QLineEdit;
  17852. QLineEdit *startValue = new QLineEdit;
  17853. thresholdOptions->addRow(tr("Column Name: "), startColumnName);
  17854. thresholdOptions->addRow(tr("Value: "), startValue);
  17855. startOptions->addLayout(thresholdOptions, 2, 1);
  17856. startConfigurationGroup->setLayout(startOptions);
  17857. layout->addWidget(startConfigurationGroup);
  17858. QGroupBox *stopConfigurationGroup = new QGroupBox(tr("Stop trigger"));
  17859. QRadioButton *stopBatchOption = new QRadioButton(tr("End of batch"));
  17860. QRadioButton *stopButtonOption = new QRadioButton(tr("Manual"));
  17861. QRadioButton *stopThresholdOption = new QRadioButton(tr("At temperature"));
  17862. QButtonGroup *stopOptionGroup = new QButtonGroup;
  17863. stopOptionGroup->addButton(stopBatchOption, 1);
  17864. stopOptionGroup->addButton(stopButtonOption, 2);
  17865. stopOptionGroup->addButton(stopThresholdOption, 3);
  17866. stopBatchOption->setChecked(true);
  17867. QGridLayout *stopOptions = new QGridLayout;
  17868. stopOptions->addWidget(stopBatchOption, 0, 0);
  17869. stopOptions->addWidget(stopButtonOption, 1, 0);
  17870. stopOptions->addWidget(stopThresholdOption, 2, 0);
  17871. QLabel *stopButtonLabel = new QLabel(tr("Button Text: "));
  17872. QLineEdit *stopButtonEdit = new QLineEdit;
  17873. QHBoxLayout *stopButtonTextOptions = new QHBoxLayout;
  17874. stopButtonTextOptions->addWidget(stopButtonLabel);
  17875. stopButtonTextOptions->addWidget(stopButtonEdit);
  17876. stopOptions->addLayout(stopButtonTextOptions, 1, 1);
  17877. QLineEdit *stopColumnName = new QLineEdit;
  17878. QLineEdit *stopValue = new QLineEdit;
  17879. QFormLayout *stopThresholdOptions = new QFormLayout;
  17880. stopThresholdOptions->addRow(tr("Column Name: "), stopColumnName);
  17881. stopThresholdOptions->addRow(tr("Value: "), stopValue);
  17882. stopOptions->addLayout(stopThresholdOptions, 2, 1);
  17883. stopConfigurationGroup->setLayout(stopOptions);
  17884. layout->addWidget(stopConfigurationGroup);
  17885. @<Get device configuration data for current node@>@;
  17886. for(int i = 0; i < configData.size(); i++)
  17887. {
  17888. node = configData.at(i).toElement();
  17889. if(node.attribute("name") == "startbuttontext")
  17890. {
  17891. buttonTextEdit->setText(node.attribute("value"));
  17892. }
  17893. else if(node.attribute("name") == "stopbuttontext")
  17894. {
  17895. stopButtonEdit->setText(node.attribute("value"));
  17896. }
  17897. else if(node.attribute("name") == "startcolumnname")
  17898. {
  17899. startColumnName->setText(node.attribute("value"));
  17900. }
  17901. else if(node.attribute("name") == "stopcolumnname")
  17902. {
  17903. stopColumnName->setText(node.attribute("value"));
  17904. }
  17905. else if(node.attribute("name") == "startvalue")
  17906. {
  17907. startValue->setText(node.attribute("value"));
  17908. }
  17909. else if(node.attribute("name") == "stopvalue")
  17910. {
  17911. stopValue->setText(node.attribute("value"));
  17912. }
  17913. else if(node.attribute("name") == "starttrigger")
  17914. {
  17915. if(node.attribute("value") == "batch")
  17916. {
  17917. startBatchOption->setChecked(true);
  17918. }
  17919. else if(node.attribute("value") == "manual")
  17920. {
  17921. buttonOption->setChecked(true);
  17922. }
  17923. else if(node.attribute("value") == "value")
  17924. {
  17925. thresholdOption->setChecked(true);
  17926. }
  17927. }
  17928. else if(node.attribute("name") == "stoptrigger")
  17929. {
  17930. if(node.attribute("value") == "batch")
  17931. {
  17932. stopBatchOption->setChecked(true);
  17933. }
  17934. else if(node.attribute("value") == "manual")
  17935. {
  17936. stopButtonOption->setChecked(true);
  17937. }
  17938. else if(node.attribute("value") == "value")
  17939. {
  17940. stopThresholdOption->setChecked(true);
  17941. }
  17942. }
  17943. }
  17944. updateStartButtonText(buttonTextEdit->text());
  17945. updateStopButtonText(stopButtonEdit->text());
  17946. updateStartColumnName(startColumnName->text());
  17947. updateStopColumnName(stopColumnName->text());
  17948. updateStartValue(startValue->text());
  17949. updateStopValue(stopValue->text());
  17950. updateStartTrigger(startOptionGroup->checkedId());
  17951. updateStopTrigger(stopOptionGroup->checkedId());
  17952. setLayout(layout);
  17953. connect(buttonTextEdit, SIGNAL(textChanged(QString)),
  17954. this, SLOT(updateStartButtonText(QString)));
  17955. connect(stopButtonEdit, SIGNAL(textChanged(QString)),
  17956. this, SLOT(updateStopButtonText(QString)));
  17957. connect(startColumnName, SIGNAL(textChanged(QString)),
  17958. this, SLOT(updateStartColumnName(QString)));
  17959. connect(stopColumnName, SIGNAL(textChanged(QString)),
  17960. this, SLOT(updateStopColumnName(QString)));
  17961. connect(startValue, SIGNAL(textChanged(QString)),
  17962. this, SLOT(updateStartValue(QString)));
  17963. connect(stopValue, SIGNAL(textChanged(QString)),
  17964. this, SLOT(updateStopValue(QString)));
  17965. connect(startOptionGroup, SIGNAL(buttonClicked(int)),
  17966. this, SLOT(updateStartTrigger(int)));
  17967. connect(stopOptionGroup, SIGNAL(buttonClicked(int)),
  17968. this, SLOT(updateStopTrigger(int)));
  17969. }
  17970. @ Small methods update the configuration as usual.
  17971. @<RangeTimerConfWidget implementation@>=
  17972. void RangeTimerConfWidget::updateStartButtonText(const QString &text)
  17973. {
  17974. updateAttribute("startbuttontext", text);
  17975. }
  17976. void RangeTimerConfWidget::updateStopButtonText(const QString &text)
  17977. {
  17978. updateAttribute("stopbuttontext", text);
  17979. }
  17980. void RangeTimerConfWidget::updateStartColumnName(const QString &text)
  17981. {
  17982. updateAttribute("startcolumnname", text);
  17983. }
  17984. void RangeTimerConfWidget::updateStopColumnName(const QString &text)
  17985. {
  17986. updateAttribute("stopcolumnname", text);
  17987. }
  17988. void RangeTimerConfWidget::updateStartValue(const QString &text)
  17989. {
  17990. updateAttribute("startvalue", text);
  17991. }
  17992. void RangeTimerConfWidget::updateStopValue(const QString &text)
  17993. {
  17994. updateAttribute("stopvalue", text);
  17995. }
  17996. void RangeTimerConfWidget::updateStartTrigger(int option)
  17997. {
  17998. switch(option)
  17999. {
  18000. case 1:
  18001. updateAttribute("starttrigger", "batch");
  18002. break;
  18003. case 2:
  18004. updateAttribute("starttrigger", "manual");
  18005. break;
  18006. case 3:
  18007. updateAttribute("starttrigger", "value");
  18008. break;
  18009. default:
  18010. break;
  18011. }
  18012. }
  18013. void RangeTimerConfWidget::updateStopTrigger(int option)
  18014. {
  18015. switch(option)
  18016. {
  18017. case 1:
  18018. updateAttribute("stoptrigger", "batch");
  18019. break;
  18020. case 2:
  18021. updateAttribute("stoptrigger", "manual");
  18022. break;
  18023. case 3:
  18024. updateAttribute("stoptrigger", "value");
  18025. break;
  18026. default:
  18027. break;
  18028. }
  18029. }
  18030. @ The widget is registered with the configuration system.
  18031. @<Register device configuration widgets@>=
  18032. app.registerDeviceConfigurationWidget("rangetimer",
  18033. RangeTimerConfWidget::staticMetaObject);
  18034. @ The implementation chunk for now is in the main source file.
  18035. @<Class implementations@>=
  18036. @<RangeTimerConfWidget implementation@>
  18037. @ The multirange timer is a little different. To keep configuration tractible,
  18038. this is slightly less general purpose than the range timer and only supports
  18039. automatic triggering on a single data series.
  18040. @<Class declarations@>=
  18041. class MultiRangeTimerConfWidget : public BasicDeviceConfigurationWidget
  18042. {
  18043. @[Q_OBJECT@]@/
  18044. public:@/
  18045. @[Q_INVOKABLE@]@, MultiRangeTimerConfWidget(DeviceTreeModel *model,
  18046. const QModelIndex &index);
  18047. @[private slots@]:@/
  18048. void updateColumnName(const QString &text);
  18049. void updateRangeData();
  18050. private:@/
  18051. SaltModel *tablemodel;
  18052. };
  18053. @ These limitations allow a rather small set of controls for configuration. A
  18054. line edit to specify the data series used for automatic triggering and a table
  18055. which specifies the name of the timed range and an ending temperature.
  18056. @<MultiRangeTimerConfWidget implementation@>=
  18057. MultiRangeTimerConfWidget::MultiRangeTimerConfWidget(DeviceTreeModel *model,
  18058. const QModelIndex &index)
  18059. : BasicDeviceConfigurationWidget(model, index), tablemodel(new SaltModel(2))
  18060. {
  18061. QFormLayout *layout = new QFormLayout;
  18062. QLineEdit *trigger = new QLineEdit;
  18063. layout->addRow(tr("Trigger column name:"), trigger);
  18064. tablemodel->setHeaderData(0, Qt::Horizontal, "Range Name");
  18065. tablemodel->setHeaderData(1, Qt::Horizontal, "End Temperature");
  18066. QTableView *rangeTable = new QTableView;
  18067. rangeTable->setModel(tablemodel);
  18068. layout->addRow(tr("Range data:"), rangeTable);
  18069. @<Get device configuration data for current node@>@;
  18070. for(int i = 0; i < configData.size(); i++)
  18071. {
  18072. node = configData.at(i).toElement();
  18073. if(node.attribute("name") == "trigger")
  18074. {
  18075. trigger->setText(node.attribute("value"));
  18076. }
  18077. else if(node.attribute("name") == "rangenames")
  18078. {
  18079. QString data = node.attribute("value");
  18080. if(data.length() > 3)
  18081. {
  18082. data.chop(2);
  18083. data = data.remove(0, 2);
  18084. }
  18085. QStringList itemList = data.split(", ");
  18086. for(int j = 0; j < itemList.size(); j++)
  18087. {
  18088. QString item = itemList.at(j);
  18089. item.chop(1);
  18090. item = item.remove(0, 1);
  18091. tablemodel->setData(tablemodel->index(j, 0),
  18092. QVariant(item), Qt::DisplayRole);
  18093. }
  18094. }
  18095. else if(node.attribute("name") == "endtemps")
  18096. {
  18097. @<Convert numeric array literal to list@>@;
  18098. int column = 1;
  18099. @<Populate model column from list@>@;
  18100. }
  18101. }
  18102. updateColumnName(trigger->text());
  18103. updateRangeData();
  18104. connect(trigger, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  18105. connect(tablemodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateRangeData()));
  18106. setLayout(layout);
  18107. }
  18108. @ The update mechanisms are reasonably straightforward. Table updates just
  18109. refresh the entire table instead of attempting to be clever about updating only
  18110. the element that changed.
  18111. @<MultiRangeTimerConfWidget implementation@>=
  18112. void MultiRangeTimerConfWidget::updateRangeData()
  18113. {
  18114. updateAttribute("rangenames", tablemodel->quotedArrayLiteral(0, Qt::DisplayRole));
  18115. updateAttribute("endtemps", tablemodel->arrayLiteral(1, Qt::DisplayRole));
  18116. }
  18117. void MultiRangeTimerConfWidget::updateColumnName(const QString &text)
  18118. {
  18119. updateAttribute("trigger", text);
  18120. }
  18121. @ The widget is registered with the configuration system.
  18122. @<Register device configuration widgets@>=
  18123. app.registerDeviceConfigurationWidget("multirangetimer",
  18124. MultiRangeTimerConfWidget::staticMetaObject);
  18125. @ The implementation is in the main source file.
  18126. @<Class implementations@>=
  18127. @<MultiRangeTimerConfWidget implementation@>
  18128. @* Profile Translation Configuration Widget.
  18129. \noindent Configuring profile translation requires knowing which column to use
  18130. for matching purposes and the value to match.
  18131. @<Class declarations@>=
  18132. class TranslationConfWidget : public BasicDeviceConfigurationWidget
  18133. {
  18134. @[Q_OBJECT@]@;
  18135. public:@/
  18136. @[Q_INVOKABLE@]@, TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  18137. @[private slots@]:@/
  18138. void updateMatchingColumn(const QString &column);
  18139. void updateTemperature();
  18140. void updateDelay();
  18141. private:@/
  18142. QDoubleSpinBox *temperatureValue;
  18143. QComboBox *unitSelector;
  18144. QSpinBox *delaySelector;
  18145. };
  18146. @ The constructor sets up our user interface.
  18147. @<TranslationConfWidget implementation@>=
  18148. TranslationConfWidget::TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  18149. : BasicDeviceConfigurationWidget(model, index),
  18150. temperatureValue(new QDoubleSpinBox), unitSelector(new QComboBox),
  18151. delaySelector(new QSpinBox)
  18152. {
  18153. unitSelector->addItem("Fahrenheit");
  18154. unitSelector->addItem("Celsius");
  18155. temperatureValue->setMinimum(0);
  18156. temperatureValue->setMaximum(1000);
  18157. QFormLayout *layout = new QFormLayout;
  18158. QLineEdit *column = new QLineEdit;
  18159. layout->addRow(tr("Column to match:"), column);
  18160. layout->addRow(tr("Unit:"), unitSelector);
  18161. layout->addRow(tr("Value:"), temperatureValue);
  18162. layout->addRow(tr("Start of batch safety delay:"), delaySelector);
  18163. @<Get device configuration data for current node@>@;
  18164. for(int i = 0; i < configData.size(); i++)
  18165. {
  18166. node = configData.at(i).toElement();
  18167. if(node.attribute("name") == "column")
  18168. {
  18169. column->setText(node.attribute("value"));
  18170. }
  18171. else if(node.attribute("name") == "unit")
  18172. {
  18173. unitSelector->setCurrentIndex(unitSelector->findText(node.attribute("value")));
  18174. }
  18175. else if(node.attribute("name") == "value")
  18176. {
  18177. temperatureValue->setValue(node.attribute("value").toDouble());
  18178. }
  18179. else if(node.attribute("name") == "delay")
  18180. {
  18181. delaySelector->setValue(node.attribute("value").toInt());
  18182. }
  18183. }
  18184. updateMatchingColumn(column->text());
  18185. updateTemperature();
  18186. updateDelay();
  18187. connect(column, SIGNAL(textEdited(QString)), this, SLOT(updateMatchingColumn(QString)));
  18188. connect(unitSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateTemperature()));
  18189. connect(temperatureValue, SIGNAL(valueChanged(double)), this, SLOT(updateTemperature()));
  18190. connect(delaySelector, SIGNAL(valueChanged(int)), this, SLOT(updateDelay()));
  18191. setLayout(layout);
  18192. }
  18193. @ To update the temperature at which to match we save both the values of the
  18194. two widgets which control this and the value in Fahrenheit so we don'@q'@>t need to
  18195. run unit conversions during view initialization.
  18196. @<TranslationConfWidget implementation@>=
  18197. void TranslationConfWidget::updateTemperature()
  18198. {
  18199. updateAttribute("unit", unitSelector->currentText());
  18200. updateAttribute("value", QString("%1").arg(temperatureValue->value()));
  18201. if(unitSelector->currentText() == "Fahrenheit")
  18202. {
  18203. updateAttribute("FValue", QString("%1").arg(temperatureValue->value()));
  18204. }
  18205. else
  18206. {
  18207. updateAttribute("FValue", QString("%1").arg(temperatureValue->value() * 9 / 5 + 32));
  18208. }
  18209. }
  18210. void TranslationConfWidget::updateMatchingColumn(const QString &column)
  18211. {
  18212. updateAttribute("column", column);
  18213. }
  18214. void TranslationConfWidget::updateDelay()
  18215. {
  18216. updateAttribute("delay", QString("%1").arg(delaySelector->value()));
  18217. }
  18218. @ This is registered with the configuration system.
  18219. @<Register device configuration widgets@>=
  18220. app.registerDeviceConfigurationWidget("translation", TranslationConfWidget::staticMetaObject);
  18221. @i rate.w
  18222. @i mergeseries.w
  18223. @i dataqsdk.w
  18224. @i scales.w
  18225. @i valueannotation.w
  18226. @i thresholdannotation.w
  18227. @i user.w
  18228. @i roastcoloredit.w
  18229. @** Local changes.
  18230. \noindent This is the end of \pn{} as distributed by its author. It is expected
  18231. that some might have need of a program like \pn, but require some modification.
  18232. The patching capabilities of \cweb{} can be used to produce these local
  18233. modifications. This section is provided for those whose change requirements are
  18234. sufficiently extensive to require the introduction of new sections to the
  18235. program.
  18236. @** Index.
  18237. \noindent Following is a list of identifiers used in \pn, with underlined
  18238. entries pointing to where \cweb{} has guessed that the identifier was defined.
  18239. All references are to section numbers instead of page numbers.
  18240. \def\nullsec{--}