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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471
  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.8.2 \number\year-\number\month-\number\day}
  25. \def\years{2007--2017}
  26. \def\title{\pn{} (Version \version)}
  27. \newskip\dangerskipb
  28. \newskip\dangerskip
  29. \dangerskip=20pt
  30. \dangerskipb=42pt
  31. \def\hang{\hangindent\dangerskip}
  32. \def\hangb{\hangindent\dangerskipb}
  33. \font\manual=manfnt at 12pt
  34. \def\danbend{{\manual\char127}}
  35. \def\datanger{\medbreak\begingroup\clubpenalty=10000
  36. \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2
  37. \hbox to0pt{\hskip-3.5pc\danbend\hfill}}
  38. \outer\def\danger{\datanger}%
  39. %
  40. \def\datangerb{\medbreak\begingroup\clubpenalty=10000
  41. \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2
  42. \hbox to0pt{\hskip-3.5pc\danbend\hfill}}
  43. \outer\def\dangerb{\datangerb}
  44. \def\endanger{\medskip}
  45. \def\nullsec{\S1}
  46. \def\lheader{\mainfont\the\pageno\kern1pc(\topsecno)\eightrm
  47. \qquad\grouptitle\hfill\title}
  48. \def\rheader{\eightrm\title\hfill\grouptitle\qquad\mainfont
  49. (\topsecno)\kern1pc\the\pageno}
  50. \def\botofcontents{\vfill
  51. \noindent Copyright \copyright\ \years~Neal Evan Wilson
  52. \bigskip\noindent Permission is hereby granted, free of charge, to any
  53. person obtaining a copy of this software and associated documentation files
  54. (the ``Software''), to deal in the Software without restriction, including
  55. without limitation the rights to use, copy, modify, merge, publish,
  56. distribute, sublicense, and/or sell copies of the Software, and to permit
  57. persons to whom the Software is furnished to do so, subject to the following
  58. conditions:\medskip
  59. The above copyright notice and this permission notice shall be included in
  60. all copies or substantial portions of the Software.\medskip
  61. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  62. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  63. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  64. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  65. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  66. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  67. IN THE SOFTWARE.
  68. \bigskip\noindent Parts of \pn{} are from QextSerialPort which is used under the
  69. MIT license as follows:
  70. \bigskip\noindent Copyright \copyright\ 2000--2003 Wayne Roth
  71. \noindent Copyright \copyright\ 2004--2007 Stefan Sander
  72. \noindent Copyright \copyright\ 2007 Michal Policht
  73. \noindent Copyright \copyright\ 2008 Brandon Fosdick
  74. \noindent Copyright \copyright\ 2009--2010 Liam Staskawicz
  75. \noindent Copyright \copyright\ 2011 Debao Zhang
  76. \bigskip\noindent Web: http://code.google.com/p/qextserialport/
  77. \bigskip\noindent Permission is hereby granted, free of charge, to any person obtaining
  78. a copy of this software and associated documentation files (the
  79. ``Software''), to deal in the Software without restriction, including
  80. without limitation the rights to use, copy, modify, merge, publish,
  81. distribute, sublicense, and/or sell copies of the Software, and to
  82. permit persons to whom the Software is furnished to do so, subject to
  83. the following conditions:
  84. The above copyright notice and this permission notice shall be
  85. included in all copies or substantial portions of the Software.
  86. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
  87. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  88. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  89. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  90. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  91. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  92. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  93. }
  94. \let\K=\leftarrow
  95. \def\CPLUSPLUS/{{%
  96. \mc C{\hbox{\kern.5pt\raise1pt\hbox{\sevenrm+\kern-1pt+}\kern.5pt}}
  97. \spacefactor1000}}
  98. \def\PP{\uparrow}
  99. \def\MM{\downarrow}
  100. \newbox\DCBox
  101. \setbox\DCBox=\hbox{$\in$}
  102. \def\DC{\copy\DCBox}
  103. \newbox\MODbox \setbox\MODbox=\hbox{\eightrm MOD}
  104. \def\MOD{\mathbin{\copy\MODbox}}
  105. % Title page
  106. \font\authorfont=cmr12
  107. \null\vfill
  108. \centerline{\titlefont \pn}
  109. \vskip 18pt\centerline{(Version \version)}
  110. \vskip 24pt\centerline{\authorfont Neal Evan Wilson}
  111. \vfill
  112. \titletrue\eject\hbox to 0pt{}
  113. \pageno=0 \titletrue\eject
  114. \secpagedepth=1
  115. % Convenience macros
  116. \def\newline{\vskip\baselineskip}
  117. \def\cweb{\.{CWEB}}
  118. \def\web{\.{WEB}}
  119. \newcount\footnotenumber
  120. \def\nfnote{\global\advance\footnotenumber by 1
  121. \footnote{$^{\the\footnotenumber}$}}
  122. % Listing macro from The TeXBook. See page 381 for an explaination.
  123. \def\uncatcodespecials{\def\do##1{\catcode`##1=12 }\dospecials}
  124. \newcount\lineno
  125. \def\setupverbatim{\tt \lineno=0
  126. \def\par{\leavevmode\endgraf} \catcode`\`=\active
  127. \obeylines \uncatcodespecials \obeyspaces
  128. \everypar{\advance\lineno by1 \llap{\sevenrm\the\lineno\ \ }}}
  129. {\obeyspaces\global\let =\ }
  130. \def\listing#1{\par\begingroup\setupverbatim\input#1 \endgroup}
  131. % Javascript chunk handling
  132. \def\jsfile#1#2{\Y\B\4\X\secno:\.{#1}\X${}\E{}\6$\par
  133. \listing{#2}}
  134. % Type formatting
  135. @s QTime int
  136. @s QMetaType int
  137. @s DAQ int
  138. @s Channel int
  139. @s QString int
  140. @s QObject int
  141. @s QThread int
  142. @s DAQImplementation int
  143. @s QVector int
  144. @s TaskHandle int
  145. @s qint32 int
  146. @s int32 int
  147. @s QMessageBox int
  148. @s QLCDNumber int
  149. @s QWidget int
  150. @s AnnotationButton int
  151. @s AnnotationSpinBox int
  152. @s QPushButton int
  153. @s QTimer int
  154. @s QAction int
  155. @s QApplication int
  156. @s PackLayout int
  157. @s QLayout int
  158. @s QLayoutItem int
  159. @s QRect int
  160. @s QList int
  161. @s QSize int
  162. @s QGraphicsScene int
  163. @s SceneButton int
  164. @s QGraphicsSceneMouseEvent int
  165. @s QPoint int
  166. @s true const
  167. @s false const
  168. @s QGraphicsView int
  169. @s QGraphicsTextItem int
  170. @s QFrame int
  171. @s QPaintDevice int
  172. @s QColor int
  173. @s QBrush int
  174. @s QHash int
  175. @s QPointF int
  176. @s QGraphicsLineItem int
  177. @s MeasurementModel int
  178. @s QTableView int
  179. @s QVariant int
  180. @s QAbstractItemView int
  181. @s QAbstractItemModel int
  182. @s QStringList int
  183. @s QModelIndex int
  184. @s MeasurementList int
  185. @s QVariantList int
  186. @s QSplitter int
  187. @s QHBoxLayout int
  188. @s QMainWindow int
  189. @s QCoreApplication int
  190. @s QSettings int
  191. @s QMenu int
  192. @s QCloseEvent int
  193. @s LogEditWindow int
  194. @s QFile int
  195. @s QFileInfo int
  196. @s QDir int
  197. @s QXmlStreamWriter int
  198. @s QXmlStreamReader int
  199. @s QIODevice int
  200. @s QLabel int
  201. @s QTimeEdit int
  202. @s QSpinBox int
  203. @s QDoubleSpinBox int
  204. @s ThermocoupleType int
  205. @s TemperatureUnits int
  206. @s Qt int
  207. @s emit throw
  208. @s TemperatureDisplay int
  209. @s ZeroEmitter int
  210. @s MeasurementAdapter int
  211. @s GraphView int
  212. @s ZoomLog int
  213. @s TimerDisplay int
  214. @s QBoxLayout int
  215. @s WidgetDecorator int
  216. @s XMLInput int
  217. @s XMLOutput int
  218. @s CSVOutput int
  219. @s QTextStream int
  220. @s QTranslator int
  221. @s QLocale int
  222. @s Application int
  223. @s QScriptContext int
  224. @s QScriptEngine int
  225. @s QScriptEngineDebugger int
  226. @s QScriptValue int
  227. @s FakeDAQ int
  228. @s QMenuBar int
  229. @s QKeySequence int
  230. @s QFileDialog int
  231. @s Measurement int
  232. @s Date int
  233. @s QLibrary int
  234. @s daqfp int
  235. @s QResizeEvent int
  236. @s QVBoxLayout int
  237. @s QByteArray int
  238. @s QSqlDatabase int
  239. @s QComboBox int
  240. @s QXmlStreamAttribute int
  241. @s QSqlQuery int
  242. @s QLineEdit int
  243. @s QDoubleValidator int
  244. @s QIntValidator int
  245. @s QTextEdit int
  246. @s QStandardItemModel int
  247. @s QValidator int
  248. @s QMap int
  249. @s QDomElement int
  250. @s QDomNodeList int
  251. @s QDomNode int
  252. @s QStack int
  253. @s QDomDocument int
  254. @s QDomNamedNodeMap int
  255. @s QFormLayout int
  256. @s QAbstractButton int
  257. @s QAbstractScrollArea int
  258. @s SqlComboBox int
  259. @s QUuid int
  260. @s SqlComboBoxDelegate int
  261. @s QItemDelegate int
  262. @s SqlConnectionSetup int
  263. @s QDialog int
  264. @s QCheckBox int
  265. @s SaltModel int
  266. @s QStyleOptionViewItem int
  267. @s QBuffer int
  268. @s QDateEdit int
  269. @s QCalendarWidget int
  270. @s QDate int
  271. @s QFocusEvent int
  272. @s QGridLayout int
  273. @s QScrollArea int
  274. @s QSqlQueryModel int
  275. @s QSqlRecord int
  276. @s QSqlResult int
  277. @s SqlQueryConnection int
  278. @s QFont int
  279. @s SqlQueryView int
  280. @s QTextDocument int
  281. @s QTextCursor int
  282. @s QTextFrame int
  283. @s ReportTable int
  284. @s QTextTable int
  285. @s QTextTableFormat int
  286. @s QTextFrameFormat int
  287. @s QTextTableCell int
  288. @s QPrinter int
  289. @s QPrintDialog int
  290. @s QSqlError int
  291. @s FormArray int
  292. @s QRegExp int
  293. @s QRegExpValidator int
  294. @s QDomDocumentFragment int
  295. @s QStackedLayout int
  296. @s QMouseEvent int
  297. @s QGraphicsPolygonItem int
  298. @s QPolygonF int
  299. @s QGraphicsPathItem int
  300. @s QPainterPath int
  301. @s QXmlQuery int
  302. @s QGraphicsItem int
  303. @s QWebView int
  304. @s QUrl int
  305. @s QShowEvent int
  306. @s QDateTimeEdit int
  307. @s ThresholdDetector int
  308. @s EdgeDirection int
  309. @s DeviceTreeModelNode int
  310. @s QMetaObject int
  311. @s QTreeView int
  312. @s QToolButton int
  313. @s QextPortInfo int
  314. @s QextSerialEnumerator int
  315. @s QMetaEnum int
  316. @s quint16 int
  317. @s QextSerialPort int
  318. @s QGroupBox int
  319. @s QVariantMap int
  320. @s QIcon int
  321. @s QFileInfoList int
  322. @s QMetaMethod int
  323. @f error normal
  324. @f line normal
  325. @f signals public
  326. @f slots int
  327. @f qRegisterMetaType make_pair
  328. @f READ TeX
  329. @f WRITE TeX
  330. @f tr TeX
  331. @f this TeX
  332. @f foreach while
  333. @f qobject_cast make_pair
  334. @f t1 TeX
  335. @f t2 TeX
  336. @f AppInstance TeX
  337. @f getself make_pair
  338. @f TYPE TeX
  339. @f argument make_pair
  340. @f toScriptValue make_pair
  341. @f arg1 TeX
  342. @f arg2 TeX
  343. @f arg3 TeX
  344. @f arg4 TeX
  345. @f findChild make_pair
  346. @f qscriptvalue_cast make_pair
  347. \def\READ{\kern4pt{\tt READ}\kern4pt}
  348. \def\WRITE{\kern4pt{\tt WRITE}\kern4pt}
  349. \def\tr{\delta}
  350. \def\this{\forall}
  351. \def\t#1{t_{#1}}
  352. \def\AppInstance{\.{AppInstance}}
  353. \def\TYPE{\cal T\kern1pt}
  354. \def\arg#1{arg_{#1}}
  355. % Document
  356. @** A Note on Notation.
  357. \noindent As noted by Falkoff and Iverson\nfnote{A.~D.~Falkoff and
  358. K.~E.~Iverson, ``The Design of APL'' (1973)}~there is little need to limit the
  359. typography used to represent a computer program in print. The printed code of
  360. \pn{} uses a number of notations that I have found useful in making clear the
  361. intent of the code. For example, a common mistake in \CPLUSPLUS/ \kern-0.5em
  362. code is the confusion of assignment ({\tt =}) with a test for equality
  363. ({\tt ==}). The \web{} convention of using |=| for assignment and |==| to test
  364. for equality makes such errors obvious at a glance. A list of special symbols
  365. and the equivalent \CPLUSPLUS/text is provided in Table \secno. Most of these
  366. symbols should be familiar\nfnote{The {\tt NULL} symbol is a break with the
  367. conventions of most Qt applications. According the the \CPLUSPLUS/standard, |0|
  368. is both an integer constant and a null pointer constant. Most programs using Qt
  369. use |0| in place of any name for the null pointer, however conceptually these
  370. are two very different things. The notation chosen here was used by Knuth for
  371. similar purposes and seems to have worked well there.}.
  372. \medskip
  373. \settabs 9 \columns
  374. \+&&&{\tt =}&|=|&Assignment\cr
  375. \+&&&{\tt --}&|--|&Decrement\cr
  376. \+&&&{\tt ==}&|==|&Equality Test\cr
  377. \+&&&{\tt >=}&|>=|&Greater or Equal Test\cr
  378. \+&&&{\tt ++}&|++|&Increment\cr
  379. \+&&&{\tt !=}&|!=|&Inequality Test\cr
  380. \+&&&{\tt <=}&|<=|&Less or Equal Test\cr
  381. \+&&&{\tt \char'046\char'046}&$\land$&Logical AND\cr
  382. \+&&&{\tt \char'174\char'174}&$\lor$&Logical OR\cr
  383. \+&&&{\tt ::}&|::|&Member of\cr
  384. \+&&&{\tt !}&|!|&Negation\cr
  385. \+&&&{\tt NULL}&|NULL|&Null Pointer\cr
  386. \+&&&{\tt this}&|this|&Object\cr
  387. \+&&&{\tt \%}&|%|&Remainder\cr
  388. \+&&&{\tt tr()}&|tr()|&Translate\cr
  389. \smallskip
  390. \centerline{Table \secno: Special Characters In \pn}
  391. \medskip
  392. Reserved words are set in bold face. As some of these reserved words are also
  393. the names of types, type names that are not specified in \CPLUSPLUS/are also
  394. set in bold face. Type placeholders in template definitions, however, are set in
  395. caligraphic capitals to emphasize that it will be replaced with a real type at
  396. compile time. Variables and class members are set in italics, character strings
  397. are set in a typewriter style with visible spaces. Macro names are also set in
  398. typewriter style. Numeric constants and plain text comments are set in an
  399. upright roman style. Comments containing \CEE/ or mathematics are styled as
  400. such. Code that will be interpreted by the ECMA-262 host environment has no
  401. pretty printing.
  402. \danger With apologies to prof.~Knuth\nfnote{This symbol was introduced in
  403. {\underbar{Computers~\char'046~Typesetting}}@q'@> (Knuth, 1984) to point out material
  404. that is for ``wizards only.'' It seems to be as appropriate a symbol as any to
  405. point out the darker corners of this program.}, code that is known to be
  406. potentially buggy is flagged with a dangerous bend sign. Some of this code is
  407. buggy due to issues with the code \pn{} depends on, others are things that
  408. should be fixed in \pn{}. Of course, there may also be bugs that have not yet
  409. been noticed or have not been attached to a particular block of code.\endanger
  410. A basic familiarity with literate programming techniques (particularly the
  411. conventions of \cweb{}), Qt, and \CPLUSPLUS/is recommended before altering the
  412. program, but an effort has been made to keep the program understandable for
  413. those who are only interested in studying it.
  414. @** Introduction.
  415. \noindent A common tool in the craft of coffee roasting is the data logger.
  416. Perhaps the most commonly used of these fall into the category of manual data
  417. loggers which require the roaster to use paper and a writing utensil,
  418. periodically recording measurements and noting control changes and observations
  419. of interest as needed.
  420. While there are many benefits to recording roast data\nfnote{Torrey Lee, Stephan
  421. Diedrich, Carl Staub, and Jack Newall, ``How to Obtain Excellence with Drum
  422. Roasters'' (2002) {\it Specialty Coffee Association of America 14$^{th}$ Annual
  423. Conference and Exhibition}}, there are a number of limitations to the manual
  424. approach; maintaining the records in a useful order is time consuming and error
  425. prone, it is difficult to work with aggregates of such records, and the
  426. attention required to log the data by hand can distract from the roasting. Using
  427. a computer with automatic data logging software designed with coffee roasting in
  428. mind can reduce or eliminate these deficiencies. \pn{} is one such program.
  429. The file {\tt \filebase.w} contains both \CPLUSPLUS/source code and the
  430. documentation for that code. This file is intended to be processed by
  431. \cweb\nfnote{Donald E. Knuth and Silvio Levy, ``The \cweb{} System of Structured
  432. Documentation'' (1994)}~to produce source code for your compiler and plain
  433. \TeX{}\nfnote{\TeX{} (pronounced $\tau\epsilon\chi$) is a trademark of the
  434. American Mathematical Society.} documentation that can be used to generate a PDF
  435. document for gorgeous printable documentation. These generated files may have
  436. been distributed with your copy of {\tt \filebase.w} for convenience.
  437. Changes to the program can be made in three ways. \cweb{} provides a patching
  438. mechanism which can be used to experiment with the code without risk of
  439. clobbering it. Instructions for the construction of such a change file can be
  440. found in the \cweb{} documentation. Adding the name of the change file to the
  441. invocation of {\tt ctangle} and {\tt cweave} will incorporate that change
  442. seamlessly in both source and documentation files. A section is provided at the
  443. end of this program for use with this mechanism in the case that new sections
  444. must be added. Another way to create persistent modifications is to alter
  445. {\tt \filebase.w} however this may make it more difficult to use changes with
  446. future versions of the software. Changes should not be made to
  447. {\tt \filebase.cpp} if these changes are expected to persist. Finally, it is
  448. possible to make many changes to how the program looks and behaves by creating a
  449. new configuration document for the program to load. Modifications made in this
  450. way do not even require recompiling the software. Examples that can serve as a
  451. starting point for such customizations are provided with \pn{}.
  452. \pn{} is a work in progress. There are several portions of the documentation
  453. that contain suggestions for future improvement. These notes provide clues for
  454. my future development plans. Naturally, if you have needs which are not quite
  455. addressed by this program, you should feel free to modify the code to suit your
  456. needs. Hopefully this will be easy to do.
  457. In the spirit of Benjamin Franklin\nfnote{``\dots as we enjoy great advantages
  458. from the inventions of others, we should be glad of an opportunity to serve
  459. others by any invention of ours; and this we should do freely and
  460. generously.''
  461. --- Benjamin Franklin, \underbar{The Private Life of the Late
  462. Benjamin Franklin, LL.D.~Originally
  463. Written By Himself, And Now}\par\noindent
  464. \underbar{Translated From The French} (1793)}, \pn{} is shared
  465. with minimal restriction (see the license after the table of contents for legal
  466. requirements). Libraries used by \pn{} may have other restrictions. Before
  467. undertaking to distribute a binary created from this code, you may want to
  468. either determine your rights with regard to these libraries or modify the
  469. program to remove them.
  470. As CWEB generates files with the wrong extension, we leave the default
  471. generated file empty.
  472. @c
  473. /* Nothing to see here. */
  474. @ The following is an overview of the structure of \pn:
  475. @(typica.cpp@>=
  476. #define PROGRAM_NAME "Typica"
  477. @<Header files to include@>@/
  478. @<Additional type definitions@>@/
  479. @<Additional function prototypes@>@/
  480. @<Class declarations@>@/
  481. @<Additional functions@>@/
  482. @<Function prototypes for scripting@>@/
  483. @<Logging function prototype@>@/
  484. @<Class implementations@>@/
  485. @<Functions for scripting@>@/
  486. @<Logging function implementation@>@/
  487. @<The main program@>
  488. #include "moc_typica.cpp"
  489. @ \pn{} is made of a number of distinct classes.
  490. @<Class implementations@>=
  491. @<NodeInserter implementation@>@/
  492. @<Measurement implementation@>@/
  493. @<DAQ Implementation@>@/
  494. @<DataqSdkDevice implementation@>@/
  495. @<FakeDAQ Implementation@>@/
  496. @<Channel Implementation@>@/
  497. @<TemperatureDisplay Implementation@>@/
  498. @<MeasurementTimeOffset Implementation@>@/
  499. @<ZeroEmitter Implementation@>@/
  500. @<MeasurementAdapter Implementation@>@/
  501. @<GraphView Implementation@>@/
  502. @<ZoomLog Implementation@>@/
  503. @<MeasurementModel Implementation@>@/
  504. @<AnnotationButton Implementation@>@/
  505. @<AnnotationSpinBox Implementation@>@/
  506. @<TimerDisplay Implementation@>@/
  507. @<PackLayout Implementation@>@/
  508. @<SceneButton Implementation@>@/
  509. @<WidgetDecorator Implementation@>@/
  510. @<LogEditWindow Implementation@>@/
  511. @<XMLOutput Implementation@>@/
  512. @<XMLInput Implementation@>@/
  513. @<CSVOutput Implementation@>@/
  514. @<SaltModel Implementation@>@/
  515. @<SqlComboBox Implementation@>@/
  516. @<SqlComboBoxDelegate Implementation@>@/
  517. @<Application Implementation@>@/
  518. @<SqlConnectionSetup implementation@>@/
  519. @<SqlQueryView implementation@>@/
  520. @<SqlQueryConnection implementation@>@/
  521. @<ReportTable implementation@>@/
  522. @<FormArray implementation@>@/
  523. @<ScaleControl implementation@>@/
  524. @<IntensityControl implementation@>@/
  525. @<ThresholdDetector Implementation@>@/
  526. @<PortSelector implementation@>@/
  527. @<BaudSelector implementation@>@/
  528. @<ParitySelector implementation@>@/
  529. @<FlowSelector implementation@>@/
  530. @<StopSelector implementation@>@/
  531. @<ModbusConfigurator implementation@>@/
  532. @<ShortHexSpinBox implementation@>@/
  533. @<ModbusRTUDevice implementation@>@/
  534. @<DeviceTreeModelNode implementation@>@/
  535. @<DeviceTreeModel implementation@>@/
  536. @<BasicDeviceConfigurationWidget implementation@>@/
  537. @<DeviceConfigurationWindow implementation@>@/
  538. @<Ni9211TcConfWidget implementation@>@/
  539. @<NiDaqMxBase9211ConfWidget implementation@>@/
  540. @<NiDaqMxBaseDriverConfWidget implementation@>@/
  541. @<ReportAction implementation@>@/
  542. @<NumericDelegate implementation@>@/
  543. @<NiDaqMxDriverConfWidget implementation@>@/
  544. @<NiDaqMx9211ConfWidget implementation@>@/
  545. @<NiDaqMxTc01ConfWidget implementation@>@/
  546. @<ModbusRtuPortConfWidget implementation@>@/
  547. @<ModbusRtuDeviceConfWidget implementation@>@/
  548. @<ModbusRtuDeviceTPvConfWidget implementation@>@/
  549. @<ModbusRtuDeviceTSvConfWidget implementation@>@/
  550. @<RoasterConfWidget implementation@>@/
  551. @<AnnotationButtonConfWidget implementation@>@/
  552. @<NoteSpinConfWidget implementation@>@/
  553. @<LinearCalibrator Implementation@>@/
  554. @<LinearSplineInterpolator Implementation@>@/
  555. @<LinearSplineInterpolationConfWidget implementation@>@/
  556. @<TranslationConfWidget implementation@>@/
  557. @<FreeAnnotationConfWidget implementation@>@/
  558. @<RateOfChange implementation@>@/
  559. @<SettingsWindow implementation@>@/
  560. @<GraphSettingsWidget implementation@>@/
  561. @<DataqSdkDeviceConfWidget implementation@>@/
  562. @<SerialScaleConfWidget implementation@>@/
  563. @<ValueAnnotation implementation@>@/
  564. @<ValueAnnotationConfWidget implementation@>@/
  565. @<ModbusNG implementation@>@/
  566. @<ThresholdAnnotationConfWidget implementation@>@/
  567. @<Annotator implementation@>@/
  568. @ A few headers are required for various parts of \pn{}. These allow the use of
  569. various Qt modules.
  570. @<Header files to include@>=
  571. #include <QtCore>
  572. #include <QtGui>
  573. #include <QtScript>
  574. #include <QtScriptTools>
  575. #include <QtXml>
  576. #include <QtSql>
  577. #include <QtDebug>
  578. #include <QtXmlPatterns>
  579. #include <QtWebKit>
  580. #include <QtSvg>
  581. #include <QtNetwork>
  582. @ New code is being written in separate files in a long term effort to improve
  583. organization of the code. The result of this is that some additional headers
  584. are required here.
  585. @<Header files to include@>=
  586. #include "helpmenu.h"
  587. @** The Scripting Engine.
  588. \noindent The main enhancement of \pn{} version 1.1 is the introduction of a
  589. scriptable environment. This change allows people to easily customize \pn{}
  590. without having to alter the program code. Instead, the user interface and
  591. program data flow is set up with a small script that runs in an ECMA-262 host
  592. environment\nfnote{Standard ECMA-262, 3$^{\rm{rd}}$ Edition\par\hbox{\indent%
  593. \pdfURL{%
  594. http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}%
  595. {http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}}}
  596. which requires
  597. significantly less expertise to modify than \pn{} itself. Such a scripting
  598. environment will be familiar to anybody with experience using JavaScript on web
  599. pages or ActionScript in Flash. \pn{}'@q'@>s configuration system was later updated
  600. to support running several script fragments found in an XML configuration
  601. document.
  602. Most of the application classes are available from the scripting environment.
  603. The functions that make this possible are presented along with the classes. A
  604. selection of classes provided by Qt are also available. These are presented
  605. here.
  606. This chunk provides two |QScriptValue| objects which are used in other sections
  607. appended to this chunk.
  608. @<Set up the scripting engine@>=
  609. QScriptEngine *engine = new QScriptEngine;
  610. QScriptValue constructor;
  611. QScriptValue value;
  612. @ A common task when working with objects created from a script is finding the
  613. object a method is called on from the current script context. The code for this
  614. is simple, but lengthy. This is shortened with the use of a template function
  615. that obtains the object in question and casts it to the appropriate type. If an
  616. incorrect type is specified, a null pointer or similarly invalid value will be
  617. returned.
  618. @<Functions for scripting@>=
  619. template<class TYPE> TYPE@, getself(QScriptContext *context)
  620. {
  621. TYPE@, self = qobject_cast<TYPE>(context->thisObject().toQObject());
  622. return self;
  623. }
  624. template<> QTime getself(QScriptContext *context)
  625. {
  626. QTime self = context->thisObject().toVariant().toTime();
  627. return self;
  628. }
  629. template<> QByteArray getself(QScriptContext *context)
  630. {
  631. QByteArray self = context->thisObject().toVariant().toByteArray();
  632. return self;
  633. }
  634. template<> SqlQueryConnection* getself(QScriptContext *context)
  635. {
  636. SqlQueryConnection *self =@|
  637. (SqlQueryConnection *)qscriptvalue_cast<void *>(context->thisObject());
  638. return self;
  639. }
  640. template<> QXmlQuery* getself(QScriptContext *context)
  641. {
  642. QXmlQuery *self =
  643. (QXmlQuery *)qscriptvalue_cast<void *>(context->thisObject());
  644. return self;
  645. }
  646. template<> QXmlStreamWriter* getself(QScriptContext *context)
  647. {
  648. QXmlStreamWriter *self = @|
  649. (QXmlStreamWriter *)qscriptvalue_cast<void *>(context->thisObject());
  650. return self;
  651. }
  652. template<> QXmlStreamReader* getself(QScriptContext *context)
  653. {
  654. QXmlStreamReader *self = @|
  655. (QXmlStreamReader *)qscriptvalue_cast<void *>(context->thisObject());
  656. return self;
  657. }
  658. @ Another common task is obtaining the arguments of a method call from the
  659. script context and casting these arguments to the proper type. This is once
  660. again done with templates.
  661. @<Functions for scripting@>=
  662. template<class TYPE> TYPE@, argument(int arg, QScriptContext *context)
  663. {
  664. TYPE@, argument = qobject_cast<TYPE>(context->argument(arg).toQObject());
  665. return argument;
  666. }
  667. template<> QString argument(int arg, QScriptContext *context)
  668. {
  669. return context->argument(arg).toString();
  670. }
  671. template<> QVariant argument(int arg, QScriptContext *context)
  672. {
  673. return context->argument(arg).toVariant();
  674. }
  675. template<> int argument(int arg, QScriptContext *context)
  676. {
  677. return context->argument(arg).toInt32();
  678. }
  679. template<> SqlQueryConnection* argument(int arg, QScriptContext *context)
  680. {
  681. return (SqlQueryConnection *)
  682. qscriptvalue_cast<void *>(context->argument(arg));
  683. }
  684. template<> QModelIndex argument(int arg, QScriptContext *context)
  685. {
  686. return qscriptvalue_cast<QModelIndex>(context->argument(arg));
  687. }
  688. template<> double argument(int arg, QScriptContext *context)
  689. {
  690. return (double)(context->argument(arg).toNumber());
  691. }
  692. template<> Units::Unit argument(int arg, QScriptContext *context)
  693. {
  694. return (Units::Unit)(context->argument(arg).toInt32());
  695. }
  696. template<> QByteArray argument(int arg, QScriptContext *context)
  697. {
  698. return qscriptvalue_cast<QByteArray>(context->argument(arg));
  699. }
  700. template<> bool argument(int arg, QScriptContext *context)
  701. {
  702. return context->argument(arg).toBool();
  703. }
  704. @ The scripting engine is informed of a number of classes defined elsewhere in
  705. the program. Code related to scripting these classes is grouped with the code
  706. implementing the classes. Additionally, there are several classes from Qt which
  707. are also made scriptable. These are detailed in the following sections.
  708. @* Exposing an Object Hierarchy to the Host Environment.
  709. \noindent While QtScript does a generally acceptable job of exposing
  710. information about objects that are available through the meta-object system,
  711. some methods require special handling in order to make them fully available to
  712. the host environment. Several functions are provided which provide a
  713. |QScriptValue| with these additional properties. The functions providing these
  714. properties also call other functions providing the properties of any base
  715. classes. In this way, any additional functionality provided to the host
  716. environment for a base class is also provided for any class that inherits that
  717. base class.
  718. For example, a |QBoxLayout| created in a script will have properties from
  719. |QLayout| which in turn brings in properties from |QObject| and |QLayoutItem|.
  720. A |QMainWindow| would bring in properties from |QWidget| which would bring in
  721. properties from |QObject|.
  722. Neither all methods nor all Qt classes are available from the host environment.
  723. When adding functionality to the host environment, there is a priority on
  724. classes and methods that are useful for \pn{}'@q'@>s intended purpose.
  725. @* Base Classes.
  726. \noindent There are a few classes that are base classes of classes exposed to
  727. the scripting engine. There is no need for the host environment to allow the
  728. creation of these base classes and there may not be methods that must be added
  729. as properties in derived classes, however stub functions are provided so that
  730. in the event that a method from one of these base classes is needed later, it
  731. can be added once for all derived classes.
  732. The first of these is |QObject|.
  733. @<Function prototypes for scripting@>=
  734. void setQObjectProperties(QScriptValue value, QScriptEngine *engine);
  735. QScriptValue QObject_setProperty(QScriptContext *context, QScriptEngine *engine);
  736. @ Attaching properties to a |QScriptValue| that wraps a |QObject| does not
  737. create a dynamic property on the underlying |QObject| by default. This can
  738. cause issues with certain interactions between script and native code. Rather
  739. than change every wrapper, we can instead expose a |setProperty()| method.
  740. @<Functions for scripting@>=
  741. void setQObjectProperties(QScriptValue value, QScriptEngine *engine)
  742. {
  743. value.setProperty("setProperty", engine->newFunction(QObject_setProperty));
  744. }
  745. QScriptValue QObject_setProperty(QScriptContext *context, QScriptEngine *)
  746. {
  747. QObject *self = getself<QObject *>(context);
  748. self->setProperty(argument<QString>(0, context).toUtf8().constData(),
  749. argument<QVariant>(1, context));
  750. return QScriptValue();
  751. }
  752. @ The same can be done for |QPaintDevice| and |QLayoutItem|.
  753. @<Function prototypes for scripting@>=
  754. void setQPaintDeviceProperties(QScriptValue value, QScriptEngine *engine);
  755. void setQLayoutItemProperties(QScriptValue value, QScriptEngine *engine);
  756. @ The implementations are similarly empty.
  757. @<Functions for scripting@>=
  758. void setQPaintDeviceProperties(QScriptValue, QScriptEngine *)
  759. {
  760. /* Nothing needs to be done here. */
  761. }
  762. void setQLayoutItemProperties(QScriptValue, QScriptEngine *)
  763. {
  764. /* Nothing needs to be done here. */
  765. }
  766. @* Timers.
  767. \noindent Some features in Typica require access to functionality similar to
  768. what |QTimer| provides from the host environment. This includes allowing
  769. script devices to periodically poll connected hardware and allowing a safety
  770. delay on profile translation.
  771. <@Function prototypes for scripting@>=
  772. void setQTimerProperties(QScriptValue value, QScriptEngine *engine);
  773. QScriptValue constructQTimer(QScriptContext *context, QScriptEngine *engine);
  774. @ The host environment is informed of the constructor.
  775. @<Set up the scripting engine@>=
  776. constructor = engine->newFunction(constructQTimer);
  777. value = engine->newQMetaObject(&QTimer::staticMetaObject, constructor);
  778. engine->globalObject().setProperty("Timer", value);
  779. @ Everything that we are interested in here is a signal, slot, or property so
  780. there is little else to do.
  781. @<Functions for scripting@>=
  782. void setQTimerProperties(QScriptValue value, QScriptEngine *engine)
  783. {
  784. setQObjectProperties(value, engine);
  785. }
  786. QScriptValue constructQTimer(QScriptContext *, QScriptEngine *engine)
  787. {
  788. QScriptValue object = engine->newQObject(new QTimer);
  789. setQTimerProperties(object, engine);
  790. return object;
  791. }
  792. @* Scripting QWidget.
  793. \noindent The first interesting class in this hierarchy is |QWidget|. This is
  794. mainly used as a base class for other widgets and in such a role it is not
  795. particularly interesting. It is, however, possible to apply a layout to a
  796. |QWidget| and use that to manage the size and position of one or more child
  797. widgets. A few functions are used to accomplish this.
  798. @<Function prototypes for scripting@>=
  799. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine);
  800. QScriptValue constructQWidget(QScriptContext *context, QScriptEngine *engine);
  801. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *engine);
  802. QScriptValue QWidget_activateWindow(QScriptContext *context,
  803. QScriptEngine *engine);
  804. @ The script constructor must be passed to the scripting engine.
  805. @<Set up the scripting engine@>=
  806. constructor = engine->newFunction(constructQWidget);
  807. value = engine->newQMetaObject(&QWidget::staticMetaObject, constructor);
  808. engine->globalObject().setProperty("QWidget", value);
  809. @ The constructor creates a script value, but uses another function to add
  810. properties that wrap methods we want to make available to subclasses. Note that
  811. properties of the base classes are added before properties of this class. This
  812. procedure ensures that properties added from base classes can be be replaced in
  813. subclasses.
  814. @<Functions for scripting@>=
  815. QScriptValue constructQWidget(QScriptContext *, QScriptEngine *engine)
  816. {
  817. QScriptValue object = engine->newQObject(new QWidget);
  818. setQWidgetProperties(object, engine);
  819. return object;
  820. }
  821. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine)
  822. {
  823. setQObjectProperties(value, engine);
  824. setQPaintDeviceProperties(value, engine);
  825. value.setProperty("setLayout", engine->newFunction(QWidget_setLayout));
  826. value.setProperty("activateWindow",
  827. engine->newFunction(QWidget_activateWindow));
  828. }
  829. @ This just leaves the property implementations. |QWidget::setLayout()| takes
  830. one argument, a |QLayout| and returns |void|. This wrapper duplicates this
  831. interface. |QWidget::activateWindow()| takes no arguments and returns nothing
  832. meaningful.
  833. @<Functions for scripting@>=
  834. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *)
  835. {
  836. if(context->argumentCount() == 1)
  837. {
  838. QWidget *self = getself<QWidget *>(context);
  839. QLayout *layout = argument<QLayout *>(0, context);
  840. if(layout)
  841. {
  842. self->setLayout(layout);
  843. }
  844. else
  845. {
  846. context->throwError("Incorrect argument type passed to "@|
  847. "QWidget::setLayout(). This method requires "@|
  848. "a QLayout.");
  849. }
  850. }
  851. else
  852. {
  853. context->throwError("Incorrect number of arguments passed to "@|
  854. "QWidget::setLayout(). This method takes one "@|
  855. "QLayout as an argument.");
  856. }
  857. return QScriptValue();
  858. }
  859. QScriptValue QWidget_activateWindow(QScriptContext *context,
  860. QScriptEngine *)
  861. {
  862. QWidget *self = getself<QWidget *>(context);
  863. self->activateWindow();
  864. return QScriptValue();
  865. }
  866. @* Scripting QMessageBox.
  867. \noindent Some features require that \pn{} pauses an operation until further
  868. information can be obtained. An example of this is discretionary validation
  869. where input is checked and if it seems unlikely but not impossible to be
  870. correct a dialog should come up asking if that input is correct. If it is not,
  871. the operation should be cancelled and the person using \pn{} should be allowed
  872. to correct the information and try again.
  873. For this use case, it is not necessary to fully expose the |QMessageBox| class.
  874. Instead, it is enough to provide a function that will raise an appropriate
  875. message and return the selected action.
  876. @<Function prototypes for scripting@>=
  877. QScriptValue displayWarning(QScriptContext *context, QScriptEngine *engine);
  878. QScriptValue displayError(QScriptContext *context, QScriptEngine *engine);
  879. QScriptValue displayInfo(QScriptContext *context, QScriptEngine *engine);
  880. @ This function is exposed to the host environment.
  881. @<Set up the scripting engine@>=
  882. constructor = engine->newFunction(displayWarning);
  883. engine->globalObject().setProperty("displayWarning", constructor);
  884. constructor = engine->newFunction(displayError);
  885. engine->globalObject().setProperty("displayError", constructor);
  886. constructor = engine->newFunction(displayInfo);
  887. engine->globalObject().setProperty("displayInfo", constructor);
  888. @ The function takes some arguments.
  889. @<Functions for scripting@>=
  890. QScriptValue displayWarning(QScriptContext *context, QScriptEngine *)
  891. {
  892. QMessageBox::StandardButton selection = QMessageBox::warning(NULL,
  893. argument<QString>(0, context),
  894. argument<QString>(1, context),
  895. QMessageBox::Ok | QMessageBox::Cancel);
  896. if(selection == QMessageBox::Ok) {
  897. return QScriptValue(true);
  898. }
  899. return QScriptValue(false);
  900. }
  901. QScriptValue displayError(QScriptContext *context, QScriptEngine *)
  902. {
  903. QMessageBox::critical(NULL, argument<QString>(0, context),
  904. argument<QString>(1, context));
  905. return QScriptValue();
  906. }
  907. QScriptValue displayInfo(QScriptContext *context, QScriptEngine *)
  908. {
  909. QMessageBox::information(NULL, argument<QString>(0, context),
  910. argument<QString>(1, context));
  911. return QScriptValue();
  912. }
  913. @* Scripting QMainWindow.
  914. \noindent Rather than directly exposing |QMainWindow| to the scripting engine,
  915. we expose a class derived from |QMainWindow| with a minor change allowing the
  916. script to be notified when the window is about to be closed.
  917. This allows us to save settings for objects populating the window. Close
  918. handlers can be established by connecting to the |aboutToClose()| signal which
  919. is emitted in the |closeEvent()| handler. The close event is always accepted
  920. after the script has had a chance to respond, so this cannot be used to present
  921. an, ``Are you sure?'' message without additional modification.
  922. Slots are also provided for saving the size and position of the window to
  923. settings and restoring the window geometry from these settings.
  924. As of version 1.4 window geometry management is provided for all windows. The
  925. |restoreSizeAndPosition()| and |saveSizeAndPosition()| methods should be
  926. considered depreciated.
  927. Version 1.6 adds a new property for handling the |windowModified| property
  928. such that an appropriate prompt is provided to confirm or cancel close events.
  929. Version 1.8 adds a new |setupFinished()| slot which is called after the
  930. initial |show()| at the end of window creation. This emits a |windowReady()|
  931. signal. Scripts can connect to this signal to perform tasks that must happen
  932. after the window has fully finished opening. The initial use for this is
  933. validating that all required configuration has been performed for a given
  934. window to be useful and, if not, immediately closing that. Without this, a
  935. call to |close()| in the script is reversed when the function creating the
  936. window calls |show()|.
  937. @<Class declarations@>=
  938. class ScriptQMainWindow : public QMainWindow@/
  939. {@t\1@>@/
  940. Q_OBJECT@;@/
  941. Q_PROPERTY(QString closePrompt READ closePrompt WRITE setClosePrompt)@;@/
  942. public:@/
  943. ScriptQMainWindow();
  944. QString closePrompt();@/
  945. @t\4@>public slots@t\kern-3pt@>:@/
  946. void show();
  947. void saveSizeAndPosition(const QString &key);
  948. void restoreSizeAndPosition(const QString &key);
  949. void displayStatus(const QString &message = QString());
  950. void setClosePrompt(QString prompt);
  951. void setupFinished();@/
  952. signals:@/
  953. void aboutToClose(void);
  954. void windowReady(void);@/
  955. protected:@/
  956. void closeEvent(QCloseEvent *event);
  957. void showEvent(QShowEvent *event);@/
  958. private:@/
  959. QString cprompt;@t\2@>@/
  960. }@t\kern-3pt@>;
  961. @ The implementation of these functions is simple.
  962. @<Functions for scripting@>=
  963. ScriptQMainWindow::ScriptQMainWindow()@+: QMainWindow(NULL),
  964. cprompt(tr("Closing this window may result in loss of data. Continue?"))@/
  965. {
  966. if(!AppInstance->databaseConnected())
  967. {
  968. statusBar()->addWidget(new QLabel(tr("Not connected to database")));
  969. }
  970. else
  971. {
  972. statusBar()->addWidget(new UserLabel);
  973. }
  974. }
  975. void ScriptQMainWindow::saveSizeAndPosition(const QString &key)
  976. {
  977. QSettings settings;
  978. settings.beginGroup(key);
  979. settings.setValue("pos", pos());
  980. settings.setValue("size", size());
  981. settings.endGroup();
  982. }
  983. void ScriptQMainWindow::restoreSizeAndPosition(const QString &key)
  984. {
  985. QSettings settings;
  986. settings.beginGroup(key);
  987. if(settings.contains("size"))
  988. {
  989. resize(settings.value("size").toSize());
  990. }
  991. if(settings.contains("pos"))
  992. {
  993. move(settings.value("pos").toPoint());
  994. }
  995. settings.endGroup();
  996. }
  997. void ScriptQMainWindow::displayStatus(const QString &message)
  998. {
  999. statusBar()->showMessage(message);
  1000. }
  1001. void ScriptQMainWindow::showEvent(QShowEvent *event)
  1002. {
  1003. if(!event->spontaneous())
  1004. {
  1005. @<Restore window geometry@>@;
  1006. event->accept();
  1007. }
  1008. else
  1009. {
  1010. event->ignore();
  1011. }
  1012. }
  1013. void ScriptQMainWindow::show()
  1014. {
  1015. QMainWindow::show();
  1016. }
  1017. void ScriptQMainWindow::setupFinished()
  1018. {
  1019. emit windowReady();
  1020. }
  1021. @ When a close event occurs, we check the |windowModified| property to
  1022. determine if closing the window could result in loss of data. If this is
  1023. true, we allow the event to be cancelled. Otherwise, a signal is emitted which
  1024. allows scripts to perform any cleanup that may be required before closing the
  1025. window and the window geometry data is saved before allowing the window to
  1026. close.
  1027. @<Functions for scripting@>=
  1028. void ScriptQMainWindow::closeEvent(QCloseEvent *event)
  1029. {
  1030. if(isWindowModified()) {
  1031. @<Allow close event to be cancelled@>@;
  1032. }
  1033. emit aboutToClose();
  1034. @<Save window geometry@>@;
  1035. event->accept();
  1036. }
  1037. @ The prompt text for our confirmation window is provided through the
  1038. |closePrompt| property.
  1039. @<Allow close event to be cancelled@>=
  1040. QMessageBox::StandardButton result;
  1041. result = QMessageBox::warning(this, "Typica", closePrompt(),
  1042. QMessageBox::Ok | QMessageBox::Cancel);
  1043. if(result == QMessageBox::Cancel)
  1044. {
  1045. event->ignore();
  1046. return;
  1047. }
  1048. @ Implementation of the |closePrompt| property is trivial.
  1049. @<Functions for scripting@>=
  1050. QString ScriptQMainWindow::closePrompt()
  1051. {
  1052. return cprompt;
  1053. }
  1054. void ScriptQMainWindow::setClosePrompt(QString prompt)
  1055. {
  1056. cprompt = prompt;
  1057. }
  1058. @ Window geometry management from version 1.4 on makes use of the window ID to
  1059. produce an appropriate QSettings key. This decision relies on the ID being set
  1060. before any show or close events are received and it relies on every distinct
  1061. type of window having a unique ID. If this is not the case then other things
  1062. are likely very broken. Note that with this approach multiple instances of the
  1063. same type of window will use the same key. This may not be ideal in all cases,
  1064. but further refinements can be produced if necessary.
  1065. @<Save window geometry@>=
  1066. QSettings settings;
  1067. settings.setValue(QString("geometries/%1").arg(objectName()), saveGeometry());
  1068. @ Restoring saved geometry is performed similarly to saving it.
  1069. @<Restore window geometry@>=
  1070. QSettings settings;
  1071. restoreGeometry(settings.value(QString("geometries/%1").arg(objectName())).
  1072. toByteArray());
  1073. @ Three functions are required to obtain the required functionality from a
  1074. script. A fourth adds properties for the object hierarchy.
  1075. @<Function prototypes for scripting@>=
  1076. QScriptValue constructQMainWindow(QScriptContext *context,
  1077. QScriptEngine *engine);
  1078. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,@|
  1079. QScriptEngine *engine);
  1080. QScriptValue QMainWindow_menuBar(QScriptContext *context,
  1081. QScriptEngine *engine);
  1082. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine);
  1083. @ Of these, the engine only needs to be informed of the constructor initially.
  1084. @<Set up the scripting engine@>=
  1085. constructor = engine->newFunction(constructQMainWindow);
  1086. value = engine->newQMetaObject(&ScriptQMainWindow::staticMetaObject,
  1087. constructor);
  1088. engine->globalObject().setProperty("QMainWindow", value);
  1089. @ The constructor calls a function to add the additional properties to the
  1090. newly created value.
  1091. @<Functions for scripting@>=
  1092. QScriptValue constructQMainWindow(QScriptContext *, QScriptEngine *engine)
  1093. {
  1094. QScriptValue object = engine->newQObject(new ScriptQMainWindow);
  1095. setQMainWindowProperties(object, engine);
  1096. return object;
  1097. }
  1098. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine)
  1099. {
  1100. setQWidgetProperties(value, engine);
  1101. value.setProperty("setCentralWidget",
  1102. engine->newFunction(QMainWindow_setCentralWidget));
  1103. value.setProperty("menuBar", engine->newFunction(QMainWindow_menuBar));
  1104. }
  1105. @ The |"setCentralWidget"| property is used for setting a widget in the main
  1106. area of the window. In \pn{} this will usually be a |QSplitter| object, but it
  1107. could also be a bare |QWidget| with a layout managing multiple widgets or a
  1108. custom widget defined in a local change. This is a simple wrapper around
  1109. |QMainWindow::setCentralWidget()|.
  1110. @<Functions for scripting@>=
  1111. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,
  1112. QScriptEngine *)
  1113. {
  1114. if(context->argumentCount() == 1)
  1115. {
  1116. QMainWindow *self = getself<QMainWindow *>(context);
  1117. QWidget *widget = argument<QWidget *>(0, context);
  1118. if(widget)
  1119. {
  1120. self->setCentralWidget(widget);
  1121. }
  1122. else
  1123. {
  1124. context->throwError("Incorrect argument type passed to "@|
  1125. "QMainWindow::setCentralWidget(). This "@|
  1126. "method requires a QWidget.");
  1127. }
  1128. }
  1129. else
  1130. {
  1131. context->throwError("Incorrect number of arguments passed to "@|
  1132. "QMainWindow::setCentralWidget(). This method "@|
  1133. "takes one QWidget as an argument.");
  1134. }
  1135. return QScriptValue();
  1136. }
  1137. @ The |"menuBar"| property requires that we expose |QMenuBar| to the scripting
  1138. environment in a limited fashion. We don'@q'@>t need to allow scripts to create a
  1139. new menu bar as it can be obtained from the window, however to add the menus to
  1140. the menu bar, we need to add a property to the |QMenuBar| object before passing
  1141. it back.
  1142. @<Functions for scripting@>=
  1143. QScriptValue QMainWindow_menuBar(QScriptContext *context, QScriptEngine *engine)
  1144. {
  1145. QScriptValue object;
  1146. if(context->argumentCount() == 0)
  1147. {
  1148. QMainWindow *self = getself<@[QMainWindow *@]>(context);
  1149. QMenuBar *bar = self->menuBar();
  1150. object = engine->newQObject(bar);
  1151. setQMenuBarProperties(object, engine);
  1152. }
  1153. else
  1154. {
  1155. context->throwError("Incorrect number of arguments passed to "@|
  1156. "QMainWindow::menuBar(). This method takes no "@|
  1157. "arguments.");
  1158. }
  1159. return object;
  1160. }
  1161. @ The previous function is the only place a new |QMenuBar| is created through
  1162. the host environment. Two functions are used in handling this object creation.
  1163. @<Function prototypes for scripting@>=
  1164. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine);
  1165. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine);
  1166. @ The first of these adds the appropriate properties to the newly created
  1167. object.
  1168. @<Functions for scripting@>=
  1169. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine)
  1170. {
  1171. setQWidgetProperties(value, engine);
  1172. value.setProperty("addMenu", engine->newFunction(QMenuBar_addMenu));
  1173. }
  1174. @ This function can be used to add new menus to a menu bar. In order to do
  1175. anything with the newly created menus, two properties are added to the |QMenu|
  1176. objects which allow actions to be added as menu items and allow separators to be
  1177. placed between groups of menu items.
  1178. At the time of this writing, there are three |QMenuBar::addMenu()| methods. This
  1179. function wraps |QMenu* QMenuBar::addMenu(const QString &title)|.
  1180. @<Functions for scripting@>=
  1181. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine)
  1182. {
  1183. QScriptValue object;
  1184. if(context->argumentCount() == 1)
  1185. {
  1186. QMenuBar *self = getself<@[QMenuBar *@]>(context);
  1187. QString title = argument<QString>(0, context);
  1188. object = engine->newQObject(self->addMenu(title));
  1189. setQMenuProperties(object, engine);
  1190. }
  1191. else
  1192. {
  1193. context->throwError("Incorrect number of arguments passed to "@|
  1194. "QMenuBar::addMenu(). This method takes one "@|
  1195. "string as an argument.");
  1196. }
  1197. return object;
  1198. }
  1199. @ These three functions allow adding items to the menu and adding separators
  1200. between groups of items.
  1201. @<Function prototypes for scripting@>=
  1202. void setQMenuProperties(QScriptValue value, QScriptEngine *engine);
  1203. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *engine);
  1204. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *engine);
  1205. @ The first of these add properties to newly created |QMenu| objects.
  1206. @<Functions for scripting@>=
  1207. void setQMenuProperties(QScriptValue value, QScriptEngine *engine)
  1208. {
  1209. setQWidgetProperties(value, engine);
  1210. value.setProperty("addAction", engine->newFunction(QMenu_addAction));
  1211. value.setProperty("addSeparator", engine->newFunction(QMenu_addSeparator));
  1212. }
  1213. @ These functions are simple wrappers around |QMenu| methods.
  1214. @<Functions for scripting@>=
  1215. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *)
  1216. {
  1217. if(context->argumentCount() == 1)
  1218. {
  1219. QMenu *self = getself<@[QMenu *@]>(context);
  1220. QAction *action = argument<QAction *>(0, context);
  1221. if(action)
  1222. {
  1223. self->addAction(action);
  1224. }
  1225. else
  1226. {
  1227. context->throwError("Incorrect argument type passed to "@|
  1228. "QMenu::addAction(). This method requires a "@|
  1229. "QAction.");
  1230. }
  1231. }
  1232. else
  1233. {
  1234. context->throwError("Incorrect number of arguments passed to "@|
  1235. "QMenu::addAction(). This method takes one "@|
  1236. "QAction as an argument.");
  1237. }
  1238. return QScriptValue();
  1239. }
  1240. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *)
  1241. {
  1242. if(context->argumentCount() == 0)
  1243. {
  1244. QMenu *self = getself<@[QMenu *@]>(context);
  1245. self->addSeparator();
  1246. }
  1247. else
  1248. {
  1249. context->throwError("Incorrect number of arguments passed to "@|
  1250. "QMenu::addSeparator(). This method takes no "@|
  1251. "arguments.");
  1252. }
  1253. return QScriptValue();
  1254. }
  1255. @* Scripting QFrame.
  1256. \noindent |QFrame| is another class for which little needs to be done. It exists
  1257. as a subclass of |QWidget| and a superclass for |QSplitter|, |QLCDNumber|, and
  1258. |QAbstractScrollArea| among other classes.
  1259. @<Function prototypes for scripting@>=
  1260. void setQFrameProperties(QScriptValue value, QScriptEngine *engine);
  1261. QScriptValue constructQFrame(QScriptContext *context, QScriptEngine *engine);
  1262. @ The constructor must be passed to the scripting engine.
  1263. @<Set up the scripting engine@>=
  1264. constructor = engine->newFunction(constructQFrame);
  1265. value = engine->newQMetaObject(&QFrame::staticMetaObject, constructor);
  1266. engine->globalObject().setProperty("QFrame", value);
  1267. @ The implementation of these functions should seem familiar.
  1268. @<Functions for scripting@>=
  1269. QScriptValue constructQFrame(QScriptContext *, QScriptEngine *engine)
  1270. {
  1271. QScriptValue object = engine->newQObject(new QFrame);
  1272. setQFrameProperties(object, engine);
  1273. return object;
  1274. }
  1275. void setQFrameProperties(QScriptValue value, QScriptEngine *engine)
  1276. {
  1277. setQWidgetProperties(value, engine);
  1278. }
  1279. @* Scripting QLabel.
  1280. \noindent When constructing an interface wholly or partially through dynamic
  1281. means rather than entirely through the XML configuration document it can
  1282. sometimes be desirable to construct |QLabel| instances. This is usually used
  1283. to provide a very small amount of text.
  1284. @<Function prototypes for scripting@>=
  1285. void setQLabelProperties(QScriptValue value, QScriptEngine *engine);
  1286. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine);
  1287. @ The constructor must be passed to the scripting engine.
  1288. @<Set up the scripting engine@>=
  1289. constructor = engine->newFunction(constructQLabel);
  1290. value = engine->newQMetaObject(&QLabel::staticMetaObject, constructor);
  1291. engine->globalObject().setProperty("QLabel", value);
  1292. @ In the constructor we allow an optional argument to specify the text of the
  1293. label.
  1294. @<Functions for scripting@>=
  1295. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine)
  1296. {
  1297. QString text;
  1298. if(context->argumentCount() == 1)
  1299. {
  1300. text = argument<QString>(0, context);
  1301. }
  1302. QScriptValue object = engine->newQObject(new QLabel(text));
  1303. setQLabelProperties(object, engine);
  1304. return object;
  1305. }
  1306. void setQLabelProperties(QScriptValue value, QScriptEngine *engine)
  1307. {
  1308. setQFrameProperties(value, engine);
  1309. }
  1310. @* Scripting QSvgWidget.
  1311. \noindent Sometimes it is useful to provide a space for simple drawings without
  1312. the need for all of the other capabilities of a web view. This was introduced
  1313. as a way to draw box plots to help guide the creation of roast specifications.
  1314. @<Function prototypes for scripting@>=
  1315. void setQSvgWidgetProperties(QScriptValue value, QScriptEngine *engine);
  1316. QScriptValue constructQSvgWidget(QScriptContext *context,
  1317. QScriptEngine *engine);
  1318. QScriptValue QSvgWidget_loadDevice(QScriptContext *context,
  1319. QScriptEngine *engine);
  1320. void addSvgWidgetToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  1321. QStack<QLayout *> *layoutStack);
  1322. @ The constructor must be passed to the scripting engine.
  1323. @<Set up the scripting engine@>=
  1324. constructor = engine->newFunction(constructQSvgWidget);
  1325. value = engine->newQMetaObject(&QSvgWidget::staticMetaObject, constructor);
  1326. engine->globalObject().setProperty("QSvgWidget", value);
  1327. @ The constructor is trivial.
  1328. @<Functions for scripting@>=
  1329. QScriptValue constructQSvgWidget(QScriptContext *,
  1330. QScriptEngine *engine)
  1331. {
  1332. QScriptValue object = engine->newQObject(new QSvgWidget);
  1333. setQSvgWidgetProperties(object, engine);
  1334. return object;
  1335. }
  1336. @ A property is added that allows loading data from a |QIODevice|.
  1337. @<Functions for scripting@>=
  1338. void setQSvgWidgetProperties(QScriptValue value, QScriptEngine *engine)
  1339. {
  1340. setQWidgetProperties(value, engine);
  1341. value.setProperty("loadDevice",
  1342. engine->newFunction(QSvgWidget_loadDevice));
  1343. }
  1344. QScriptValue QSvgWidget_loadDevice(QScriptContext *context, QScriptEngine *)
  1345. {
  1346. if(context->argumentCount() == 1)
  1347. {
  1348. QSvgWidget *self = getself<@[QSvgWidget *@]>(context);
  1349. QIODevice *device = argument<QIODevice *>(0, context);
  1350. device->reset();
  1351. QByteArray data = device->readAll();
  1352. self->load(data);
  1353. }
  1354. else
  1355. {
  1356. context->throwError("Incorrect number of arguments passed to "@|
  1357. "QSvgWidget::loadData(). This method takes one "@|
  1358. "QIODevice as an argument.");
  1359. }
  1360. return QScriptValue();
  1361. }
  1362. @ Additional work is needed to allow including this from the XML description of
  1363. a window.
  1364. @<Additional box layout elements@>=
  1365. else if(currentElement.tagName() == "svgwidget")
  1366. {
  1367. addSvgWidgetToLayout(currentElement, widgetStack, layoutStack);
  1368. }
  1369. @ The function used to create this follows the usual pattern.
  1370. @<Functions for scripting@>=
  1371. void addSvgWidgetToLayout(QDomElement element, QStack<QWidget *> *,
  1372. QStack<QLayout *> *layoutStack)
  1373. {
  1374. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  1375. QSvgWidget *widget = new QSvgWidget;
  1376. layout->addWidget(widget);
  1377. QString id = element.attribute("id");
  1378. if(!id.isEmpty())
  1379. {
  1380. widget->setObjectName(id);
  1381. }
  1382. }
  1383. @* Scripting QLineEdit.
  1384. \noindent Similarly, we may want to allow line edits in interfaces defined
  1385. through the host environment. For example, this is used for the free text
  1386. annotation control for roasters this has been configured on.
  1387. @<Function prototypes for scripting@>=
  1388. void setQLineEditProperties(QScriptValue value, QScriptEngine *engine);
  1389. QScriptValue constructQLineEdit(QScriptContext *context, QScriptEngine *engine);
  1390. @ The constructor must be passed to the host environment.
  1391. @<Set up the scripting engine@>=
  1392. constructor = engine->newFunction(constructQLineEdit);
  1393. value = engine->newQMetaObject(&QLineEdit::staticMetaObject, constructor);
  1394. engine->globalObject().setProperty("QLineEdit", value);
  1395. @ The constructor is trivial.
  1396. @<Functions for scripting@>=
  1397. QScriptValue constructQLineEdit(QScriptContext *, QScriptEngine *engine)
  1398. {
  1399. QScriptValue object = engine->newQObject(new QLineEdit());
  1400. setQLineEditProperties(object, engine);
  1401. return object;
  1402. }
  1403. @ At present all of the QLineEdit functionality exposed through this interface
  1404. is provided automatically through the meta-object system.
  1405. @<Functions for scripting@>=
  1406. void setQLineEditProperties(QScriptValue value, QScriptEngine *engine)
  1407. {
  1408. setQWidgetProperties(value, engine);
  1409. }
  1410. @* Scripting QSplitter.
  1411. \noindent The |QSplitter| class is one of the main classes used for user
  1412. interface object layout in \pn{}. To provide this class to the scripting engine,
  1413. we provide five functions: a constructor, a method for adding widgets to the
  1414. splitter, a method for saving the size of each widget in the splitter, a
  1415. method for restoring these saved sizes, and a function for adding these methods
  1416. as properties of newly created |QSplitter| objects.
  1417. @<Function prototypes for scripting@>=
  1418. QScriptValue constructQSplitter(QScriptContext *context, QScriptEngine *engine);
  1419. QScriptValue QSplitter_addWidget(QScriptContext *context,
  1420. QScriptEngine *engine);
  1421. QScriptValue QSplitter_saveState(QScriptContext *context,
  1422. QScriptEngine *engine);
  1423. QScriptValue QSplitter_restoreState(QScriptContext *context,
  1424. QScriptEngine *engine);
  1425. QScriptValue QSplitter_count(QScriptContext *context,
  1426. QScriptEngine *engine);
  1427. QScriptValue QSplitter_setCollapsible(QScriptContext *context,
  1428. QScriptEngine *engine);
  1429. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine);
  1430. @ Of these, the scripting engine must be informed of the constructor.
  1431. @<Set up the scripting engine@>=
  1432. constructor = engine->newFunction(constructQSplitter);
  1433. value = engine->newQMetaObject(&QSplitter::staticMetaObject, constructor);
  1434. engine->globalObject().setProperty("QSplitter", value);
  1435. @ The constructor creates the object and adds the required properties to it.
  1436. @<Functions for scripting@>=
  1437. QScriptValue constructQSplitter(QScriptContext *, QScriptEngine *engine)
  1438. {
  1439. QScriptValue object = engine->newQObject(new QSplitter);
  1440. setQSplitterProperties(object, engine);
  1441. return object;
  1442. }
  1443. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine)
  1444. {
  1445. setQFrameProperties(value, engine);
  1446. value.setProperty("addWidget", engine->newFunction(QSplitter_addWidget));
  1447. value.setProperty("saveState", engine->newFunction(QSplitter_saveState));
  1448. value.setProperty("restoreState",
  1449. engine->newFunction(QSplitter_restoreState));
  1450. value.setProperty("count", engine->newFunction(QSplitter_count));
  1451. value.setProperty("setCollapsible", engine->newFunction(QSplitter_setCollapsible));
  1452. }
  1453. @ The |"addWidget"| property is a simple wrapper around
  1454. |QSplitter::addWidget()|.
  1455. @<Functions for scripting@>=
  1456. QScriptValue QSplitter_addWidget(QScriptContext *context, QScriptEngine *)
  1457. {
  1458. if(context->argumentCount() == 1)
  1459. {
  1460. QSplitter *self = getself<QSplitter *>(context);
  1461. QWidget *widget = argument<QWidget *>(0, context);
  1462. if(widget)
  1463. {
  1464. self->addWidget(widget);
  1465. }
  1466. else
  1467. {
  1468. context->throwError("Incorrect argument type passed to "@|
  1469. "QSplitter::addWidget(). This method "@|
  1470. "requires a QWidget.");
  1471. }
  1472. }
  1473. else
  1474. {
  1475. context->throwError("Incorrect number of arguments passed to "@|
  1476. "QSplitter::addWidget(). This method takes one "@|
  1477. "QWidget as an argument.");
  1478. }
  1479. return QScriptValue();
  1480. }
  1481. @ The methods for saving and restoring the state of a splitter do not behave
  1482. well when the number of widgets contained in the splitter increase. This is a
  1483. problem in the logging view where we may want to allow zero width indicators
  1484. but reconfiguration can cause the number of indicators to increase. This would
  1485. result in the right most indicators such as the batch timer disappearing. Most
  1486. people do not notice the splitter handle or think to drag that to the left to
  1487. correct this issue so it would be better to save the number of indicators when
  1488. saving the state and if the number of indicators does not match, we should not
  1489. restore the obsolete saved state.
  1490. @<Functions for scripting@>=
  1491. QScriptValue QSplitter_count(QScriptContext *context, QScriptEngine *)
  1492. {
  1493. QSplitter *self = getself<QSplitter *>(context);
  1494. return QScriptValue(self->count());
  1495. }
  1496. @ When saving and restoring the state of a splitter, we always want to do this
  1497. through a |QSettings| object. For this, we take an extra argument specifying the
  1498. settings key to read from or write to. Unlike the equivalent functions called
  1499. from native code, neither of these functions called from a script will return
  1500. the data being saved.
  1501. @<Functions for scripting@>=
  1502. QScriptValue QSplitter_saveState(QScriptContext *context, QScriptEngine *)
  1503. {
  1504. if(context->argumentCount() == 1)
  1505. {
  1506. QSplitter *self = getself<QSplitter *>(context);
  1507. QString key = argument<QString>(0, context);
  1508. QSettings settings;
  1509. settings.setValue(key, self->saveState());
  1510. }
  1511. else
  1512. {
  1513. context->throwError("Incorrect number of arguments passed to "@|
  1514. "QSplitter::saveState(). This method takes one "@|
  1515. "string as an argument.");
  1516. }
  1517. return QScriptValue();
  1518. }
  1519. QScriptValue QSplitter_restoreState(QScriptContext *context, QScriptEngine *)
  1520. {
  1521. if(context->argumentCount() == 1)
  1522. {
  1523. QSplitter *self = getself<QSplitter *>(context);
  1524. QString key = argument<QString>(0, context);
  1525. QSettings settings;
  1526. self->restoreState(settings.value(key).toByteArray());
  1527. }
  1528. else
  1529. {
  1530. context->throwError("Incorrect number of arguments passed to "@|
  1531. "QSplitter::restoreState(). This method takes "@|
  1532. "one string as an argument.");
  1533. }
  1534. return QScriptValue();
  1535. }
  1536. @ Sometimes a |QSplitter| is used to make it easy to hide optional elements. In
  1537. this use case it can be useful to indicate that required elements cannot be
  1538. collapsed.
  1539. @<Functions for scripting@>=
  1540. QScriptValue QSplitter_setCollapsible(QScriptContext *context, QScriptEngine *)
  1541. {
  1542. if(context->argumentCount() == 2)
  1543. {
  1544. QSplitter *self = getself<QSplitter *>(context);
  1545. self->setCollapsible(argument<int>(0, context), argument<bool>(1, context));
  1546. }
  1547. else
  1548. {
  1549. context->throwError("Incorrect number of arguments");
  1550. }
  1551. return QScriptValue();
  1552. }
  1553. @* Scripting Layout classes.
  1554. \noindent Layout classes simplify managing the size and position of widgets in a
  1555. user interface. Qt provides several such classes, including |QBoxLayout| which
  1556. can be used to construct a variety of different interfaces. As widgets
  1557. containing a layout should not really need to care which layout is being used,
  1558. the |QLayout| class acts as an abstract base for all layout classes. A bare
  1559. |QLayout| will never be constructed, however subclasses can make use of the
  1560. |addWidget()| property.
  1561. @<Function prototypes for scripting@>=
  1562. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1563. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1564. @ The implementation is trivial.
  1565. @<Functions for scripting@>=
  1566. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1567. {
  1568. setQLayoutItemProperties(value, engine);
  1569. value.setProperty("addWidget", engine->newFunction(QLayout_addWidget));
  1570. }
  1571. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1572. {
  1573. if(context->argumentCount() == 1)
  1574. {
  1575. QLayout *self = getself<QLayout *>(context);
  1576. QWidget *widget = argument<QWidget *>(0, context);
  1577. if(widget)
  1578. {
  1579. self->addWidget(widget);
  1580. }
  1581. else
  1582. {
  1583. context->throwError("Incorrect argument type passed to "@|
  1584. "QLayout::addWidget(). This method requires "@|
  1585. "a QWidget.");
  1586. }
  1587. }
  1588. else
  1589. {
  1590. context->throwError("Incorrect number of arguments passed to "@|
  1591. "QLayout::addWidget(). This method takes one "@|
  1592. "QWidget as an argument.");
  1593. }
  1594. return QScriptValue();
  1595. }
  1596. @ |QBoxLayout| is a more interesting layout class. This allows widgets to be
  1597. arranged in a single row or column and can be used, for example, to arrange a
  1598. row of buttons as in figure \secno.
  1599. \medskip
  1600. \resizebox*{6.3in}{!}{\includegraphics{boxlayoutexample}}
  1601. \smallskip
  1602. \centerline{Figure \secno: Buttons in a |QBoxLayout|.}
  1603. \medskip
  1604. This class makes use of the |addWidget()| method from |QLayout|.
  1605. @<Function prototypes for scripting@>=
  1606. QScriptValue constructQBoxLayout(QScriptContext *context,
  1607. QScriptEngine *engine);
  1608. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1609. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *engine);
  1610. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1611. @ The script constructor must be passed to the scripting engine.
  1612. @<Set up the scripting engine@>=
  1613. constructor = engine->newFunction(constructQBoxLayout);
  1614. value = engine->newQMetaObject(&QBoxLayout::staticMetaObject, constructor);
  1615. engine->globalObject().setProperty("QBoxLayout", value);
  1616. @ The implementation of these functions should seem familiar by now. Note that
  1617. while a horizontal layout is provided by default, this can be changed from the
  1618. script once the layout is created.
  1619. @<Functions for scripting@>=
  1620. QScriptValue constructQBoxLayout(QScriptContext *, QScriptEngine *engine)
  1621. {
  1622. QScriptValue object =
  1623. engine->newQObject(new QBoxLayout(QBoxLayout::LeftToRight));
  1624. setQBoxLayoutProperties(object, engine);
  1625. return object;
  1626. }
  1627. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1628. {
  1629. setQLayoutProperties(value, engine);
  1630. value.setProperty("addLayout", engine->newFunction(QBoxLayout_addLayout));
  1631. value.setProperty("addWidget", engine->newFunction(QBoxLayout_addWidget));
  1632. }
  1633. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *)
  1634. {
  1635. if(context->argumentCount() > 0 && context->argumentCount() < 3)
  1636. {
  1637. QBoxLayout *self = getself<QBoxLayout *>(context);
  1638. QLayout *layout = argument<QLayout *>(0, context);
  1639. int stretch = 0;
  1640. if(context->argumentCount() == 2)
  1641. {
  1642. stretch = argument<int>(1, context);
  1643. }
  1644. if(layout)
  1645. {
  1646. self->addLayout(layout, stretch);
  1647. }
  1648. else
  1649. {
  1650. context->throwError("Incorrect argument type passed to "@|
  1651. "QLayout::addLayout(). This method requires "@|
  1652. "a QLayout.");
  1653. }
  1654. }
  1655. else
  1656. {
  1657. context->throwError("Incorrect number of arguments passed to "@|
  1658. "QLayout::addLayout(). This method takes one "@|
  1659. "QLayout as an argument and optionally one integer.");
  1660. }
  1661. return QScriptValue();
  1662. }
  1663. @ We override the base class wrapper for |addWidget| to add two optional
  1664. arguments: one specifies the stretch factor of the widget and the other
  1665. specifies the alignment of the widget within the layout.
  1666. @<Functions for scripting@>=
  1667. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1668. {
  1669. if(context->argumentCount() > 0 && context->argumentCount() < 4)
  1670. {
  1671. QBoxLayout *self = getself<QBoxLayout *>(context);
  1672. QWidget *widget = argument<QWidget *>(0, context);
  1673. int stretch = 0;
  1674. Qt::Alignment alignment = 0;
  1675. if(context->argumentCount() > 1)
  1676. {
  1677. stretch = argument<int>(1, context);
  1678. }
  1679. if(context->argumentCount() > 2)
  1680. {
  1681. alignment = (Qt::Alignment)(argument<int>(2, context));
  1682. }
  1683. if(widget)
  1684. {
  1685. self->addWidget(widget, stretch, alignment);
  1686. }
  1687. else
  1688. {
  1689. context->throwError("Incorrect argument type passed to "@|
  1690. "QBoxLayout::addWidget(). This method requires "@|
  1691. "a QWidget.");
  1692. }
  1693. }
  1694. else
  1695. {
  1696. context->throwError("Incorrect number of arguments passed to "@|
  1697. "QBoxLayout::addWidget(). This method takes one "@|
  1698. "QWidget and optionally up to two integers as "@|
  1699. "arguments.");
  1700. }
  1701. return QScriptValue();
  1702. }
  1703. @* Scripting QAction.
  1704. \noindent The |QAction| class is used in \pn{} to create menu items and respond
  1705. to the selection of these items. Three functions are required for our scripting
  1706. needs with regard to this class.
  1707. @<Function prototypes for scripting@>=
  1708. QScriptValue constructQAction(QScriptContext *context, QScriptEngine *engine);
  1709. QScriptValue QAction_setShortcut(QScriptContext *context,
  1710. QScriptEngine *engine);
  1711. void setQActionProperties(QScriptValue value, QScriptEngine *engine);
  1712. @ The scripting engine must be informed of the constructor.
  1713. @<Set up the scripting engine@>=
  1714. constructor = engine->newFunction(constructQAction);
  1715. value = engine->newQMetaObject(&QAction::staticMetaObject, constructor);
  1716. engine->globalObject().setProperty("QAction", value);
  1717. @ The constructor is simple, however some might sensibly question why the
  1718. |"setShortcut"| property is needed at all. Why not have scripts simply set the
  1719. |shortcut| property of the |QAction| directly? The answer to this is that the
  1720. property expects data of the |QKeySequence| type. While this can be created from
  1721. a |QString|, passing a string to the property through the scripting engine did
  1722. not work at the time this was written.
  1723. @<Functions for scripting@>=
  1724. QScriptValue constructQAction(QScriptContext *, QScriptEngine *engine)
  1725. {
  1726. QScriptValue object = engine->newQObject(new QAction(NULL));
  1727. setQActionProperties(object, engine);
  1728. return object;
  1729. }
  1730. void setQActionProperties(QScriptValue value, QScriptEngine *engine)
  1731. {
  1732. setQObjectProperties(value, engine);
  1733. value.setProperty("setShortcut", engine->newFunction(QAction_setShortcut));
  1734. }
  1735. QScriptValue QAction_setShortcut(QScriptContext *context, QScriptEngine *)
  1736. {
  1737. if(context->argumentCount() == 1)
  1738. {
  1739. QAction *self = getself<@[QAction *@]>(context);
  1740. self->setShortcut(argument<QString>(0, context));
  1741. }
  1742. else
  1743. {
  1744. context->throwError("Incorrect number of arguments passed to "@|
  1745. "QAction::setShortcut(). This method takes one "@|
  1746. "string as an argument.");
  1747. }
  1748. return QScriptValue();
  1749. }
  1750. @* Scripting QFileDialog.
  1751. \noindent |QFileDialog| provides two static member functions which is all that
  1752. we need. The objects returned from these methods are built on the |QDialog|
  1753. abstract base class.
  1754. @<Function prototypes for scripting@>=
  1755. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1756. QScriptEngine *engine);
  1757. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1758. QScriptEngine *engine);
  1759. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine);
  1760. void setQDialogProperties(QScriptValue value, QScriptEngine *engine);
  1761. @ The scripting engine must be informed of the wrapper functions for the static
  1762. methods.
  1763. @<Set up the scripting engine@>=
  1764. value = engine->newQMetaObject(&QFileDialog::staticMetaObject);
  1765. value.setProperty("getOpenFileName",
  1766. engine->newFunction(QFileDialog_getOpenFileName));
  1767. value.setProperty("getSaveFileName",
  1768. engine->newFunction(QFileDialog_getSaveFileName));
  1769. engine->globalObject().setProperty("QFileDialog", value);
  1770. @ This function is just a simple wrapper around the |QFileDialog| method, but
  1771. the object returned has any properties added to the base class available.
  1772. @<Functions for scripting@>=
  1773. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1774. QScriptEngine *engine)
  1775. {
  1776. QScriptValue retval;
  1777. if(context->argumentCount() == 3)
  1778. {
  1779. QWidget *widget = argument<QWidget *>(0, context);
  1780. if(widget)
  1781. {
  1782. QString caption = argument<QString>(1, context);
  1783. QString dir = argument<QString>(2, context);
  1784. retval = QScriptValue(engine,
  1785. QFileDialog::getOpenFileName(widget, caption,
  1786. dir, "", 0, 0));
  1787. setQFileDialogProperties(retval, engine);
  1788. }
  1789. else
  1790. {
  1791. context->throwError("Incorrect argument type passed to "@|
  1792. "QFileDialog::getOpenFileName(). The first "@|
  1793. "argument to this method must be a QWidget.");
  1794. }
  1795. }
  1796. else
  1797. {
  1798. context->throwError("Incorrect number of arguments passed to "@|
  1799. "QFileDialog::getOpenFileName(). This method "@|
  1800. "takes one QWidget followed by two strings for a "@|
  1801. "total of three arguments.");
  1802. }
  1803. return retval;
  1804. }
  1805. @ Similarly, this just wraps |QFileDialog::getSaveFileName()|.
  1806. @<Functions for scripting@>=
  1807. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1808. QScriptEngine *engine)
  1809. {
  1810. QScriptValue retval;
  1811. if(context->argumentCount() == 3)
  1812. {
  1813. QWidget *widget = argument<QWidget *>(0, context);
  1814. if(widget)
  1815. {
  1816. QString caption = argument<QString>(1, context);
  1817. QString dir = argument<QString>(2, context);
  1818. retval = QScriptValue(engine,
  1819. QFileDialog::getSaveFileName(widget, caption,
  1820. dir, "", 0, 0));
  1821. setQFileDialogProperties(retval, engine);
  1822. }
  1823. else
  1824. {
  1825. context->throwError("Incorrect argument type passed to "@|
  1826. "QFileDialog::getSaveFileName(). The first "@|
  1827. "argument to this method must be a QWidget.");
  1828. }
  1829. }
  1830. else
  1831. {
  1832. context->throwError("Incorrect number of arguments passed to "@|
  1833. "QFileDialog::getSaveFileName(). This method "@|
  1834. "takes one QWidget followed by two strings for a "@|
  1835. "total of three arguments.");
  1836. }
  1837. return retval;
  1838. }
  1839. @ Adding object hierarchy properties to the objects created above is simple.
  1840. @<Functions for scripting@>=
  1841. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine)
  1842. {
  1843. setQDialogProperties(value, engine);
  1844. }
  1845. void setQDialogProperties(QScriptValue value, QScriptEngine *engine)
  1846. {
  1847. setQWidgetProperties(value, engine);
  1848. }
  1849. @* Scripting QFile.
  1850. \noindent When using a |QFile| in a script, we only need the constructor and two
  1851. functions for hooking it in with the rest of the object hierarchy.
  1852. @<Function prototypes for scripting@>=
  1853. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine);
  1854. void setQFileProperties(QScriptValue value, QScriptEngine *engine);
  1855. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine);
  1856. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine);
  1857. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *engine);
  1858. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *engine);
  1859. QScriptValue QIODevice_readToString(QScriptContext *context,
  1860. QScriptEngine *engine);
  1861. QScriptValue QIODevice_putChar(QScriptContext *context, QScriptEngine *engine);
  1862. QScriptValue QIODevice_writeString(QScriptContext *context, QScriptEngine *engine);
  1863. QScriptValue QIODevice_writeBytes(QScriptContext *context, QScriptEngine *engine);
  1864. QScriptValue QIODevice_readBytes(QScriptContext *context, QScriptEngine *engine);
  1865. QScriptValue QIODevice_peek(QScriptContext *context, QScriptEngine *engine);
  1866. QScriptValue QIODevice_read(QScriptContext *context, QScriptEngine *engine);
  1867. @ This function is passed to the scripting engine.
  1868. @<Set up the scripting engine@>=
  1869. constructor = engine->newFunction(constructQFile);
  1870. value = engine->newQMetaObject(&QFile::staticMetaObject, constructor);
  1871. engine->globalObject().setProperty("QFile", value);
  1872. @ The implementation is trivial.
  1873. @<Functions for scripting@>=
  1874. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine)
  1875. {
  1876. QScriptValue object =
  1877. engine->newQObject(new QFile(argument<QString>(0, context)));@/
  1878. setQFileProperties(object, engine);
  1879. return object;
  1880. }
  1881. @ |QFile| gets a wrapper around |remove()| to support deleting temporary files.
  1882. @<Functions for scripting@>=
  1883. void setQFileProperties(QScriptValue value, QScriptEngine *engine)
  1884. {
  1885. setQIODeviceProperties(value, engine);
  1886. value.setProperty("remove", engine->newFunction(QFile_remove));
  1887. }
  1888. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine)
  1889. {
  1890. QFile *self = getself<QFile *>(context);
  1891. bool retval = self->remove();
  1892. return QScriptValue(engine, retval);
  1893. }
  1894. @ Although we aren'@q'@>t going to create any instances of |QIODevice| directly,
  1895. subclasses such as |QFile| and |QBuffer| get two additional properties for
  1896. opening and closing the device.
  1897. In order to solve some class interoperability issues, a convenience method is
  1898. also added which is equivalent to creating a |QString| from the |QByteArray|
  1899. returned from the |readAll()| method.
  1900. @<Functions for scripting@>=
  1901. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine)
  1902. {
  1903. setQObjectProperties(value, engine);
  1904. value.setProperty("open", engine->newFunction(QIODevice_open));
  1905. value.setProperty("close", engine->newFunction(QIODevice_close));
  1906. value.setProperty("readToString",
  1907. engine->newFunction(QIODevice_readToString));
  1908. value.setProperty("putChar", engine->newFunction(QIODevice_putChar));
  1909. value.setProperty("writeString", engine->newFunction(QIODevice_writeString));
  1910. value.setProperty("writeBytes", engine->newFunction(QIODevice_writeBytes));
  1911. value.setProperty("readBytes", engine->newFunction(QIODevice_readBytes));
  1912. value.setProperty("peek", engine->newFunction(QIODevice_peek));
  1913. value.setProperty("read", engine->newFunction(QIODevice_read));
  1914. }
  1915. @ These are simple wrappers. In the case of the |open()| property, one argument
  1916. may be passed specifying the mode used for opening. The supported values for
  1917. this are 1 (Read Only), 2 (Write Only), and 3 (Read Write). If this argument is
  1918. not passed, it is assumed that the user wants read and write access.
  1919. @<Functions for scripting@>=
  1920. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *)
  1921. {
  1922. QIODevice *self = getself<QIODevice *>(context);
  1923. bool retval = false;
  1924. if(context->argumentCount() == 1)
  1925. {
  1926. switch(argument<int>(0, context))
  1927. {
  1928. case 1:
  1929. retval = self->open(QIODevice::ReadOnly);
  1930. break;
  1931. case 2:
  1932. retval = self->open(QIODevice::WriteOnly);
  1933. break;
  1934. case 3:
  1935. retval = self->open(QIODevice::ReadWrite);
  1936. break;
  1937. default:
  1938. break;
  1939. }
  1940. }
  1941. else
  1942. {
  1943. retval = self->open(QIODevice::ReadWrite);
  1944. }
  1945. return QScriptValue(retval);
  1946. }
  1947. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *)
  1948. {
  1949. QIODevice *self = getself<QIODevice *>(context);
  1950. self->close();
  1951. return QScriptValue();
  1952. }
  1953. @ The |readToString()| method is a simple extension of |QIODevice::readAll()| to
  1954. interface with classes that expect document data in the form of a string. Most
  1955. notably, this includes |QWebView|.
  1956. @<Functions for scripting@>=
  1957. QScriptValue QIODevice_readToString(QScriptContext *context, QScriptEngine *)
  1958. {
  1959. QIODevice *self = getself<QIODevice *>(context);
  1960. self->reset();
  1961. return QScriptValue(QString(self->readAll()));
  1962. }
  1963. @ In support of serial port communications, wrappers around two methods for
  1964. writing data have been added. As these are valid for other classes derived from
  1965. |QIODevice|, they are added here so the functionality is available more
  1966. broadly.
  1967. As we are unable to pass a type that guarantees only a single character, we
  1968. instead accept a string and only pass along the first character.
  1969. @<Functions for scripting@>=
  1970. QScriptValue QIODevice_putChar(QScriptContext *context, QScriptEngine *)
  1971. {
  1972. QIODevice *self = getself<QIODevice *>(context);
  1973. if(context->argumentCount() == 1)
  1974. {
  1975. return QScriptValue(self->putChar(argument<QString>(0, context).toUtf8().at(0)));
  1976. }
  1977. context->throwError("Incorrect number of arguments passed to "@|
  1978. "QIODevice::putChar()");
  1979. return QScriptValue();
  1980. }
  1981. @ Two wrappers are provided around |QIODevice::write()| for outputting
  1982. multi-byte data. If we are writing strings that are valid UTF-8, we can use the
  1983. |writeString| wrapper, but if we require full control over exactly which bytes
  1984. are output, the |writeBytes| wrapper is more appropriate.
  1985. @<Functions for scripting@>=
  1986. QScriptValue QIODevice_writeString(QScriptContext *context, QScriptEngine *)
  1987. {
  1988. QIODevice *self = getself<QIODevice *>(context);
  1989. if(context->argumentCount() == 1)
  1990. {
  1991. self->write(argument<QString>(0, context).toUtf8());
  1992. }
  1993. else
  1994. {
  1995. context->throwError("Incorrect number of arguments passed to "@|
  1996. "QIODevice::writeString()");
  1997. }
  1998. return QScriptValue();
  1999. }
  2000. QScriptValue QIODevice_writeBytes(QScriptContext *context, QScriptEngine *)
  2001. {
  2002. QIODevice *self = getself<QIODevice *>(context);
  2003. if(context->argumentCount() == 1)
  2004. {
  2005. self->write(argument<QByteArray>(0, context));
  2006. }
  2007. else
  2008. {
  2009. context->throwError("Incorrect number of arguments passed to "@|
  2010. "QIODevice::writeBytes()");
  2011. }
  2012. return QScriptValue();
  2013. }
  2014. @ The readBytes method is an alternate wrapper around |QByteArray::readAll()|
  2015. which returns the |QByteArray| instead of converting this to a |QString|.
  2016. @<Functions for scripting@>=
  2017. QScriptValue QIODevice_readBytes(QScriptContext *context, QScriptEngine *engine)
  2018. {
  2019. QIODevice *self = getself<QIODevice *>(context);
  2020. QScriptValue value = engine->toScriptValue<QByteArray>(self->readAll());
  2021. setQByteArrayProperties(value, engine);
  2022. return value;
  2023. }
  2024. @ Wrappers around |peek()| and |read()| are also provided.
  2025. @<Functions for scripting@>=
  2026. QScriptValue QIODevice_peek(QScriptContext *context, QScriptEngine *engine)
  2027. {
  2028. QIODevice *self = getself<QIODevice *>(context);
  2029. QScriptValue value = engine->toScriptValue<QByteArray>(
  2030. self->peek(argument<int>(0, context)));
  2031. setQByteArrayProperties(value, engine);
  2032. return value;
  2033. }
  2034. QScriptValue QIODevice_read(QScriptContext *context, QScriptEngine *engine)
  2035. {
  2036. QIODevice *self = getself<QIODevice *>(context);
  2037. QScriptValue value = engine->toScriptValue<QByteArray>(
  2038. self->read(argument<int>(0, context)));
  2039. setQByteArrayProperties(value, engine);
  2040. return value;
  2041. }
  2042. @* Scripting QProcess.
  2043. \noindent Sometimes it is useful to have \pn work with an external program.
  2044. The initial use case was document generation by typesetting instructions to a
  2045. file and then running \TeX to generate a shelf sign or a sheet of labels.
  2046. Other likely use cases include interfacing with external programs that output
  2047. measurement streams. There are several methods which we may want to expose,
  2048. however this is being done only as needed.
  2049. @<Function prototypes for scripting@>=
  2050. QScriptValue constructQProcess(QScriptContext *context, QScriptEngine *engine);
  2051. void setQProcessProperties(QScriptValue value, QScriptEngine *engine);
  2052. QScriptValue QProcess_execute(QScriptContext *context, QScriptEngine *engine);
  2053. QScriptValue QProcess_startDetached(QScriptContext *context, QScriptEngine *engine);
  2054. QScriptValue QProcess_setWorkingDirectory(QScriptContext *context, QScriptEngine *engine);
  2055. QScriptValue QProcess_start(QScriptContext *context, QScriptEngine *engine);
  2056. @ We follow the same pattern with this as with many other types.
  2057. @<Set up the scripting engine@>=
  2058. constructor = engine->newFunction(constructQProcess);
  2059. value = engine->newQMetaObject(&QProcess::staticMetaObject, constructor);
  2060. engine->globalObject().setProperty("QProcess", value);
  2061. @ The constructor is trivial.
  2062. @<Functions for scripting@>=
  2063. QScriptValue constructQProcess(QScriptContext *, QScriptEngine *engine)
  2064. {
  2065. QScriptValue object = engine->newQObject(new QProcess);
  2066. setQProcessProperties(object, engine);
  2067. return object;
  2068. }
  2069. @ As |QProcess| is a |QIODevice| we inherit some properties from that. We also
  2070. expose some details that are specific to |QProcess|.
  2071. @<Functions for scripting@>=
  2072. void setQProcessProperties(QScriptValue value, QScriptEngine *engine)
  2073. {
  2074. setQIODeviceProperties(value, engine);
  2075. value.setProperty("execute", engine->newFunction(QProcess_execute));
  2076. value.setProperty("startDetached", engine->newFunction(QProcess_startDetached));
  2077. value.setProperty("setWorkingDirectory", engine->newFunction(QProcess_setWorkingDirectory));
  2078. value.setProperty("start", engine->newFunction(QProcess_start));
  2079. }
  2080. @ The |execute()| method comes in two flavors: one with arguments and one without.
  2081. We always call the one with arguments and simply pass in an empty list if no
  2082. arguments are specified.
  2083. @<Functions for scripting@>=
  2084. QScriptValue QProcess_execute(QScriptContext *context, QScriptEngine *)
  2085. {
  2086. QProcess *self = getself<QProcess *>(context);
  2087. QString program = argument<QString>(0, context);
  2088. QStringList arguments = QStringList();
  2089. if(context->argumentCount() > 1) {
  2090. arguments = argument<QVariant>(1, context).toStringList();
  2091. }
  2092. int retval = self->execute(program, arguments);
  2093. return QScriptValue(retval);
  2094. }
  2095. @ Similarly |startDetached()| can be called in a few different ways.
  2096. @<Functions for scripting@>=
  2097. QScriptValue QProcess_startDetached(QScriptContext *context, QScriptEngine *)
  2098. {
  2099. QProcess *self = getself<QProcess *>(context);
  2100. QString program = argument<QString>(0, context);
  2101. QStringList arguments = QStringList();
  2102. if(context->argumentCount() > 1) {
  2103. arguments = argument<QVariant>(1, context).toStringList();
  2104. }
  2105. QString workingDirectory = "";
  2106. if(context->argumentCount() > 2) {
  2107. workingDirectory = argument<QString>(2, context);
  2108. }
  2109. bool retval;
  2110. switch(context->argumentCount())
  2111. {
  2112. case 1:
  2113. retval = self->startDetached(program);
  2114. break;
  2115. case 2:
  2116. retval = self->startDetached(program, arguments);
  2117. break;
  2118. case 3:
  2119. retval = self->startDetached(program, arguments, workingDirectory);
  2120. break;
  2121. default:
  2122. retval = false;
  2123. }
  2124. return QScriptValue(retval);
  2125. }
  2126. @ Sometimes we care about the working directory for our program.
  2127. @<Functions for scripting@>=
  2128. QScriptValue QProcess_setWorkingDirectory(QScriptContext *context, QScriptEngine *)
  2129. {
  2130. QProcess *self = getself<QProcess *>(context);
  2131. QString directory = argument<QString>(0, context);
  2132. self->setWorkingDirectory(directory);
  2133. return QScriptValue();
  2134. }
  2135. @ When using the |start()| method we always assume that we want read and write
  2136. access.
  2137. @<Functions for scripting@>=
  2138. QScriptValue QProcess_start(QScriptContext *context, QScriptEngine *)
  2139. {
  2140. QProcess *self = getself<QProcess *>(context);
  2141. QString program = argument<QString>(0, context);
  2142. QStringList arguments = QStringList();
  2143. if(context->argumentCount() > 1) {
  2144. arguments = argument<QVariant>(1, context).toStringList();
  2145. }
  2146. self->start(program, arguments);
  2147. return QScriptValue();
  2148. }
  2149. @ In order to work with |QByteArray| this should also be exposed to the host
  2150. environment.
  2151. @<Function prototypes for scripting@>=
  2152. QScriptValue QByteArray_toScriptValue(QScriptEngine *engine, const QByteArray &bytes);
  2153. void QByteArray_fromScriptValue(const QScriptValue &value, QByteArray &bytes);
  2154. QScriptValue constructQByteArray(QScriptContext *context, QScriptEngine *engine);
  2155. void setQByteArrayProperties(QScriptValue value, QScriptEngine *engine);
  2156. QScriptValue QByteArray_fromHex(QScriptContext *context, QScriptEngine *engine);
  2157. QScriptValue QByteArray_getAt(QScriptContext *context, QScriptEngine *engine);
  2158. QScriptValue QByteArray_setAt(QScriptContext *context, QScriptEngine *engine);
  2159. QScriptValue QByteArray_appendBytes(QScriptContext *context, QScriptEngine *engine);
  2160. QScriptValue QByteArray_appendString(QScriptContext *context, QScriptEngine *engine);
  2161. QScriptValue QByteArray_size(QScriptContext *context, QScriptEngine *engine);
  2162. QScriptValue QByteArray_left(QScriptContext *context, QScriptEngine *engine);
  2163. QScriptValue QByteArray_right(QScriptContext *context, QScriptEngine *engine);
  2164. QScriptValue QByteArray_mid(QScriptContext *context, QScriptEngine *engine);
  2165. QScriptValue QByteArray_chop(QScriptContext *context, QScriptEngine *engine);
  2166. QScriptValue QByteArray_remove(QScriptContext *context, QScriptEngine *engine);
  2167. QScriptValue QByteArray_toInt8(QScriptContext *context, QScriptEngine *engine);
  2168. QScriptValue QByteArray_toInt16(QScriptContext *context, QScriptEngine *engine);
  2169. QScriptValue QByteArray_toInt32(QScriptContext *context, QScriptEngine *engine);
  2170. QScriptValue QByteArray_toFloat(QScriptContext *context, QScriptEngine *engine);
  2171. QScriptValue QByteArray_toDouble(QScriptContext *context, QScriptEngine *engine);
  2172. @ First, we provide some functionns for moving array data across the
  2173. language barrier.
  2174. @<Functions for scripting@>=
  2175. QScriptValue QByteArray_toScriptValue(QScriptEngine *engine, const QByteArray &bytes)
  2176. {
  2177. QScriptValue object = engine->newVariant(QVariant(bytes));
  2178. setQByteArrayProperties(object, engine);
  2179. return object;
  2180. }
  2181. void QByteArray_fromScriptValue(const QScriptValue &value, QByteArray &bytes)
  2182. {
  2183. bytes = value.toVariant().toByteArray();
  2184. }
  2185. @ We register this our conversion functions and allow creation of new arrays
  2186. next.
  2187. @<Set up the scripting engine@>=
  2188. qScriptRegisterMetaType(engine, QByteArray_toScriptValue, QByteArray_fromScriptValue);
  2189. constructor = engine->newFunction(constructQByteArray);
  2190. engine->globalObject().setProperty("QByteArray", constructor);
  2191. @ The constructor is straightforward.
  2192. @<Functions for scripting@>=
  2193. QScriptValue constructQByteArray(QScriptContext *, QScriptEngine *engine)
  2194. {
  2195. QScriptValue object = engine->toScriptValue<QByteArray>(QByteArray());
  2196. setQByteArrayProperties(object, engine);
  2197. return object;
  2198. }
  2199. @ There are many methods which are not automatically available which we may
  2200. want to have wrappers around. These should be added as required.
  2201. @<Functions for scripting@>=
  2202. void setQByteArrayProperties(QScriptValue value, QScriptEngine *engine)
  2203. {
  2204. value.setProperty("fromHex", engine->newFunction(QByteArray_fromHex));
  2205. value.setProperty("getAt", engine->newFunction(QByteArray_getAt));
  2206. value.setProperty("setAt", engine->newFunction(QByteArray_setAt));
  2207. value.setProperty("appendBytes", engine->newFunction(QByteArray_appendBytes));
  2208. value.setProperty("appendString", engine->newFunction(QByteArray_appendString));
  2209. value.setProperty("size", engine->newFunction(QByteArray_size));
  2210. value.setProperty("left", engine->newFunction(QByteArray_left));
  2211. value.setProperty("right", engine->newFunction(QByteArray_right));
  2212. value.setProperty("mid", engine->newFunction(QByteArray_mid));
  2213. value.setProperty("chop", engine->newFunction(QByteArray_chop));
  2214. value.setProperty("remove", engine->newFunction(QByteArray_remove));
  2215. value.setProperty("toInt8", engine->newFunction(QByteArray_toInt8));
  2216. value.setProperty("toInt16", engine->newFunction(QByteArray_toInt16));
  2217. value.setProperty("toInt32", engine->newFunction(QByteArray_toInt32));
  2218. value.setProperty("toFloat", engine->newFunction(QByteArray_toFloat));
  2219. value.setProperty("toDouble", engine->newFunction(QByteArray_toDouble));
  2220. }
  2221. @ Perhaps the easiest way to deal with fixed byte strings for serial
  2222. communications across script boundaries is to use a hex encoded string.
  2223. @<Functions for scripting@>=
  2224. QScriptValue QByteArray_fromHex(QScriptContext *context, QScriptEngine *engine)
  2225. {
  2226. QByteArray self = getself<QByteArray>(context);
  2227. QByteArray retval;
  2228. retval = self.fromHex(argument<QString>(0, context).toUtf8());
  2229. QScriptValue value = engine->toScriptValue<QByteArray>(retval);
  2230. setQByteArrayProperties(value, engine);
  2231. return value;
  2232. }
  2233. @ A pair of methods is provided for getting and setting values at a particular
  2234. byte.
  2235. @<Functions for scripting@>=
  2236. QScriptValue QByteArray_getAt(QScriptContext *context, QScriptEngine *)
  2237. {
  2238. QByteArray self = getself<QByteArray>(context);
  2239. return QScriptValue((int)(self.at(argument<int>(0, context))));
  2240. }
  2241. QScriptValue QByteArray_setAt(QScriptContext *context, QScriptEngine *)
  2242. {
  2243. QByteArray self = getself<QByteArray>(context);
  2244. self[argument<int>(0, context)] = (char)(argument<int>(1, context));
  2245. return QScriptValue();
  2246. }
  2247. @ Methods are provided for appending either another |QByteArray| or a string
  2248. to a |QByteArray|. The only difference between these functions is the expected
  2249. argument type.
  2250. @<Functions for scripting@>=
  2251. QScriptValue QByteArray_appendBytes(QScriptContext *context, QScriptEngine *engine)
  2252. {
  2253. QByteArray self = getself<QByteArray>(context);
  2254. QScriptValue value =
  2255. engine->toScriptValue<QByteArray>(
  2256. self.append(argument<QByteArray>(0, context)));
  2257. setQByteArrayProperties(value, engine);
  2258. return value;
  2259. }
  2260. QScriptValue QByteArray_appendString(QScriptContext *context, QScriptEngine *engine)
  2261. {
  2262. QByteArray self = getself<QByteArray>(context);
  2263. QScriptValue value = engine->toScriptValue<QByteArray>(
  2264. self.append(argument<QString>(0, context)));
  2265. setQByteArrayProperties(value, engine);
  2266. return value;
  2267. }
  2268. @ Checking the size of our byte array frequently a requirement.
  2269. @<Functions for scripting@>=
  2270. QScriptValue QByteArray_size(QScriptContext *context, QScriptEngine *)
  2271. {
  2272. QByteArray self = getself<QByteArray>(context);
  2273. return QScriptValue(self.size());
  2274. }
  2275. @ It is also frequently useful to be able to work with specific parts of a byte
  2276. array, so a few methods are provided for carving these up.
  2277. @<Functions for scripting@>=
  2278. QScriptValue QByteArray_left(QScriptContext *context, QScriptEngine *engine)
  2279. {
  2280. QByteArray self = getself<QByteArray>(context);
  2281. QScriptValue value = engine->toScriptValue<QByteArray>(
  2282. self.left(argument<int>(0, context)));
  2283. setQByteArrayProperties(value, engine);
  2284. return value;
  2285. }
  2286. QScriptValue QByteArray_right(QScriptContext *context, QScriptEngine *engine)
  2287. {
  2288. QByteArray self = getself<QByteArray>(context);
  2289. QScriptValue value = engine->toScriptValue<QByteArray>(
  2290. self.right(argument<int>(0, context)));
  2291. setQByteArrayProperties(value, engine);
  2292. return value;
  2293. }
  2294. QScriptValue QByteArray_mid(QScriptContext *context, QScriptEngine *engine)
  2295. {
  2296. QByteArray self = getself<QByteArray>(context);
  2297. int length = -1;
  2298. if(context->argumentCount() > 1)
  2299. {
  2300. length = argument<int>(1, context);
  2301. }
  2302. QScriptValue value = engine->toScriptValue<QByteArray>(
  2303. self.mid(argument<int>(0, context), length));
  2304. setQByteArrayProperties(value, engine);
  2305. return value;
  2306. }
  2307. @ We may also want to remove bytes from an array.
  2308. @<Functions for scripting@>=
  2309. QScriptValue QByteArray_chop(QScriptContext *context, QScriptEngine *)
  2310. {
  2311. QByteArray self = getself<QByteArray>(context);
  2312. self.chop(argument<int>(0, context));
  2313. return QScriptValue();
  2314. }
  2315. QScriptValue QByteArray_remove(QScriptContext *context, QScriptEngine *engine)
  2316. {
  2317. QByteArray self = getself<QByteArray>(context);
  2318. QScriptValue value = engine->toScriptValue<QByteArray>(
  2319. self.remove(argument<int>(0, context), argument<int>(1, context)));
  2320. setQByteArrayProperties(value, engine);
  2321. return value;
  2322. }
  2323. @ When receiving data in a byte array, bytes are sometimes intended to
  2324. represent 8, 16, or 32 bit integers. In such cases we often want to perform
  2325. some computation on these values so having the ability to split off that
  2326. portion of the array (for example, with |mid()|) and convert to a Number is
  2327. useful.
  2328. @<Functions for scripting@>=
  2329. QScriptValue QByteArray_toInt8(QScriptContext *context, QScriptEngine *)
  2330. {
  2331. QByteArray self = getself<QByteArray>(context);
  2332. int value = 0;
  2333. char *bytes = (char *)&value;
  2334. bytes[0] = self[0];
  2335. return QScriptValue(value);
  2336. }
  2337. QScriptValue QByteArray_toInt16(QScriptContext *context, QScriptEngine *)
  2338. {
  2339. QByteArray self = getself<QByteArray>(context);
  2340. int value = 0;
  2341. char *bytes = (char *)&value;
  2342. bytes[0] = self[0];
  2343. bytes[1] = self[1];
  2344. return QScriptValue(value);
  2345. }
  2346. QScriptValue QByteArray_toInt32(QScriptContext *context, QScriptEngine *)
  2347. {
  2348. QByteArray self = getself<QByteArray>(context);
  2349. int value = 0;
  2350. char *bytes = (char *)&value;
  2351. bytes[0] = self[0];
  2352. bytes[1] = self[1];
  2353. bytes[2] = self[2];
  2354. bytes[3] = self[3];
  2355. return QScriptValue(value);
  2356. }
  2357. @ Similar methods are provided for converting bytes to a |float| or |double|.
  2358. Note that the return value from |toFloat| will, in the host environment, be
  2359. represented as a |double|.
  2360. @<Functions for scripting@>=
  2361. QScriptValue QByteArray_toFloat(QScriptContext *context, QScriptEngine *)
  2362. {
  2363. QByteArray self = getself<QByteArray>(context);
  2364. float value = 0.0;
  2365. char *bytes = (char *)&value;
  2366. bytes[0] = self[0];
  2367. bytes[1] = self[1];
  2368. bytes[2] = self[2];
  2369. bytes[3] = self[3];
  2370. return QScriptValue(value);
  2371. }
  2372. QScriptValue QByteArray_toDouble(QScriptContext *context, QScriptEngine *)
  2373. {
  2374. QByteArray self = getself<QByteArray>(context);
  2375. double value = 0.0;
  2376. char *bytes = (char *)&value;
  2377. bytes[0] = self[0];
  2378. bytes[1] = self[1];
  2379. bytes[2] = self[2];
  2380. bytes[3] = self[3];
  2381. bytes[4] = self[4];
  2382. bytes[5] = self[5];
  2383. bytes[6] = self[6];
  2384. bytes[7] = self[7];
  2385. return QScriptValue(value);
  2386. }
  2387. @ Some protocols require manipulating larger than 8 bit numbers as a sequence
  2388. of bytes. To facilitate this, methods are provided to construct a |QByteArray|
  2389. from different sized numbers. 8 bit numbers are provided for uniformity.
  2390. @<Function prototypes for scripting@>=
  2391. QScriptValue bytesFromInt8(QScriptContext *context, QScriptEngine *engine);
  2392. QScriptValue bytesFromInt16(QScriptContext *context, QScriptEngine *engine);
  2393. QScriptValue bytesFromInt32(QScriptContext *context, QScriptEngine *engine);
  2394. QScriptValue bytesFromFloat(QScriptContext *context, QScriptEngine *engine);
  2395. QScriptValue bytesFromDouble(QScriptContext *context, QScriptEngine *engine);
  2396. @ These are globally available.
  2397. @<Set up the scripting engine@>=
  2398. engine->globalObject().setProperty("bytesFromInt8", engine->newFunction(bytesFromInt8));
  2399. engine->globalObject().setProperty("bytesFromInt16", engine->newFunction(bytesFromInt16));
  2400. engine->globalObject().setProperty("bytesFromInt32", engine->newFunction(bytesFromInt32));
  2401. engine->globalObject().setProperty("bytesFromFloat", engine->newFunction(bytesFromFloat));
  2402. engine->globalObject().setProperty("bytesFromDouble", engine->newFunction(bytesFromDouble));
  2403. @ The methods all work by casting the appropriate numeric type to a |char *|
  2404. and copying the bytes to a new |QByteArray|. Note that the ECMA-262 standard
  2405. only has one type of number and this is an IEEE 754 binary64 double precision
  2406. floating point number. Functions other than |bytesFromDouble| will be cast
  2407. from |double|.
  2408. @<Functions for scripting@>=
  2409. QScriptValue bytesFromInt8(QScriptContext *context, QScriptEngine *engine)
  2410. {
  2411. qint8 value = (qint8)(argument<int>(0, context));
  2412. char *bytes = (char *)&value;
  2413. QByteArray retval;
  2414. retval.resize(1);
  2415. retval[0] = bytes[0];
  2416. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2417. setQByteArrayProperties(v, engine);
  2418. return v;
  2419. }
  2420. QScriptValue bytesFromInt16(QScriptContext *context, QScriptEngine *engine)
  2421. {
  2422. qint16 value = (qint16)(argument<int>(0, context));
  2423. char *bytes = (char *)&value;
  2424. QByteArray retval;
  2425. retval.resize(2);
  2426. retval[0] = bytes[0];
  2427. retval[1] = bytes[1];
  2428. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2429. setQByteArrayProperties(v, engine);
  2430. return v;
  2431. }
  2432. QScriptValue bytesFromInt32(QScriptContext *context, QScriptEngine *engine)
  2433. {
  2434. qint32 value = (qint32)(argument<int>(0, context));
  2435. char *bytes = (char *)&value;
  2436. QByteArray retval;
  2437. retval.resize(4);
  2438. retval[0] = bytes[0];
  2439. retval[1] = bytes[1];
  2440. retval[2] = bytes[2];
  2441. retval[3] = bytes[3];
  2442. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2443. setQByteArrayProperties(v, engine);
  2444. return v;
  2445. }
  2446. QScriptValue bytesFromFloat(QScriptContext *context, QScriptEngine *engine)
  2447. {
  2448. float value = (float)(argument<double>(0, context));
  2449. char *bytes = (char *)&value;
  2450. QByteArray retval;
  2451. retval.resize(4);
  2452. retval[0] = bytes[0];
  2453. retval[1] = bytes[1];
  2454. retval[2] = bytes[2];
  2455. retval[3] = bytes[3];
  2456. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2457. setQByteArrayProperties(v, engine);
  2458. return v;
  2459. }
  2460. QScriptValue bytesFromDouble(QScriptContext *context, QScriptEngine *engine)
  2461. {
  2462. double value = (double)(argument<double>(0, context));
  2463. char *bytes = (char *)&value;
  2464. QByteArray retval;
  2465. retval.resize(8);
  2466. retval[0] = bytes[0];
  2467. retval[1] = bytes[1];
  2468. retval[2] = bytes[2];
  2469. retval[3] = bytes[3];
  2470. retval[4] = bytes[4];
  2471. retval[5] = bytes[5];
  2472. retval[6] = bytes[6];
  2473. retval[7] = bytes[7];
  2474. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2475. setQByteArrayProperties(v, engine);
  2476. return v;
  2477. }
  2478. @* Scripting QBuffer.
  2479. \noindent Sometimes it is desirable to load a roast profile from a file. At
  2480. other times, it is more useful to load that profile from a byte array stored in
  2481. a database. The |XMLInput| class takes data from a |QIODevice| object, which
  2482. means that we can choose from a |QFile| when we want the former or a |QBuffer|
  2483. when we want the latter.
  2484. @<Function prototypes for scripting@>=
  2485. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine);
  2486. void setQBufferProperties(QScriptValue value, QScriptEngine *engine);
  2487. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *engine);
  2488. QScriptValue QBuffer_data(QScriptContext *context, QScriptEngine *engine);
  2489. @ The host environment needs to be aware of the constructor.
  2490. @<Set up the scripting engine@>=
  2491. constructor = engine->newFunction(constructQBuffer);
  2492. value = engine->newQMetaObject(&QBuffer::staticMetaObject, constructor);
  2493. engine->globalObject().setProperty("QBuffer", value);
  2494. @ The implementation is trivial.
  2495. @<Functions for scripting@>=
  2496. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine)
  2497. {
  2498. QByteArray *array = new QByteArray(argument<QString>(0, context).toAscii());
  2499. QScriptValue object = engine->newQObject(new QBuffer(array));
  2500. setQBufferProperties(object, engine);
  2501. return object;
  2502. }
  2503. void setQBufferProperties(QScriptValue value, QScriptEngine *engine)
  2504. {
  2505. setQIODeviceProperties(value, engine);
  2506. value.setProperty("setData", engine->newFunction(QBuffer_setData));
  2507. value.setProperty("data", engine->newFunction(QBuffer_data));
  2508. }
  2509. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *)
  2510. {
  2511. QBuffer *self = getself<QBuffer *>(context);
  2512. self->setData(argument<QString>(0, context).toAscii());
  2513. return QScriptValue();
  2514. }
  2515. QScriptValue QBuffer_data(QScriptContext *context, QScriptEngine *)
  2516. {
  2517. QBuffer *self = getself<QBuffer *>(context);
  2518. return QScriptValue(QString(self->data()));
  2519. }
  2520. @* Scripting QXmlQuery.
  2521. \noindent Sometimes we have some XML data in a file or a buffer and we would
  2522. like to extract certain information from that data in the host environment.
  2523. Rather than write complicated string manipulation routines in an attempt to deal
  2524. with this sensibly, we can use the XQuery language to extract the information we
  2525. want. One common use case for this is extracting all measurements from a roast
  2526. profile that are associated with an annotation.
  2527. @<Function prototypes for scripting@>=
  2528. QScriptValue constructXQuery(QScriptContext *context, QScriptEngine *engine);
  2529. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *engine);
  2530. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *engine);
  2531. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *engine);
  2532. QScriptValue XQuery_invalidate(QScriptContext *context, QScriptEngine *engine);
  2533. void setXQueryProperties(QScriptValue value, QScriptEngine *engine);
  2534. @ The constructor must be registered with the host environment. This is done a
  2535. bit differently from most classes as |QXmlQuery| is not a |QObject|.
  2536. @<Set up the scripting engine@>=
  2537. constructor = engine->newFunction(constructXQuery);
  2538. engine->globalObject().setProperty("XQuery", constructor);
  2539. @ The constructor just needs to make sure the functions we want to make
  2540. available are applied. A method is also provided to free the |QXmlQuery|.
  2541. @<Functions for scripting@>=
  2542. QScriptValue constructXQuery(QScriptContext *, QScriptEngine *engine)
  2543. {
  2544. QScriptValue object = engine->toScriptValue<void *>(new QXmlQuery);
  2545. setXQueryProperties(object, engine);
  2546. return object;
  2547. }
  2548. QScriptValue XQuery_invalidate(QScriptContext *context, QScriptEngine *)
  2549. {
  2550. QXmlQuery *self = getself<QXmlQuery *>(context);
  2551. delete self;
  2552. return QScriptValue();
  2553. }
  2554. void setXQueryProperties(QScriptValue value, QScriptEngine *engine)
  2555. {
  2556. value.setProperty("bind", engine->newFunction(XQuery_bind));
  2557. value.setProperty("exec", engine->newFunction(XQuery_exec));
  2558. value.setProperty("setQuery", engine->newFunction(XQuery_setQuery));
  2559. value.setProperty("invalidate", engine->newFunction(XQuery_invalidate));
  2560. }
  2561. @ The |bind()| property can be used to specify a |QIODevice| to be referenced by
  2562. a variable within a query.
  2563. @<Functions for scripting@>=
  2564. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *)
  2565. {
  2566. QXmlQuery *self = getself<QXmlQuery *>(context);
  2567. QIODevice *buffer = argument<QIODevice *>(1, context);
  2568. self->bindVariable(argument<QString>(0, context), buffer);
  2569. return QScriptValue();
  2570. }
  2571. @ A method is also required for setting the query we wish to conduct.
  2572. @<Functions for scripting@>=
  2573. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *)
  2574. {
  2575. QXmlQuery *self = getself<QXmlQuery *>(context);
  2576. self->setQuery(argument<QString>(0, context));
  2577. return QScriptValue();
  2578. }
  2579. @ This method runs the previously specified query.
  2580. @<Functions for scripting@>=
  2581. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *)
  2582. {
  2583. QXmlQuery *self = getself<QXmlQuery *>(context);
  2584. QString result;
  2585. self->evaluateTo(&result);
  2586. return QScriptValue(result);
  2587. }
  2588. @* Scripting QXmlStreamWriter.
  2589. \noindent There are some cases where it may be desirable to produce XML from the
  2590. host environment. While there are several ways to accomplish this, the
  2591. |QXmlStreamWriter| class greatly simplifies generating complex XML documents.
  2592. This class is not related to |QObject|, so several functions are needed to
  2593. expose the functionality of this class to the host environment.
  2594. @<Function prototypes for scripting@>=
  2595. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine);
  2596. QScriptValue XmlWriter_setDevice(QScriptContext *context,
  2597. QScriptEngine *engine);
  2598. QScriptValue XmlWriter_writeAttribute(QScriptContext *context,
  2599. QScriptEngine *engine);
  2600. QScriptValue XmlWriter_writeCDATA(QScriptContext *context,
  2601. QScriptEngine *engine);
  2602. QScriptValue XmlWriter_writeCharacters(QScriptContext *context,
  2603. QScriptEngine *engine);
  2604. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *engine);
  2605. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  2606. QScriptEngine *engine);
  2607. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  2608. QScriptEngine *engine);
  2609. QScriptValue XmlWriter_writeEndElement(QScriptContext *context,
  2610. QScriptEngine *engine);
  2611. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  2612. QScriptEngine *engine);
  2613. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  2614. QScriptEngine *engine);
  2615. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  2616. QScriptEngine *engine);
  2617. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  2618. QScriptEngine *engine);
  2619. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  2620. QScriptEngine *engine);
  2621. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine);
  2622. @ The constructor must be registered with the host environment.
  2623. @<Set up the scripting engine@>=
  2624. constructor = engine->newFunction(constructXmlWriter);
  2625. engine->globalObject().setProperty("XmlWriter", constructor);
  2626. @ The constructor takes an optional argument allowing the output device to be
  2627. specified.
  2628. @<Functions for scripting@>=
  2629. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine)
  2630. {
  2631. QXmlStreamWriter *retval;
  2632. if(context->argumentCount() == 1)
  2633. {
  2634. retval = new QXmlStreamWriter(argument<QIODevice *>(0, context));
  2635. }
  2636. else
  2637. {
  2638. retval = new QXmlStreamWriter;
  2639. }
  2640. QScriptValue object = engine->toScriptValue<void *>(retval);
  2641. setXmlWriterProperties(object, engine);
  2642. return object;
  2643. }
  2644. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine)
  2645. {
  2646. value.setProperty("setDevice", engine->newFunction(XmlWriter_setDevice));
  2647. value.setProperty("writeAttribute",
  2648. engine->newFunction(XmlWriter_writeAttribute));
  2649. value.setProperty("writeCDATA", engine->newFunction(XmlWriter_writeCDATA));
  2650. value.setProperty("writeCharacters",
  2651. engine->newFunction(XmlWriter_writeCharacters));
  2652. value.setProperty("writeDTD", engine->newFunction(XmlWriter_writeDTD));
  2653. value.setProperty("writeEmptyElement",
  2654. engine->newFunction(XmlWriter_writeEmptyElement));
  2655. value.setProperty("writeEndDocument",
  2656. engine->newFunction(XmlWriter_writeEndDocument));
  2657. value.setProperty("writeEndElement",
  2658. engine->newFunction(XmlWriter_writeEndElement));
  2659. value.setProperty("writeEntityReference",
  2660. engine->newFunction(XmlWriter_writeEntityReference));
  2661. value.setProperty("writeProcessingInstruction",
  2662. engine->newFunction(XmlWriter_writeProcessingInstruction));
  2663. value.setProperty("writeStartDocument",
  2664. engine->newFunction(XmlWriter_writeStartDocument));
  2665. value.setProperty("writeStartElement",
  2666. engine->newFunction(XmlWriter_writeStartElement));
  2667. value.setProperty("writeTextElement",
  2668. engine->newFunction(XmlWriter_writeTextElement));
  2669. }
  2670. @ If the output device needs to be changed or if one is not passed to the
  2671. constructor, the |setDevice()| method can be used.
  2672. @<Functions for scripting@>=
  2673. QScriptValue XmlWriter_setDevice(QScriptContext *context, QScriptEngine *)
  2674. {
  2675. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2676. QIODevice *device = argument<QIODevice *>(0, context);
  2677. self->setDevice(device);
  2678. return QScriptValue();
  2679. }
  2680. @ The remaining functions are simple wrappers used for writing various types of
  2681. data. After creating a writer and setting the output device, the start of the
  2682. document should be written. One argument is required containing the XML version
  2683. number. Another function handles writing the end of the document.
  2684. @<Functions for scripting@>=
  2685. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  2686. QScriptEngine *)
  2687. {
  2688. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2689. self->writeStartDocument(argument<QString>(0, context));
  2690. return QScriptValue();
  2691. }
  2692. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  2693. QScriptEngine *)
  2694. {
  2695. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2696. self->writeEndDocument();
  2697. return QScriptValue();
  2698. }
  2699. @ After the start of the document, a DTD is commonly needed.
  2700. @<Functions for scripting@>=
  2701. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *)
  2702. {
  2703. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2704. self->writeDTD(argument<QString>(0, context));
  2705. return QScriptValue();
  2706. }
  2707. @ After this, elements need to be written. For this, we write the start
  2708. element, any attributes needed, character data, and the end element.
  2709. @<Functions for scripting@>=
  2710. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  2711. QScriptEngine *)
  2712. {
  2713. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2714. self->writeStartElement(argument<QString>(0, context));
  2715. return QScriptValue();
  2716. }
  2717. QScriptValue XmlWriter_writeAttribute(QScriptContext *context, QScriptEngine *)
  2718. {
  2719. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2720. self->writeAttribute(argument<QString>(0, context),
  2721. argument<QString>(1, context));
  2722. return QScriptValue();
  2723. }
  2724. QScriptValue XmlWriter_writeCharacters(QScriptContext *context, QScriptEngine *)
  2725. {
  2726. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2727. self->writeCharacters(argument<QString>(0, context));
  2728. return QScriptValue();
  2729. }
  2730. QScriptValue XmlWriter_writeEndElement(QScriptContext *context, QScriptEngine *)
  2731. {
  2732. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2733. self->writeEndElement();
  2734. return QScriptValue();
  2735. }
  2736. @ For convenience, two other methods are provided for writing elements. Elements
  2737. which do not require anything between the start and end elements can be created
  2738. with |writeEmptyElement()|. Elements which do not require attributes, but do
  2739. contain text can be created with |writeTextElement()|.
  2740. @<Functions for scripting@>=
  2741. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  2742. QScriptEngine *)
  2743. {
  2744. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2745. self->writeEmptyElement(argument<QString>(0, context));
  2746. return QScriptValue();
  2747. }
  2748. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  2749. QScriptEngine *)
  2750. {
  2751. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2752. self->writeTextElement(argument<QString>(0, context),
  2753. argument<QString>(1, context));
  2754. return QScriptValue();
  2755. }
  2756. @ Less commonly needed are functions for writing CDATA sections, entity
  2757. references, and processing instructions.
  2758. @<Functions for scripting@>=
  2759. QScriptValue XmlWriter_writeCDATA(QScriptContext *context, QScriptEngine *)
  2760. {
  2761. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2762. self->writeCDATA(argument<QString>(0, context));
  2763. return QScriptValue();
  2764. }
  2765. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  2766. QScriptEngine *)
  2767. {
  2768. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2769. self->writeEntityReference(argument<QString>(0, context));
  2770. return QScriptValue();
  2771. }
  2772. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  2773. QScriptEngine *)
  2774. {
  2775. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2776. self->writeProcessingInstruction(argument<QString>(0, context),
  2777. argument<QString>(1, context));
  2778. return QScriptValue();
  2779. }
  2780. @* Scripting QXmlStreamReader.
  2781. \noindent When a serializer is written using |QXmlStreamWriter|, a corresponding
  2782. deserializer should also be written. While there are several possible ways to do
  2783. this, using |QXmlStreamReader| is often the best choice. \pn{} provides a subset
  2784. of the functionality from this class which should be adequate for most purposes.
  2785. @<Function prototypes for scripting@>=
  2786. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine);
  2787. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *engine);
  2788. QScriptValue XmlReader_attribute(QScriptContext *context,
  2789. QScriptEngine *engine);
  2790. QScriptValue XmlReader_hasAttribute(QScriptContext *context,
  2791. QScriptEngine *engine);
  2792. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *engine);
  2793. QScriptValue XmlReader_isStartElement(QScriptContext *context,
  2794. QScriptEngine *engine);
  2795. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *engine);
  2796. QScriptValue XmlReader_readElementText(QScriptContext *context,
  2797. QScriptEngine *engine);
  2798. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *engine);
  2799. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *engine);
  2800. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine);
  2801. @ The constructor must be registered with the host environment.
  2802. @<Set up the scripting engine@>=
  2803. constructor = engine->newFunction(constructXmlReader);
  2804. engine->globalObject().setProperty("XmlReader", constructor);
  2805. @ The constructor requires an argument specifying the output device. This can be
  2806. any |QIODevice|. The |open()| method must be called on the device before passing
  2807. it as an argument to this function.
  2808. @<Functions for scripting@>=
  2809. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine)
  2810. {
  2811. QXmlStreamReader *retval =
  2812. new QXmlStreamReader(argument<QIODevice *>(0, context));
  2813. QScriptValue object = engine->toScriptValue<void *>(retval);
  2814. setXmlReaderProperties(object, engine);
  2815. return object;
  2816. }
  2817. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine)
  2818. {
  2819. value.setProperty("atEnd", engine->newFunction(XmlReader_atEnd));
  2820. value.setProperty("attribute", engine->newFunction(XmlReader_attribute));
  2821. value.setProperty("hasAttribute",
  2822. engine->newFunction(XmlReader_hasAttribute));
  2823. value.setProperty("isDTD", engine->newFunction(XmlReader_isDTD));
  2824. value.setProperty("isStartElement",
  2825. engine->newFunction(XmlReader_isStartElement));
  2826. value.setProperty("name", engine->newFunction(XmlReader_name));
  2827. value.setProperty("readElementText",
  2828. engine->newFunction(XmlReader_readElementText));
  2829. value.setProperty("readNext",
  2830. engine->newFunction(XmlReader_readNext));
  2831. value.setProperty("text", engine->newFunction(XmlReader_text));
  2832. }
  2833. @ Most of the functions are simple member function wrappers. Two of these
  2834. properties are not. These are the |attribute()| and |hasAttribute()| properties.
  2835. @<Functions for scripting@>=
  2836. QScriptValue XmlReader_attribute(QScriptContext *context, QScriptEngine *)
  2837. {
  2838. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2839. QString retval =
  2840. self->attributes().value(argument<QString>(0, context)).toString();
  2841. return QScriptValue(retval);
  2842. }
  2843. QScriptValue XmlReader_hasAttribute(QScriptContext *context, QScriptEngine *)
  2844. {
  2845. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2846. bool retval =
  2847. self->attributes().hasAttribute(argument<QString>(0, context));
  2848. return QScriptValue(retval);
  2849. }
  2850. @ Other properties can be used for determining how to proceed with the
  2851. processing.
  2852. @<Functions for scripting@>=
  2853. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *)
  2854. {
  2855. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2856. return QScriptValue(self->atEnd());
  2857. }
  2858. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *)
  2859. {
  2860. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2861. return QScriptValue(self->isDTD());
  2862. }
  2863. QScriptValue XmlReader_isStartElement(QScriptContext *context, QScriptEngine *)
  2864. {
  2865. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2866. return QScriptValue(self->isStartElement());
  2867. }
  2868. @ We move from one element to the next with the |readNext()| property.
  2869. @<Functions for scripting@>=
  2870. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *)
  2871. {
  2872. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2873. self->readNext();
  2874. return QScriptValue();
  2875. }
  2876. @ The remaining properties return the element name and text.
  2877. @<Functions for scripting@>=
  2878. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *)
  2879. {
  2880. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2881. return QScriptValue(self->name().toString());
  2882. }
  2883. QScriptValue XmlReader_readElementText(QScriptContext *context, QScriptEngine *)
  2884. {
  2885. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2886. return QScriptValue(self->readElementText());
  2887. }
  2888. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *)
  2889. {
  2890. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2891. return QScriptValue(self->text().toString());
  2892. }
  2893. @* Scripting QSettings.
  2894. \noindent Rather than have a script create a |QSettings| object when it needs to
  2895. save or load settings, the object is provided along with properties for getting
  2896. and setting values. Two functions are needed for this along with a third which
  2897. ensures any properties added to |QObject| are also available to |QSettings| from
  2898. the host environment.
  2899. @<Function prototypes for scripting@>=
  2900. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine);
  2901. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *engine);
  2902. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine);
  2903. @ The object with properties for these functions is passed to the scripting
  2904. engine.
  2905. @<Set up the scripting engine@>=
  2906. value = engine->newQObject(&settings);
  2907. setQSettingsProperties(value, engine);
  2908. engine->globalObject().setProperty("QSettings", value);
  2909. @ Adding properties to the |QSettings| object should seem familiar.
  2910. @<Functions for scripting@>=
  2911. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine)
  2912. {
  2913. setQObjectProperties(value, engine);
  2914. value.setProperty("value", engine->newFunction(QSettings_value));
  2915. value.setProperty("setValue", engine->newFunction(QSettings_setValue));
  2916. }
  2917. @ When getting a value from saved settings, there is the possibility that there
  2918. will not be a value saved for the requested key. An optional second argument can
  2919. be used to supply a default value.
  2920. @<Functions for scripting@>=
  2921. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine)
  2922. {
  2923. QScriptValue object;
  2924. if(context->argumentCount() == 1 || context->argumentCount() == 2)
  2925. {
  2926. QSettings settings;
  2927. QString key = argument<QString>(0, context);
  2928. QVariant value;
  2929. QVariant retval;
  2930. if(context->argumentCount() > 1)
  2931. {
  2932. value = argument<QVariant>(1, context);
  2933. retval = settings.value(key, value);
  2934. }
  2935. else
  2936. {
  2937. retval = settings.value(key);
  2938. }
  2939. object = engine->newVariant(retval);
  2940. }
  2941. else
  2942. {
  2943. context->throwError("Incorrect number of arguments passed to "@|
  2944. "QSettings::value(). This method takes one "@|
  2945. "string and one optional variant type.");
  2946. }
  2947. return object;
  2948. }
  2949. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *)
  2950. {
  2951. if(context->argumentCount() == 2)
  2952. {
  2953. QSettings settings;
  2954. QString key = argument<QString>(0, context);
  2955. QVariant value = argument<QVariant>(1, context);
  2956. settings.setValue(key, value);
  2957. }
  2958. else
  2959. {
  2960. context->throwError("Incorrect number of arguments passed to "@|
  2961. "QSettings::setValue(). This method takes one "@|
  2962. "string and one variant type for a total of two "@|
  2963. "arguments.");
  2964. }
  2965. return QScriptValue();
  2966. }
  2967. @* Scripting QLCDNumber.
  2968. \noindent |QLCDNumber| is used as a base class for \pn{}'@q'@>s |TemperatureDisplay|
  2969. and |TimerDisplay| classes, but it can also be used on its own for the display
  2970. of mainly numeric information.
  2971. @<Function prototypes for scripting@>=
  2972. QScriptValue constructQLCDNumber(QScriptContext *context,
  2973. QScriptEngine *engine);
  2974. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine);
  2975. @ The constructor must be passed to the scripting engine.
  2976. @<Set up the scripting engine@>=
  2977. constructor = engine->newFunction(constructQLCDNumber);
  2978. value = engine->newQMetaObject(&QLCDNumber::staticMetaObject, constructor);
  2979. engine->globalObject().setProperty("QLCDNumber", value);
  2980. @ There is nothing special about the implementation.
  2981. @<Functions for scripting@>=
  2982. QScriptValue constructQLCDNumber(QScriptContext *, QScriptEngine *engine)
  2983. {
  2984. QScriptValue object = engine->newQObject(new QLCDNumber());
  2985. setQLCDNumberProperties(object, engine);
  2986. return object;
  2987. }
  2988. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine)
  2989. {
  2990. setQFrameProperties(value, engine);
  2991. }
  2992. @* Scripting QTime.
  2993. \noindent |QTime| is a little different from the classes examined so far. This
  2994. class can be used for synchonizing time among various objects by creating a
  2995. common base reference time. This should not be needed as ECMA-262 already
  2996. specifies a |Date| class, however this has historically been troublesome to use.
  2997. One thing that makes this class different is that it is not related to
  2998. |QObject|. This makes usefully exposing it to the scripting engine a little more
  2999. difficult.
  3000. @<Function prototypes for scripting@>=
  3001. QScriptValue constructQTime(QScriptContext *context, QScriptEngine *engine);
  3002. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine);
  3003. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine);
  3004. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine);
  3005. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine);
  3006. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine);
  3007. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine);
  3008. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine);
  3009. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine);
  3010. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine);
  3011. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine);
  3012. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine);
  3013. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine);
  3014. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine);
  3015. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *engine);
  3016. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine);
  3017. QScriptValue QTime_currentTime(QScriptContext *context, QScriptEngine *engine);
  3018. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine);
  3019. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *engine);
  3020. void setQTimeProperties(QScriptValue value, QScriptEngine *engine);
  3021. @ We must tell the script engine about the constructor. This is not done in
  3022. quite the same way as is done for |QObject| derived types.
  3023. @<Set up the scripting engine@>=
  3024. constructor = engine->newFunction(constructQTime);
  3025. engine->globalObject().setProperty("QTime", constructor);
  3026. @ The constructor has a couple interesting twists. The first is the ability to
  3027. accept a variable number of integer arguments. The other is that |QTime| is not
  3028. derived from |QObject|. The lack of |break| statements in the |switch| is
  3029. intended.
  3030. @<Functions for scripting@>=
  3031. QScriptValue constructQTime(QScriptContext *context,
  3032. QScriptEngine *engine)
  3033. {
  3034. QScriptValue object;
  3035. if(context->argumentCount() == 0 ||
  3036. (context->argumentCount() >= 2 && context->argumentCount() <= 4))@/
  3037. {
  3038. int arg1 = 0;
  3039. int arg2 = 0;
  3040. int arg3 = 0;
  3041. int arg4 = 0;
  3042. switch(context->argumentCount())
  3043. {@t\1@>@/
  3044. case 4:@/
  3045. arg4 = argument<int>(3, context);
  3046. case 3:@/
  3047. arg3 = argument<int>(2, context);
  3048. case 2:@/
  3049. arg2 = argument<int>(1, context);
  3050. arg1 = argument<int>(0, context);
  3051. default:@/
  3052. break;@t\2@>@/
  3053. }
  3054. if(context->argumentCount())
  3055. {
  3056. object = engine->toScriptValue<QTime>(QTime(arg1, arg2, arg3,
  3057. arg4));
  3058. }
  3059. else
  3060. {
  3061. object = engine->toScriptValue<QTime>(QTime());
  3062. }
  3063. setQTimeProperties(object, engine);
  3064. }
  3065. else
  3066. {
  3067. context->throwError("Incorrect number of arguments passed to "@|
  3068. "QTime::QTime(). This method takes zero, two, "@|
  3069. "three, or four integer arguments.");
  3070. }
  3071. return object;
  3072. }
  3073. @ In order to use the various |QTime| methods, we must add wrapper functions as
  3074. properties of newly created script objects. The last two of these should really
  3075. be callable without starting from an existing |QTime|.
  3076. @<Functions for scripting@>=
  3077. void setQTimeProperties(QScriptValue value, QScriptEngine *engine)
  3078. {
  3079. value.setProperty("addMSecs", engine->newFunction(QTime_addMSecs));
  3080. value.setProperty("addSecs", engine->newFunction(QTime_addSecs));
  3081. value.setProperty("elapsed", engine->newFunction(QTime_elapsed));
  3082. value.setProperty("hour", engine->newFunction(QTime_hour));
  3083. value.setProperty("isNull", engine->newFunction(QTime_isNull));
  3084. value.setProperty("isValid", engine->newFunction(QTime_isValid));
  3085. value.setProperty("minute", engine->newFunction(QTime_minute));
  3086. value.setProperty("msec", engine->newFunction(QTime_msec));
  3087. value.setProperty("msecsTo", engine->newFunction(QTime_msecsTo));
  3088. value.setProperty("restart", engine->newFunction(QTime_restart));
  3089. value.setProperty("second", engine->newFunction(QTime_second));
  3090. value.setProperty("secsTo", engine->newFunction(QTime_secsTo));
  3091. value.setProperty("setHMS", engine->newFunction(QTime_setHMS));
  3092. value.setProperty("start", engine->newFunction(QTime_start));
  3093. value.setProperty("toString", engine->newFunction(QTime_toString));
  3094. value.setProperty("currentTime", engine->newFunction(QTime_currentTime));
  3095. value.setProperty("fromString", engine->newFunction(QTime_fromString));
  3096. value.setProperty("valueOf", engine->newFunction(QTime_valueOf));
  3097. }
  3098. @ The |valueOf()| method exposes a numeric representation of the time
  3099. suitable for use in comparing two time values. With this it is possible to
  3100. take two |QTime| values in script code {\tt t1} and {\tt t2} and get the
  3101. expected results from {\tt t1 == t2}, {\tt t1 < t2}, {\tt t1 > t2} and
  3102. similar comparative operations.
  3103. @<Functions for scripting@>=
  3104. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *)
  3105. {
  3106. QTime self = getself<QTime>(context);
  3107. int retval = (self.hour() * 60 * 60 * 1000) + (self.minute() * 60 * 1000) +
  3108. (self.second() * 1000) + self.msec();
  3109. return QScriptValue(retval);
  3110. }
  3111. @ These functions are effectively wrapper functions around existing |QTime|
  3112. functionality with some error checking for the scripting engine.
  3113. The |addMSecs()| and |addSecs()| methods return a new |QTime| object.
  3114. @<Functions for scripting@>=
  3115. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine)
  3116. {
  3117. QTime time;
  3118. QScriptValue retval;
  3119. if(context->argumentCount() == 1)
  3120. {
  3121. QTime self = getself<QTime>(context);
  3122. time = self.addMSecs(argument<int>(0, context));
  3123. retval = engine->toScriptValue<QTime>(time);
  3124. setQTimeProperties(retval, engine);
  3125. }
  3126. else
  3127. {
  3128. context->throwError("Incorrect number of arguments passed to "@|
  3129. "QTime::addMSecs(). This method takes one "@|
  3130. "integer as an argument.");
  3131. }
  3132. return retval;
  3133. }
  3134. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine)
  3135. {
  3136. QTime time;
  3137. QScriptValue retval;
  3138. if(context->argumentCount() == 1)
  3139. {
  3140. QTime self = getself<QTime>(context);
  3141. time = self.addSecs(argument<int>(0, context));
  3142. retval = engine->toScriptValue<QTime>(time);
  3143. setQTimeProperties(retval, engine);
  3144. }
  3145. else
  3146. {
  3147. context->throwError("Incorrect number of arguments passed to "@|
  3148. "QTime::addSecs(). This method takes one "@|
  3149. "integer as an argument.");
  3150. }
  3151. return retval;
  3152. }
  3153. @ The |elapsed()| method returns an integer value.
  3154. @<Functions for scripting@>=
  3155. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine)
  3156. {
  3157. QScriptValue retval;
  3158. if(context->argumentCount() == 0)
  3159. {
  3160. QTime self = getself<QTime>(context);
  3161. retval = QScriptValue(engine, self.elapsed());
  3162. }
  3163. else
  3164. {
  3165. context->throwError("Incorrect number of arguments passed to "@|
  3166. "QTime::elapsed(). This method takes no "@|
  3167. "arguments.");
  3168. }
  3169. return retval;
  3170. }
  3171. @ The |hour()|, |minute()|, |second()| and |msec()| methods return an integer
  3172. with various parts of the time. The |hour()| method is typical of these methods.
  3173. @<Functions for scripting@>=
  3174. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine)
  3175. {
  3176. QScriptValue retval;
  3177. if(context->argumentCount() == 0)
  3178. {
  3179. QTime self = getself<QTime>(context);
  3180. retval = QScriptValue(engine, self.hour());
  3181. }
  3182. else
  3183. {
  3184. context->throwError("Incorrect number of arguments passed to "@|
  3185. "QTime::hour(). This method takes no "@|
  3186. "arguments.");
  3187. }
  3188. return retval;
  3189. }
  3190. @ The |minute()|, |second()|, and |msec()| methods are implemented similarly.
  3191. @<Functions for scripting@>=
  3192. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine)
  3193. {
  3194. QScriptValue retval;
  3195. if(context->argumentCount() == 0)
  3196. {
  3197. QTime self = getself<QTime>(context);
  3198. retval = QScriptValue(engine, self.minute());
  3199. }
  3200. else
  3201. {
  3202. context->throwError("Incorrect number of arguments passed to "@|
  3203. "QTime::minute(). This method takes no "@|
  3204. "arguments.");
  3205. }
  3206. return retval;
  3207. }
  3208. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine)
  3209. {
  3210. QScriptValue retval;
  3211. if(context->argumentCount() == 0)
  3212. {
  3213. QTime self = getself<QTime>(context);
  3214. retval = QScriptValue(engine, self.second());
  3215. }
  3216. else
  3217. {
  3218. context->throwError("Incorrect number of arguments passed to "@|
  3219. "QTime::second(). This method takes no "@|
  3220. "arguments.");
  3221. }
  3222. return retval;
  3223. }
  3224. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine)
  3225. {
  3226. QScriptValue retval;
  3227. if(context->argumentCount() == 0)
  3228. {
  3229. QTime self = getself<QTime>(context);
  3230. retval = QScriptValue(engine, self.msec());
  3231. }
  3232. else
  3233. {
  3234. context->throwError("Incorrect number of arguments passed to "@|
  3235. "QTime::msec(). This method takes no "@|
  3236. "arguments.");
  3237. }
  3238. return retval;
  3239. }
  3240. @ The |isNull()| and |isValid()| methods return a boolean value. A |QTime| is
  3241. considered null if it was created with a constructor with no arguments. It is
  3242. considered invalid if it is null or if part of the time is out of range.
  3243. @<Functions for scripting@>=
  3244. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine)
  3245. {
  3246. QScriptValue retval;
  3247. if(context->argumentCount() == 0)
  3248. {
  3249. QTime self = getself<QTime>(context);
  3250. retval = QScriptValue(engine, self.isNull());
  3251. }
  3252. else
  3253. {
  3254. context->throwError("Incorrect number of arguments passed to "@|
  3255. "QTime::isNull(). This method takes no "@|
  3256. "arguments.");
  3257. }
  3258. return retval;
  3259. }
  3260. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine)
  3261. {
  3262. QScriptValue retval;
  3263. if(context->argumentCount() == 0)
  3264. {
  3265. QTime self = getself<QTime>(context);
  3266. retval = QScriptValue(engine, self.isValid());
  3267. }
  3268. else
  3269. {
  3270. context->throwError("Incorrect number of arguments passed to "@|
  3271. "QTime::isValid(). This method takes no "@|
  3272. "arguments.");
  3273. }
  3274. return retval;
  3275. }
  3276. @ The |secsTo()| and |msecsTo()| methods return an integer value indicating the
  3277. number of seconds or milliseconds until a |QTime| argument.
  3278. @<Functions for scripting@>=
  3279. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine)
  3280. {
  3281. QScriptValue retval;
  3282. if(context->argumentCount() == 1)
  3283. {
  3284. QTime self = getself<QTime>(context);
  3285. QTime arg = argument<QVariant>(0, context).toTime();
  3286. retval = QScriptValue(engine, self.msecsTo(arg));
  3287. }
  3288. else
  3289. {
  3290. context->throwError("Incorrect number of arguments passed to "@|
  3291. "QTime::msecsTo(). This method takes one QTime.");
  3292. }
  3293. return retval;
  3294. }
  3295. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine)
  3296. {
  3297. QScriptValue retval;
  3298. if(context->argumentCount() == 1)
  3299. {
  3300. QTime self = getself<QTime>(context);
  3301. QTime arg = argument<QVariant>(0, context).toTime();
  3302. retval = QScriptValue(engine, self.secsTo(arg));
  3303. }
  3304. else
  3305. {
  3306. context->throwError("Incorrect number of arguments passed to "@|
  3307. "QTime::secsTo(). This method takes one QTime.");
  3308. }
  3309. return retval;
  3310. }
  3311. @ The |start()| and |restart()| methods each set the value of the |QTime()| to
  3312. the current time. The |restart()| method additionally returns the same value as
  3313. the |elapsed()| method.
  3314. @<Functions for scripting@>=
  3315. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine)
  3316. {
  3317. QScriptValue retval;
  3318. if(context->argumentCount() == 0)
  3319. {
  3320. QTime self = getself<QTime>(context);
  3321. retval = QScriptValue(engine, self.restart());
  3322. }
  3323. else
  3324. {
  3325. context->throwError("Incorrect number of arguments passed to "@|
  3326. "QTime::restart(). This method takes no "@|
  3327. "arguments.");
  3328. }
  3329. return retval;
  3330. }
  3331. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *)
  3332. {
  3333. if(context->argumentCount() == 0)
  3334. {
  3335. QTime self = getself<QTime>(context);
  3336. self.start();
  3337. }
  3338. else
  3339. {
  3340. context->throwError("Incorrect number of arguments passed to "@|
  3341. "QTime::start(). This method takes no arguments.");
  3342. }
  3343. return QScriptValue();
  3344. }
  3345. @ The slightly inappropriately named |setHMS()| method changes the current value
  3346. of the time and returns a boolean to indicate if the new time value is valid.
  3347. @<Functions for scripting@>=
  3348. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine)
  3349. {
  3350. QScriptValue retval;
  3351. if(context->argumentCount() == 3 || context->argumentCount() == 4)
  3352. {
  3353. QTime self = getself<QTime>(context);
  3354. int arg1 = 0;
  3355. int arg2 = 0;
  3356. int arg3 = 0;
  3357. int arg4 = 0;
  3358. switch(context->argumentCount())@/
  3359. {@t\1@>@/
  3360. case 4:@/
  3361. arg4 = argument<int>(3, context);
  3362. case 3:@/
  3363. arg3 = argument<int>(2, context);
  3364. arg2 = argument<int>(1, context);
  3365. arg1 = argument<int>(0, context);
  3366. default:@/
  3367. break;@t\2@>@/
  3368. }
  3369. retval = QScriptValue(engine, self.setHMS(arg1, arg2, arg3, arg4));
  3370. }
  3371. else
  3372. {
  3373. context->throwError("Incorrect number of arguments passed to "@|
  3374. "QTime::setHMS(). This method takes three or "@|
  3375. "four integer arguments.");
  3376. }
  3377. return retval;
  3378. }
  3379. @ The |toString()| method returns a string representation of the time. See the
  3380. Qt documentation for instructions on creating a valid format string.
  3381. @<Functions for scripting@>=
  3382. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine)
  3383. {
  3384. QScriptValue retval;
  3385. if(context->argumentCount() == 1)
  3386. {
  3387. QTime self = getself<QTime>(context);
  3388. retval = QScriptValue(engine, self.toString(argument<QString>(0, context)));
  3389. }
  3390. else
  3391. {
  3392. context->throwError("Incorrect number of arguments passed to "@|
  3393. "QTime::toString(). This method takes one QString "@|
  3394. "as an argument.");
  3395. }
  3396. return retval;
  3397. }
  3398. @ The |currentTime()| and |fromString()| methods return a new |QTime| object.
  3399. These methods make no reference to the any other existing |QTime|.
  3400. @<Functions for scripting@>=
  3401. QScriptValue QTime_currentTime(QScriptContext *, QScriptEngine *engine)
  3402. {
  3403. QScriptValue object;
  3404. object = engine->toScriptValue<QTime>(QTime::currentTime());
  3405. setQTimeProperties(object, engine);
  3406. return object;
  3407. }
  3408. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine)
  3409. {
  3410. QScriptValue object;
  3411. if(context->argumentCount() == 2)
  3412. {
  3413. QString time = argument<QString>(0, context);
  3414. QString format = argument<QString>(1, context);
  3415. object = engine->toScriptValue<QTime>(QTime::fromString(time, format));
  3416. setQTimeProperties(object, engine);
  3417. }
  3418. else
  3419. {
  3420. context->throwError("Incorrect number of arguments passed to "@|
  3421. "QTime::fromString(). This method takes two "@|
  3422. "string arguments.");
  3423. }
  3424. return object;
  3425. }
  3426. @ In order to pass |QTime| objects back from a script, we also need to overload
  3427. |argument()| for this type.
  3428. @<Functions for scripting@>=
  3429. template<> QTime argument(int arg, QScriptContext *context)
  3430. {
  3431. return qscriptvalue_cast<QTime>(context->argument(arg));
  3432. }
  3433. @* Scripting Item View Classes.
  3434. \noindent |QAbstractScrollArea| is a |QFrame| that serves as the base class for
  3435. classes such as |QGraphicsView| and |QAbstractItemView|. Objects from this class
  3436. are not created directly.
  3437. @<Function prototypes for scripting@>=
  3438. void setQAbstractScrollAreaProperties(QScriptValue value,
  3439. QScriptEngine *engine);
  3440. @ The implementation of this is simple.
  3441. @<Functions for scripting@>=
  3442. void setQAbstractScrollAreaProperties(QScriptValue value, QScriptEngine *engine)
  3443. {
  3444. setQFrameProperties(value, engine);
  3445. }
  3446. @ This class is used by the |QAbstractItemView| class. This is another class
  3447. that we do not need a script constructor for.
  3448. @<Function prototypes for scripting@>=
  3449. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine);
  3450. @ This function has another simple implementation.
  3451. @<Functions for scripting@>=
  3452. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine)
  3453. {
  3454. setQAbstractScrollAreaProperties(value, engine);
  3455. }
  3456. @ The |QGraphicsView| and |QTableView| classes form the base of \pn{} classes.
  3457. @<Function prototypes for scripting@>=
  3458. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine);
  3459. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine);
  3460. @ Again, the implementations are boring.
  3461. @<Functions for scripting@>=
  3462. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine)
  3463. {
  3464. setQAbstractScrollAreaProperties(value, engine);
  3465. }
  3466. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine)
  3467. {
  3468. setQAbstractItemViewProperties(value, engine);
  3469. }
  3470. @* Scripting Button Classes.
  3471. \noindent \pn{} provides an |AnnotationButton| class which is a special kind of
  3472. |QPushButton| which in turn comes from |QAbstractButton|. While
  3473. |AnnotationButton| can be used in exactly the same way as a |QPushButton|, if
  3474. an annotation is not needed, there is little reason not to use the base class.
  3475. @<Function prototypes for scripting@>=
  3476. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine);
  3477. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine);
  3478. QScriptValue constructQPushButton(QScriptContext *context,
  3479. QScriptEngine *engine);
  3480. @ The constructor for |QPushButton| should be passed to the scripting engine.
  3481. @<Set up the scripting engine@>=
  3482. constructor = engine->newFunction(constructQPushButton);
  3483. value = engine->newQMetaObject(&QPushButton::staticMetaObject, constructor);
  3484. engine->globalObject().setProperty("QPushButton", value);
  3485. @ The implementation should seem familiar.
  3486. @<Functions for scripting@>=
  3487. QScriptValue constructQPushButton(QScriptContext *, QScriptEngine *engine)
  3488. {
  3489. QScriptValue object = engine->newQObject(new QPushButton());
  3490. setQPushButtonProperties(object, engine);
  3491. return object;
  3492. }
  3493. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine)
  3494. {
  3495. setQAbstractButtonProperties(value, engine);
  3496. }
  3497. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine)
  3498. {
  3499. setQWidgetProperties(value, engine);
  3500. }
  3501. @* Scripting QSqlQuery.
  3502. \noindent With this class exposed to the host environment, it becomes possible
  3503. for script code to execute SQL queries and evaluate the result.
  3504. Rather than use |QSqlQuery| directly, however, we use a proxy \nfnote{Erich
  3505. Gamma, Richard Helm, Raph Johnson, and John
  3506. Vlissides,\par\indent\underbar{Design Patterns: elements of reusable
  3507. object-oriented software} (1995) pp. 207--217} class. This class obtains its own
  3508. database connection and handles properly closing and removing these connections
  3509. when the query object is destroyed.
  3510. @<Class declarations@>=
  3511. class SqlQueryConnection : public QSqlQuery@/
  3512. {
  3513. public:@/
  3514. SqlQueryConnection(const QString &query = QString());
  3515. ~SqlQueryConnection();
  3516. QSqlQuery* operator->() const;
  3517. private:@/
  3518. QString connection;
  3519. QSqlQuery *q;
  3520. };
  3521. @ The constructor can be somewhat simplified from the four forms of |QSqlQuery|.
  3522. We are not interested in creating an object from a |QSqlResult| or from another
  3523. |QSqlQuery|. The database connection is managed by the class itself so the
  3524. constructor only needs an optional string containing a query. This is used to
  3525. initialize a real |QSqlQuery| object.
  3526. @<SqlQueryConnection implementation@>=
  3527. SqlQueryConnection::SqlQueryConnection(const QString &query)
  3528. {
  3529. QSqlDatabase database = AppInstance->database();
  3530. database.open();
  3531. q = new QSqlQuery(query, database);
  3532. connection = database.connectionName();
  3533. }
  3534. @ The destructor handles removing the |QSqlQuery| and the database connection
  3535. associated with it. The extra brackets introduce a new scope for the
  3536. |QSqlDatabase| so that it is out of scope when the connection is removed.
  3537. @<SqlQueryConnection implementation@>=
  3538. SqlQueryConnection::~SqlQueryConnection()
  3539. {
  3540. delete q;
  3541. {
  3542. QSqlDatabase database = QSqlDatabase::database(connection);
  3543. database.close();
  3544. }
  3545. QSqlDatabase::removeDatabase(connection);
  3546. }
  3547. @ For all other functionality, we simply forward the request to our |QSqlQuery|
  3548. object.
  3549. @<SqlQueryConnection implementation@>=
  3550. QSqlQuery* SqlQueryConnection::operator->() const
  3551. {
  3552. return q;
  3553. }
  3554. @ In order to use this new class in the host environment, a number of functions
  3555. are needed.
  3556. @<Function prototypes for scripting@>=
  3557. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine);
  3558. QScriptValue constructQSqlQuery(QScriptContext *context, QScriptEngine *engine);
  3559. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *engine);
  3560. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  3561. QScriptEngine *engine);
  3562. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  3563. QScriptEngine *engine);
  3564. QScriptValue QSqlQuery_exec(QScriptContext *context,
  3565. QScriptEngine *engine);
  3566. QScriptValue QSqlQuery_executedQuery(QScriptContext *context,
  3567. QScriptEngine *engine);
  3568. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *engine);
  3569. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine);
  3570. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine);
  3571. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine);
  3572. @ For conceptual convenience we simply pretend that we are working with a real
  3573. |QSqlQuery| object.
  3574. @<Set up the scripting engine@>=
  3575. constructor = engine->newFunction(constructQSqlQuery);
  3576. engine->globalObject().setProperty("QSqlQuery", constructor);
  3577. @ With connection creation no longer needed in the constructor, all that is
  3578. needed is object creation and applying the appropriate properties to the script
  3579. value.
  3580. @<Functions for scripting@>=
  3581. QScriptValue constructQSqlQuery(QScriptContext *, QScriptEngine *engine)
  3582. {
  3583. SqlQueryConnection *obj = new SqlQueryConnection();
  3584. QScriptValue object =
  3585. engine->toScriptValue<void *>(obj);
  3586. setQSqlQueryProperties(object, engine);
  3587. return object;
  3588. }
  3589. @ As this class does not derive from |QObject|, we must wrap all of the methods
  3590. we might want to use.
  3591. @<Functions for scripting@>=
  3592. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine)
  3593. {
  3594. value.setProperty("bind", engine->newFunction(QSqlQuery_bind));
  3595. value.setProperty("bindFileData",
  3596. engine->newFunction(QSqlQuery_bindFileData));
  3597. value.setProperty("bindDeviceData",
  3598. engine->newFunction(QSqlQuery_bindDeviceData));
  3599. value.setProperty("exec", engine->newFunction(QSqlQuery_exec));
  3600. value.setProperty("executedQuery", engine->newFunction(QSqlQuery_executedQuery));
  3601. value.setProperty("invalidate", engine->newFunction(QSqlQuery_invalidate));
  3602. value.setProperty("next", engine->newFunction(QSqlQuery_next));
  3603. value.setProperty("prepare", engine->newFunction(QSqlQuery_prepare));
  3604. value.setProperty("value", engine->newFunction(QSqlQuery_value));
  3605. }
  3606. @ Most of these properties are wrappers around existing |QSqlQuery| functions.
  3607. @<Functions for scripting@>=
  3608. QScriptValue QSqlQuery_exec(QScriptContext *context, QScriptEngine *engine)
  3609. {
  3610. QSqlQuery *q = getself<SqlQueryConnection *>(context)->operator->();
  3611. QScriptValue retval;
  3612. if(context->argumentCount() == 1)
  3613. {
  3614. retval = QScriptValue(engine,
  3615. q->exec(argument<QString>(0, context)));
  3616. }
  3617. else
  3618. {
  3619. retval = QScriptValue(engine, q->exec());
  3620. }
  3621. if(q->lastError().isValid())
  3622. {
  3623. qDebug() << q->lastQuery();
  3624. qDebug() << q->lastError().text();
  3625. }
  3626. return retval;
  3627. }
  3628. QScriptValue QSqlQuery_executedQuery(QScriptContext *context, QScriptEngine *)
  3629. {
  3630. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3631. return QScriptValue(query->lastQuery());
  3632. }
  3633. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine)
  3634. {
  3635. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3636. return QScriptValue(engine, query->next());
  3637. }
  3638. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine)
  3639. {
  3640. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3641. return QScriptValue(engine,
  3642. query->value(argument<int>(0, context)).toString());
  3643. }
  3644. @ For prepared queries, we support binding variables available to the script,
  3645. data available in a named file, or data from any open |QIODevice|.
  3646. @<Functions for scripting@>=
  3647. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine)
  3648. {
  3649. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3650. return QScriptValue(engine, query->prepare(argument<QString>(0, context)));
  3651. }
  3652. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *)
  3653. {
  3654. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3655. query->bindValue(argument<QString>(0, context),
  3656. argument<QVariant>(1, context));
  3657. return QScriptValue();
  3658. }
  3659. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  3660. QScriptEngine *)
  3661. {
  3662. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3663. QString placeholder = argument<QString>(0, context);
  3664. QString filename = argument<QString>(1, context);
  3665. QFile file(filename);
  3666. QByteArray data;
  3667. if(file.open(QIODevice::ReadOnly))
  3668. {
  3669. data = file.readAll();
  3670. file.close();
  3671. }
  3672. query->bindValue(placeholder, data);
  3673. return QScriptValue();
  3674. }
  3675. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  3676. QScriptEngine *)
  3677. {
  3678. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3679. QString placeholder = argument<QString>(0, context);
  3680. QIODevice *device = argument<QIODevice *>(1, context);
  3681. device->reset();
  3682. QByteArray data;
  3683. data = device->readAll();
  3684. query->bindValue(placeholder, data);
  3685. return QScriptValue();
  3686. }
  3687. @ To avoid leaking database connections, we add the |invalidate()| property
  3688. which destroys our object. The object on which this method is called must not be
  3689. used after calling this method. In script code this will typically be used as in
  3690. the following example:
  3691. {\tt query = query.invalidate();}
  3692. @<Functions for scripting@>=
  3693. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *)
  3694. {
  3695. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  3696. delete query;
  3697. return QScriptValue::UndefinedValue;
  3698. }
  3699. @* Other scripting functions.
  3700. \noindent There are a few functions that are exposed to the scripting engine
  3701. that are not associated with any class. Two functions are used for extracting
  3702. information from file names. Another is used to construct array values from SQL
  3703. array values. There is also a function for setting the default font for the
  3704. application or some part of the application.
  3705. @<Function prototypes for scripting@>=
  3706. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine);
  3707. QScriptValue dir(QScriptContext *context, QScriptEngine *engine);
  3708. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine);
  3709. QScriptValue setFont(QScriptContext *context, QScriptEngine *engine);
  3710. QScriptValue annotationFromRecord(QScriptContext *context,
  3711. QScriptEngine *engine);
  3712. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *engine);
  3713. QScriptValue saveFileFromDatabase(QScriptContext *context, QScriptEngine *engine);
  3714. QScriptValue scriptTr(QScriptContext *context, QScriptEngine *engine);
  3715. @ These functions are passed to the scripting engine.
  3716. @<Set up the scripting engine@>=
  3717. engine->globalObject().setProperty("baseName", engine->newFunction(baseName));
  3718. engine->globalObject().setProperty("dir", engine->newFunction(dir));
  3719. engine->globalObject().setProperty("sqlToArray",
  3720. engine->newFunction(sqlToArray));
  3721. engine->globalObject().setProperty("setFont", engine->newFunction(setFont));
  3722. engine->globalObject().setProperty("annotationFromRecord",
  3723. engine->newFunction(annotationFromRecord));
  3724. engine->globalObject().setProperty("setTabOrder",
  3725. engine->newFunction(setTabOrder));
  3726. engine->globalObject().setProperty("saveFileFromDatabase",
  3727. engine->newFunction(saveFileFromDatabase));
  3728. engine->globalObject().setProperty("TTR", engine->newFunction(scriptTr));
  3729. @ These functions are not part of an object. They expect a string specifying
  3730. the path to a file and return a string with either the name of the file without
  3731. the path and extension or the path of the directory containing the file.
  3732. @<Functions for scripting@>=
  3733. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine)
  3734. {
  3735. QFileInfo info(argument<QString>(0, context));
  3736. QScriptValue retval(engine, info.baseName());
  3737. return retval;
  3738. }
  3739. QScriptValue dir(QScriptContext *context, QScriptEngine *engine)
  3740. {
  3741. QFileInfo info(argument<QString>(0, context));
  3742. QDir dir = info.dir();
  3743. QScriptValue retval(engine, dir.path());
  3744. return retval;
  3745. }
  3746. @ This function takes a file ID and a file name and copies file data stored in
  3747. the database out to the file system.
  3748. @<Functions for scripting@>=
  3749. QScriptValue saveFileFromDatabase(QScriptContext *context, QScriptEngine *)
  3750. {
  3751. SqlQueryConnection h;
  3752. QSqlQuery *query = h.operator->();
  3753. QString q = "SELECT file FROM files WHERE id = :file";
  3754. query->prepare(q);
  3755. query->bindValue(":file", argument<int>(0, context));
  3756. query->exec();
  3757. query->next();
  3758. QByteArray array = query->value(0).toByteArray();
  3759. QFile file(argument<QString>(1, context));
  3760. file.open(QIODevice::WriteOnly);
  3761. file.write(array);
  3762. file.close();
  3763. return QScriptValue();
  3764. }
  3765. @ This function takes a string representing a SQL array and returns an array
  3766. value.
  3767. @<Functions for scripting@>=
  3768. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine)
  3769. {
  3770. QString source = argument<QString>(0, context);
  3771. source.remove(0, 1);
  3772. source.chop(1);
  3773. QStringList elements = source.split(",");
  3774. QString element;
  3775. QScriptValue dest = engine->newArray(elements.size());
  3776. int i = 0;
  3777. foreach(element, elements)
  3778. {
  3779. if(element.startsWith("\"") && element.endsWith("\""))
  3780. {
  3781. element.chop(1);
  3782. element = element.remove(0, 1);
  3783. }
  3784. dest.setProperty(i, QScriptValue(engine, element));
  3785. i++;
  3786. }
  3787. return dest;
  3788. }
  3789. @ This function can be used to set the default font for the application or on
  3790. a per-class hierarchy basis.
  3791. @<Functions for scripting@>=
  3792. QScriptValue setFont(QScriptContext *context, QScriptEngine *)
  3793. {
  3794. QString font = argument<QString>(0, context);
  3795. QString classname;
  3796. if(context->argumentCount() > 1)
  3797. {
  3798. classname = argument<QString>(1, context);
  3799. QApplication::setFont(QFont(font), classname.toLatin1().constData());
  3800. }
  3801. else
  3802. {
  3803. QApplication::setFont(QFont(font));
  3804. }
  3805. return QScriptValue();
  3806. }
  3807. @ This function was briefly used prior to adding support for |QXmlQuery| in the
  3808. host environment. The function is now depreciated and should not be used.
  3809. @<Functions for scripting@>=
  3810. QScriptValue annotationFromRecord(QScriptContext *context, QScriptEngine *)
  3811. {
  3812. SqlQueryConnection h;
  3813. QSqlQuery *query = h.operator->();
  3814. QString q = "SELECT file FROM files WHERE id = :file";
  3815. query->prepare(q);
  3816. query->bindValue(":file", argument<int>(0, context));
  3817. query->exec();
  3818. query->next();
  3819. QByteArray array = query->value(0).toByteArray();
  3820. QBuffer buffer(&array);
  3821. buffer.open(QIODevice::ReadOnly);
  3822. QXmlQuery xquery;
  3823. xquery.bindVariable("profile", &buffer);
  3824. QString xq;
  3825. xq = "for $b in doc($profile) //tuple where exists($b/annotation) return $b";
  3826. xquery.setQuery(xq);
  3827. QString result;
  3828. xquery.evaluateTo(&result);
  3829. return QScriptValue(result);
  3830. }
  3831. @ This function can be used to change the tab order for controls in Typica.
  3832. Changes to the example configuration in \pn{} 1.4 made the default handling
  3833. of tab controls in the logging window unacceptable.
  3834. @<Functions for scripting@>=
  3835. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *)
  3836. {
  3837. QWidget::setTabOrder(argument<QWidget*>(0, context),
  3838. argument<QWidget*>(1, context));
  3839. return QScriptValue();
  3840. }
  3841. @ This function is used to allow text that must be placed in scripts to be
  3842. translated into other languages.
  3843. @<Functions for scripting@>=
  3844. QScriptValue scriptTr(QScriptContext *context, QScriptEngine *)
  3845. {
  3846. return QScriptValue(QCoreApplication::translate(
  3847. "configuration",
  3848. argument<QString>(1, context).toUtf8().data()));
  3849. }
  3850. @** Application Configuration.
  3851. \noindent While \pn{} is intended as a data logging application, the diversity
  3852. of equipment and supporting technology precludes the option of providing a
  3853. single interface for common tasks. It is important that the application can be
  3854. configured to work with different roasting equipment, databases, and the like.
  3855. To accomplish this, \pn{} utilizes an XML description of the desired application
  3856. configuration and provides an ECMA-262 host environment which allows application
  3857. dataflow to be configured.
  3858. The scripting environment provides access to elements of the XML file and also
  3859. allows access to most of the application classes. A selection of classes
  3860. provided by Qt is also available. See the section on The Scripting Engine for
  3861. more details.
  3862. \danger While the code is the ultimate documentation of what is possible with
  3863. this interface, additional documentation should be provided to document the
  3864. meaning of supported elements and the objects available through the scripting
  3865. engine.\endanger
  3866. The application configuration is loaded when the program is started.
  3867. Starting with version 1.4, we check for a command line option with the path to
  3868. the configuration file and load that instead of prompting for the information
  3869. if possible.
  3870. Starting with version 1.8, if there is not a -c argument, Typica will first
  3871. search a small number of locations relative to the executable.
  3872. @<Load the application configuration@>=
  3873. QStringList arguments = QCoreApplication::arguments();
  3874. int position = arguments.indexOf("-c");
  3875. QString filename = QString();
  3876. if(position != -1)
  3877. {
  3878. if(arguments.size() >= position + 1)
  3879. {
  3880. filename = arguments.at(position + 1);
  3881. }
  3882. } else {
  3883. QDir checkPath(QCoreApplication::applicationDirPath() + "/../config/");
  3884. if(checkPath.exists("config.xml")) {
  3885. filename = checkPath.filePath("config.xml");
  3886. } else {
  3887. checkPath = QDir(QCoreApplication::applicationDirPath() + "/config/");
  3888. if(checkPath.exists("config.xml")) {
  3889. filename = checkPath.filePath("config.xml");
  3890. }
  3891. }
  3892. }
  3893. if(filename.isEmpty())
  3894. {
  3895. filename = QFileDialog::getOpenFileName(NULL, "Open Configuration File",
  3896. settings.value("config", "").toString());
  3897. }
  3898. QDir directory;
  3899. if(!filename.isEmpty())
  3900. {
  3901. QFile file(filename);
  3902. QFileInfo info(filename);
  3903. directory = info.dir();
  3904. QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
  3905. QTranslator *configtr = new QTranslator;
  3906. if(configtr->load(QString("config.%1").arg(QLocale::system().name()),
  3907. QString("%1/Translations").arg(directory.canonicalPath())))
  3908. {
  3909. QCoreApplication::installTranslator(configtr);
  3910. }
  3911. settings.setValue("config", directory.path());
  3912. if(file.open(QIODevice::ReadOnly))
  3913. {
  3914. app.configuration()->setContent(&file, true);
  3915. }
  3916. } else {
  3917. return 1;
  3918. }
  3919. @<Substitute included fragments@>@;
  3920. @ The {\tt <application>} element can contain an arbitrary number of
  3921. {\tt <include>} elements. These elements should not appear in the DOM. Instead,
  3922. the element should be replaced by the content of the specified document.
  3923. @<Substitute included fragments@>=
  3924. QDomElement root = app.configuration()->documentElement();
  3925. QDomNodeList children = root.childNodes();
  3926. QString replacementDoc;
  3927. QDomDocument includedDoc;
  3928. QDomDocumentFragment fragment;
  3929. for(int i = 0; i < children.size(); i++)
  3930. {
  3931. QDomNode currentNode = children.at(i);
  3932. QDomElement currentElement;
  3933. if(currentNode.nodeName() == "include")
  3934. {
  3935. currentElement = currentNode.toElement();
  3936. if(currentElement.hasAttribute("src"))
  3937. {
  3938. replacementDoc = directory.path();
  3939. replacementDoc.append('/');
  3940. replacementDoc.append(currentElement.attribute("src"));
  3941. QFile doc(replacementDoc);
  3942. if(doc.open(QIODevice::ReadOnly))
  3943. {
  3944. includedDoc.setContent(&doc, true);
  3945. fragment = includedDoc.createDocumentFragment();
  3946. fragment.appendChild(includedDoc.documentElement());
  3947. root.replaceChild(fragment, currentNode);
  3948. doc.close();
  3949. }
  3950. }
  3951. }
  3952. }
  3953. @ Simply loading the configuration document does not display a user interface or
  3954. set up any objects that allow the program to do anything. To do this, a script
  3955. obtained from the configuration document is run. The root element of the
  3956. document should be {\tt <application>}. This element should have a number of
  3957. child elements including {\tt <window>} elements which describe the various
  3958. windows that can be opened in the application and {\tt <program>} elements
  3959. containing script code. These {\tt <program>} elements can occur in a number of
  3960. different contexts including within {\tt <window>} elements which would indicate
  3961. that such scripts should be evaluated when the window being described is
  3962. created. After the configuration document is loaded, all {\tt <program>}
  3963. elements that are direct children of the {\tt <application>} element are
  3964. concatenated and the script is run.
  3965. Before the script is run and user interface elements are drawn, we also check
  3966. for {\tt <style>} elements which can be used to set up a stylesheet for the
  3967. application.
  3968. @<Find and evaluate starting script@>=
  3969. QString styleText;
  3970. QString programText;
  3971. QDomElement currentElement;
  3972. for(int i = 0; i < children.size(); i++)
  3973. {
  3974. QDomNode currentNode = children.at(i);
  3975. if(currentNode.nodeName() == "style")
  3976. {
  3977. currentElement = currentNode.toElement();
  3978. styleText.append(currentElement.text());
  3979. }
  3980. else if(currentNode.nodeName() == "program")
  3981. {
  3982. currentElement = currentNode.toElement();
  3983. programText.append(currentElement.text());
  3984. }
  3985. }
  3986. app.setStyleSheet(styleText);
  3987. QScriptValue result = engine->evaluate(programText);
  3988. @<Report scripting errors@>
  3989. @ When a script is evaluated, there is a chance that there will be some error in
  3990. the execution of that script. If this occurs, we want to report that.
  3991. @<Report scripting errors@>=
  3992. if(engine->hasUncaughtException())
  3993. {
  3994. int line = engine->uncaughtExceptionLineNumber();
  3995. qDebug() << "Uncaught excpetion at line " << line << " : " <<
  3996. result.toString();
  3997. QString trace;
  3998. foreach(trace, engine->uncaughtExceptionBacktrace())
  3999. {
  4000. qDebug() << trace;
  4001. }
  4002. }
  4003. @* Creating a window.
  4004. \noindent When a configuration document is loaded, none of the {\tt <window>}
  4005. elements are interpreted or used to create a graphical user interface. Instead,
  4006. any {\tt <program>} elements that are immediate children of the
  4007. {\tt <application>} element are interpreted. In order to convert a
  4008. {\tt <window>} element into a window displayed on screen, the script in the
  4009. {\tt <program>} elements must call a function to display a specified window.
  4010. Report windows can be produced by scripts in a similar, but slightly different
  4011. manner.
  4012. \danger This design works, but it'@q'@>s not particularly good design. It was written
  4013. under severe time constraints and should be redesigned or at least cleaned up
  4014. and reorganized.\endanger
  4015. @<Function prototypes for scripting@>=
  4016. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine);
  4017. QScriptValue createReport(QScriptContext *context, QScriptEngine *engine);
  4018. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  4019. QStack<QLayout*> *layoutStack);
  4020. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4021. QStack<QLayout *> *layoutStack);
  4022. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4023. QStack<QLayout *> *layoutStack);
  4024. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4025. QStack<QLayout *> *layoutStack);
  4026. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4027. QStack<QLayout *> *layoutStack);
  4028. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4029. QStack<QLayout *> *layoutStack);
  4030. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4031. QStack<QLayout *> *layoutStack);
  4032. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4033. QStack<QLayout *> *layoutStack);
  4034. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4035. QStack<QLayout *> *layoutStack);
  4036. void addTemperatureDisplayToSplitter(QDomElement element,@|
  4037. QStack<QWidget *> *widgetStack,
  4038. QStack<QLayout *> *layoutStack);
  4039. void addTemperatureDisplayToLayout(QDomElement element,@|
  4040. QStack<QWidget *> *widgetStack,
  4041. QStack<QLayout *> *layoutStack);
  4042. void addTimerDisplayToSplitter(QDomElement element,@|
  4043. QStack<QWidget *> *widgetStack,
  4044. QStack<QLayout *> *layoutStack);
  4045. void addTimerDisplayToLayout(QDomElement element,@|
  4046. QStack<QWidget *> *widgetStack,
  4047. QStack<QLayout *> *layoutStack);
  4048. void addDecorationToSplitter(QDomElement element,@|
  4049. QStack<QWidget *> *widgetStack,
  4050. QStack<QLayout *> *layoutStack);
  4051. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4052. QStack<QLayout *> *layoutStack);
  4053. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4054. QStack<QLayout *> *layoutStack);
  4055. void addButtonToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4056. QStack<QLayout *> *layoutStack);
  4057. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4058. QStack<QLayout *> *layoutStack);
  4059. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4060. QStack<QLayout *> *layoutStack);
  4061. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4062. QStack<QLayout *> *layoutStack);
  4063. void addSaltToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4064. QStack<QLayout *> *layoutStack);
  4065. void addLineToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4066. QStack<QLayout *> *layoutStack);
  4067. void addTextToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4068. QStack<QLayout *> *layoutStack);
  4069. void addSqlQueryViewToLayout(QDomElement element,
  4070. QStack<QWidget *> *widgetStack,
  4071. QStack<QLayout *> *layoutStack);
  4072. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4073. QStack<QLayout *> *layoutStack);
  4074. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4075. QStack<QLayout *> *layoutStack);
  4076. void addTimeEditToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4077. QStack<QLayout *> *layoutStack);
  4078. @ The functions for creating windows must be made available to the scripting
  4079. engine.
  4080. @<Set up the scripting engine@>=
  4081. engine->globalObject().setProperty("createWindow",
  4082. engine->newFunction(createWindow));
  4083. engine->globalObject().setProperty("createReport",
  4084. engine->newFunction(createReport));
  4085. @ This function must examine the configuration document in search of the
  4086. appropriate window element, parse the contents of that element, and create a
  4087. multitude of objects, all of which must be passed to the scripting engine.
  4088. @<Functions for scripting@>=
  4089. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine)@/
  4090. {
  4091. QString targetID = argument<QString>(0, context);
  4092. QDomNode element;
  4093. QScriptValue object;
  4094. @<Find the window element@>@;
  4095. if(!element.isNull())
  4096. {
  4097. @<Display the window@>@;
  4098. }
  4099. return object;
  4100. }
  4101. @ Report files are not part of the configuration document and must be created
  4102. differently. While there is a special menu type that handles all of this
  4103. without involving the host environment, scripted generation and manipulation of
  4104. report windows requires another function. This function will only work after a
  4105. window with a reports menu has been created.
  4106. @<Functions for scripting@>=
  4107. QScriptValue createReport(QScriptContext *context, QScriptEngine *engine)
  4108. {
  4109. QString targetID = argument<QString>(0, context);
  4110. QFile file(QString("reports:%1").arg(targetID));
  4111. QScriptValue object;
  4112. if(file.open(QIODevice::ReadOnly))
  4113. {
  4114. QDomDocument document;
  4115. document.setContent(&file, true);
  4116. QDomElement element = document.documentElement();
  4117. if(!element.isNull())
  4118. {
  4119. @<Display the window@>@;
  4120. }
  4121. file.close();
  4122. }
  4123. return object;
  4124. }
  4125. @ First we must locate the {\tt <window>} element. The most sensible way to do
  4126. this would require that each {\tt <window>} element has an ID attribute and
  4127. search the DOM tree for that ID. Unfortunately, as of this writing,
  4128. |QDomDocument::elementByID()| always returns a null element, so that won'@q'@>t work.
  4129. Instead, we search the tree for all {\tt <window>} elements and then examine
  4130. the resulting list to find the element with the appropriate ID.
  4131. @<Find the window element@>=
  4132. QDomNodeList windows =
  4133. AppInstance->configuration()->documentElement().elementsByTagName("window");
  4134. QDomNode nullNode;
  4135. int i = 0;
  4136. element = nullNode;
  4137. while(i < windows.count())
  4138. {
  4139. element = windows.at(i);
  4140. QDomNamedNodeMap attributes = element.attributes();
  4141. if(attributes.contains("id"))
  4142. {
  4143. if(attributes.namedItem("id").toAttr().value() == targetID)
  4144. {
  4145. break;
  4146. }
  4147. }
  4148. element = nullNode;
  4149. i++;
  4150. }
  4151. @ In order to display a window, we start by creating a new |ScriptQMainWindow|
  4152. and set the central widget of that window to a new |QWidget|. After this, we see
  4153. if the window element has any children and proceed to populate the window.
  4154. When creating child elements, care must be taken that all objects are descended
  4155. from the window. If an object is descended from the window and has an object
  4156. name, it will be possible for script code to recover the created object.
  4157. As of version 1.4, the window itself is given the value of its {\tt id}
  4158. attribute as an object name to facilitate automatic window geometry management.
  4159. @<Display the window@>=
  4160. ScriptQMainWindow *window = new ScriptQMainWindow;
  4161. window->setObjectName(targetID);
  4162. object = engine->newQObject(window);
  4163. setQMainWindowProperties(object, engine);
  4164. QWidget *central = new(QWidget);
  4165. central->setParent(window);
  4166. central->setObjectName("centralWidget");
  4167. window->setCentralWidget(central);
  4168. if(element.hasChildNodes())
  4169. {
  4170. @<Process window children@>@;
  4171. }
  4172. @<Insert help menu@>@;
  4173. window->show();
  4174. window->setupFinished();
  4175. @ Three element types make sense as top level children of a {\tt <window>}
  4176. element. An element representing a layout element can be used to apply that
  4177. layout to the central widget. An element representing a menu can be used to add
  4178. a menu to the window. A {\tt <program>} element can be used to specify a script
  4179. to be run after the window has been assembled.
  4180. \danger As the window comes with a blank central widget, elements representing
  4181. a widget to be used as the central widget of the window cannot be used directly
  4182. here. If only one widget is needed in the window, there is a need to create a
  4183. layout element and place that widget in the layout. Also note that there is not
  4184. enough error checking in the following code. Provide invalid input at your
  4185. peril.\endanger
  4186. Program fragments pulled from the window description are executed with the
  4187. newly created window available as {\tt this}. When such a fragment is run, the
  4188. entire description of the window will have already been evaluated and any
  4189. necessary objects created. Obtaining a child object of the window can be done
  4190. by calling |findChildObject()|.
  4191. @<Process window children@>=
  4192. QStack<QWidget*> widgetStack;
  4193. QStack<QLayout*> layoutStack;
  4194. QString windowScript;
  4195. widgetStack.push(central);
  4196. QDomNodeList windowChildren = element.childNodes();
  4197. int i = 0;
  4198. while(i < windowChildren.count())
  4199. {
  4200. QDomNode current;
  4201. QDomElement element;
  4202. current = windowChildren.at(i);
  4203. if(current.isElement())
  4204. {
  4205. element = current.toElement();
  4206. if(element.tagName() == "program")
  4207. {
  4208. windowScript.append(element.text());
  4209. }
  4210. else if(element.tagName() == "layout")
  4211. {
  4212. element.setAttribute("trcontext", "configuration");
  4213. addLayoutToWidget(element, &widgetStack, &layoutStack);
  4214. }
  4215. else if(element.tagName() == "menu")
  4216. {
  4217. @<Process menus@>@;
  4218. }
  4219. }
  4220. i++;
  4221. }
  4222. QScriptValue oldThis = context->thisObject();
  4223. context->setThisObject(object);
  4224. QScriptValue result = engine->evaluate(windowScript);
  4225. @<Report scripting errors@>@;
  4226. context->setThisObject(oldThis);
  4227. @ Elements representing menus may provide a number of child elements
  4228. representing the items in that menu. The XML portion of the configuration will
  4229. not provide any information on what these menu items do. The contents of the
  4230. {\tt <program>} element for the window will need to request the |QAction|
  4231. objects and connect a signal from that object to the desired functionality.
  4232. One special consideration is the Reports menu. This menu will populate itself
  4233. according to its own logic and will have a {\tt type} property of
  4234. {\tt "reports"} and a {\tt src} property indicating the directory where reports
  4235. can be found.
  4236. @<Process menus@>=
  4237. QMenuBar *bar = window->menuBar();
  4238. bar->setParent(window);
  4239. bar->setObjectName("menuBar");
  4240. if(element.hasAttribute("name"))
  4241. {
  4242. QMenu *menu = bar->addMenu(QCoreApplication::translate("configuration",
  4243. element.attribute("name").toUtf8().data()));
  4244. menu->setParent(bar);
  4245. if(element.hasAttribute("type"))
  4246. {
  4247. if(element.attribute("type") == "reports")
  4248. {
  4249. if(element.hasAttribute("src"))
  4250. {
  4251. @<Populate reports menu@>@;
  4252. }
  4253. }
  4254. }
  4255. if(element.hasChildNodes())
  4256. {
  4257. @<Process menu items@>@;
  4258. }
  4259. }
  4260. @ To add items to a menu, we check for {\tt <item>} elements under the
  4261. {\tt <menu>} element and create a |QAction| for each item.
  4262. @<Process menu items@>=
  4263. QDomNodeList menuItems = element.childNodes();
  4264. int j = 0;
  4265. while(j < menuItems.count())
  4266. {
  4267. QDomNode item = menuItems.at(j);
  4268. if(item.isElement())
  4269. {
  4270. QDomElement itemElement = item.toElement();
  4271. if(itemElement.tagName() == "item")
  4272. {
  4273. QAction *itemAction = new QAction(QCoreApplication::translate("configuration",
  4274. itemElement.text().toUtf8().data()), menu);
  4275. if(itemElement.hasAttribute("id"))
  4276. {
  4277. itemAction->setObjectName(itemElement.attribute("id"));
  4278. }
  4279. if(itemElement.hasAttribute("shortcut"))
  4280. {
  4281. itemAction->setShortcut(itemElement.attribute("shortcut"));
  4282. }
  4283. menu->addAction(itemAction);
  4284. }
  4285. else if(itemElement.tagName() == "separator")
  4286. {
  4287. menu->addSeparator();
  4288. }
  4289. else if(itemElement.tagName() == "plugins")
  4290. {
  4291. @<Process plugin item@>@;
  4292. }
  4293. }
  4294. j++;
  4295. }
  4296. @i helpmenu.w
  4297. @i licensewindow.w
  4298. @ A layout can contain a number of different elements including a variety of
  4299. widget types and other layouts. This function is responsible for applying any
  4300. layout class to the widget currently being populated and processing children of
  4301. the {\tt <layout>} element to populate that layout. External stacks are used to
  4302. keep track of which widgets and layouts are currently being populated. The
  4303. {\tt type} attribute is used to determine what sort of layout should be created.
  4304. Currently, {\tt horizontal}, {\tt vertical}, {\tt grid}, and {\tt stack} types
  4305. are supported. The first two resolve to |QBoxLayout| layouts, {\tt grid}
  4306. resolves to a |QGridLayout|, and {\tt stack} resolves to a |QStackedLayout|.
  4307. @<Functions for scripting@>=
  4308. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  4309. QStack<QLayout*> *layoutStack)
  4310. {
  4311. if(element.hasAttribute("type"))
  4312. {
  4313. @<Create and populate layout@>@;
  4314. QWidget *widget = widgetStack->top();
  4315. if(layout)
  4316. {
  4317. widget->setLayout(layout);
  4318. }
  4319. layoutStack->pop();
  4320. }
  4321. }
  4322. @ As there are multiple places where a {\tt <layout>} element is parsed with
  4323. slightly different semantics, the code for creating and populating the layout is
  4324. broken out so that code written to support additional layout types only needs to
  4325. be written once.
  4326. @<Create and populate layout@>=
  4327. QLayout *layout;
  4328. QString layoutType = element.attribute("type");
  4329. if(layoutType == "horizontal")
  4330. {
  4331. layout = new QHBoxLayout;
  4332. layoutStack->push(layout);
  4333. populateBoxLayout(element, widgetStack, layoutStack);
  4334. }
  4335. else if(layoutType == "vertical")
  4336. {
  4337. layout = new QVBoxLayout;
  4338. layoutStack->push(layout);
  4339. populateBoxLayout(element, widgetStack, layoutStack);
  4340. }
  4341. else if(layoutType == "grid")
  4342. {
  4343. layout = new QGridLayout;
  4344. layoutStack->push(layout);
  4345. populateGridLayout(element, widgetStack, layoutStack);
  4346. }
  4347. else if(layoutType == "stack")
  4348. {
  4349. layout = new QStackedLayout;
  4350. layoutStack->push(layout);
  4351. populateStackedLayout(element, widgetStack, layoutStack);
  4352. }
  4353. if(element.hasAttribute("id"))
  4354. {
  4355. layout->setObjectName(element.attribute("id"));
  4356. }
  4357. if(element.hasAttribute("spacing"))
  4358. {
  4359. layout->setSpacing(element.attribute("spacing").toInt());
  4360. }
  4361. if(element.hasAttribute("margin"))
  4362. {
  4363. int m = element.attribute("margin").toInt();
  4364. layout->setContentsMargins(m, m, m, m);
  4365. }
  4366. @ Stacked layouts are a bit different from the other types. A stacked layout has
  4367. an arbitrary number of {\tt <page>} children which are just a |QWidget| which
  4368. can have the same child elements as {\tt <widget>} elements elsewhere. Only the
  4369. first page will be visible initially, however it is possible to use script code
  4370. to set the currently visible page provided that an ID is set for the layout.
  4371. @<Functions for scripting@>=
  4372. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4373. QStack<QLayout *> *layoutStack)
  4374. {
  4375. QDomNodeList children = element.childNodes();
  4376. QStackedLayout *layout = qobject_cast<QStackedLayout *>(layoutStack->top());
  4377. for(int i = 0; i < children.count(); i++)
  4378. {
  4379. QDomNode current;
  4380. QDomElement currentElement;
  4381. current = children.at(i);
  4382. if(current.isElement())
  4383. {
  4384. currentElement = current.toElement();
  4385. if(currentElement.tagName() == "page")
  4386. {
  4387. QWidget *widget = new QWidget;
  4388. layout->addWidget(widget);
  4389. widgetStack->push(widget);
  4390. currentElement.setAttribute("trcontext", "configuration");
  4391. populateWidget(currentElement, widgetStack, layoutStack);
  4392. widgetStack->pop();
  4393. }
  4394. }
  4395. }
  4396. }
  4397. @ A common use of stacked layouts is in the creation of tabbed interfaces, but
  4398. there are also many uses in \pn{} where the tabs are not required. Therefore,
  4399. tab bar creation requires a separate XML element.
  4400. @<Additional box layout elements@>=
  4401. else if(currentElement.tagName() == "tabbar")
  4402. {
  4403. addTabBarToLayout(currentElement, widgetStack, layoutStack);
  4404. }
  4405. @ The function used to create this follows the usual pattern.
  4406. @<Functions for scripting@>=
  4407. void addTabBarToLayout(QDomElement element, QStack<QWidget*> *, QStack<QLayout*> *layoutStack)
  4408. {
  4409. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4410. QTabBar *widget = new QTabBar;
  4411. layout->addWidget(widget);
  4412. if(!element.attribute("id").isEmpty())
  4413. {
  4414. widget->setObjectName(element.attribute("id"));
  4415. }
  4416. }
  4417. @ Rather than define the tab set in XML, this is left to the host environment.
  4418. This means that some additional scripting support is required.
  4419. @<Set up the scripting engine@>=
  4420. constructor = engine->newFunction(constructQTabBar);
  4421. value = engine->newQMetaObject(&QTabBar::staticMetaObject, constructor);
  4422. engine->globalObject().setProperty("QTabBar", value);
  4423. @ The constructor is trivial.
  4424. @<Functions for scripting@>=
  4425. QScriptValue constructQTabBar(QScriptContext *, QScriptEngine *engine)
  4426. {
  4427. QScriptValue object = engine->newQObject(new QTabBar);
  4428. setQTabBarProperties(object, engine);
  4429. return object;
  4430. }
  4431. @ There are many functions that I might want to some day add support for, but
  4432. the immediate need is just creating the tabs in the first place.
  4433. @<Functions for scripting@>=
  4434. void setQTabBarProperties(QScriptValue value, QScriptEngine *engine)
  4435. {
  4436. setQWidgetProperties(value, engine);
  4437. value.setProperty("addTab", engine->newFunction(QTabBar_addTab));
  4438. }
  4439. QScriptValue QTabBar_addTab(QScriptContext *context, QScriptEngine *)
  4440. {
  4441. QTabBar *self = getself<QTabBar *>(context);
  4442. if(context->argumentCount() > 0)
  4443. {
  4444. self->addTab(argument<QString>(0, context));
  4445. }
  4446. else
  4447. {
  4448. context->throwError("Incorrect number of arguments passed to "@|
  4449. "QTabBar::addTab().");
  4450. }
  4451. return QScriptValue();
  4452. }
  4453. @ Function prototypes are needed.
  4454. @<Function prototypes for scripting@>=
  4455. QScriptValue constructQTabBar(QScriptContext *context, QScriptEngine *engine);
  4456. void setQTabBarProperties(QScriptValue value, QScriptEngine *engine);
  4457. QScriptValue QTabBar_addTab(QScriptContext *context, QScriptEngine *engine);
  4458. @ Using a grid layout is a bit different from using a box layout. Child elements
  4459. with various attributes are required to take full advantage of this layout type.
  4460. All direct children of a grid layout element should be {\tt <row>} elements
  4461. which may have optional {\tt height} and {\tt stretch} attributes which apply to
  4462. that row.
  4463. @<Functions for scripting@>=
  4464. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4465. QStack<QLayout *> *layoutStack)
  4466. {
  4467. QDomNodeList children = element.childNodes();
  4468. int row = -1;
  4469. QGridLayout *layout = qobject_cast<QGridLayout *>(layoutStack->top());
  4470. for(int i = 0; i < children.count(); i++)
  4471. {
  4472. QDomNode current;
  4473. QDomElement currentElement;
  4474. current = children.at(i);
  4475. if(current.isElement())
  4476. {
  4477. currentElement = current.toElement();
  4478. if(currentElement.tagName() == "row")
  4479. {
  4480. row++;
  4481. if(currentElement.hasAttribute("height"))
  4482. {
  4483. layout->setRowMinimumHeight(row,
  4484. currentElement.attribute("height").toInt());
  4485. }
  4486. if(currentElement.hasAttribute("stretch"))
  4487. {
  4488. layout->setRowStretch(row,
  4489. currentElement.attribute("stretch").toInt());
  4490. }
  4491. @<Populate grid layout row@>@;
  4492. }
  4493. }
  4494. }
  4495. }
  4496. @ Each {\tt <row>} may have arbitrarily many {\tt <column>} children. A row with
  4497. nothing in it or that is entirely populated by spanning cells from previous rows
  4498. might have no children.
  4499. The {\tt <column>} element supports several optional attributes. The
  4500. {\tt column} attribute can be used to specify which column the element refers
  4501. to. Sibling {\tt <column>} elements will refer to columns farther right unless
  4502. a lower column number is specified. This does mean that it is possible to
  4503. specify the same column more than once, however actually doing so is not
  4504. recommended. The {\tt width} attribute specifies the minimum width of the
  4505. column. If multiple cells in a column specify this attribute, the last one takes
  4506. priority. Similarly, the {\tt stretch} attribute specifies the column stretch.
  4507. The {\tt rowspan} and {\tt colspan} attributes can be used for cells that span
  4508. more than one row or column. A value of |-1| can be used to have the cell span
  4509. to the last row or column in the layout.
  4510. Once the attributes of the cell are known, a |QHBoxLayout| is added to the
  4511. layout at the appropriate location in the grid and it is this layout which is
  4512. further populated by child elements. Anything that can be placed under a
  4513. {\tt <layout>} element with {\tt "horizontal"} or {\tt "vertical"} {\tt type}
  4514. attribute can be a child of a {\tt <column>} element in this context.
  4515. @<Populate grid layout row@>=
  4516. int column = -1;
  4517. QDomNodeList rowChildren = currentElement.childNodes();
  4518. for(int j = 0; j < rowChildren.count(); j++)
  4519. {
  4520. QDomNode columnNode;
  4521. QDomElement columnElement;
  4522. columnNode = rowChildren.at(j);
  4523. if(columnNode.isElement())
  4524. {
  4525. columnElement = columnNode.toElement();
  4526. if(columnElement.tagName() == "column")
  4527. {
  4528. column++;
  4529. if(columnElement.hasAttribute("column"))
  4530. {
  4531. column = columnElement.attribute("column").toInt();
  4532. }
  4533. if(columnElement.hasAttribute("width"))
  4534. {
  4535. layout->setColumnMinimumWidth(column,
  4536. columnElement.attribute("width").toInt());
  4537. }
  4538. if(columnElement.hasAttribute("stretch"))
  4539. {
  4540. layout->setColumnStretch(column,
  4541. columnElement.attribute("stretch").toInt());
  4542. }
  4543. int hspan = 1;
  4544. int vspan = 1;
  4545. if(columnElement.hasAttribute("rowspan"))
  4546. {
  4547. vspan = columnElement.attribute("rowspan").toInt();
  4548. }
  4549. if(columnElement.hasAttribute("colspan"))
  4550. {
  4551. hspan = columnElement.attribute("colspan").toInt();
  4552. }
  4553. QHBoxLayout *cell = new QHBoxLayout;
  4554. layout->addLayout(cell, row, column, vspan, hspan);
  4555. layoutStack->push(cell);
  4556. columnElement.setAttribute("trcontext", "configuration");
  4557. populateBoxLayout(columnElement, widgetStack, layoutStack);
  4558. layoutStack->pop();
  4559. }
  4560. }
  4561. }
  4562. @ Box layouts are populated by checking for child elements representing
  4563. supported widget types and layouts and adding these to the current layout.
  4564. @<Functions for scripting@>=
  4565. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4566. QStack<QLayout *> *layoutStack)
  4567. {
  4568. QDomNodeList children = element.childNodes();
  4569. for(int i = 0; i < children.count(); i++)
  4570. {
  4571. QDomNode current;
  4572. QDomElement currentElement;
  4573. current = children.at(i);
  4574. if(current.isElement())
  4575. {
  4576. currentElement = current.toElement();
  4577. currentElement.setAttribute("trcontext", "configuration");
  4578. if(currentElement.tagName() == "button")
  4579. {
  4580. addButtonToLayout(currentElement, widgetStack, layoutStack);
  4581. }
  4582. else if(currentElement.tagName() == "calendar")
  4583. {
  4584. addCalendarToLayout(currentElement, widgetStack, layoutStack);
  4585. }
  4586. else if(currentElement.tagName() == "timeedit")
  4587. {
  4588. addTimeEditToLayout(currentElement, widgetStack, layoutStack);
  4589. }
  4590. else if(currentElement.tagName() == "decoration")
  4591. {
  4592. addDecorationToLayout(currentElement, widgetStack,
  4593. layoutStack);
  4594. }
  4595. else if(currentElement.tagName() == "layout")
  4596. {
  4597. addLayoutToLayout(currentElement, widgetStack, layoutStack);
  4598. }
  4599. else if(currentElement.tagName() == "splitter")
  4600. {
  4601. addSplitterToLayout(currentElement, widgetStack, layoutStack);
  4602. }
  4603. else if(currentElement.tagName() == "label")
  4604. {
  4605. QBoxLayout *layout =
  4606. qobject_cast<QBoxLayout *>(layoutStack->top());
  4607. QLabel *label = new QLabel(QCoreApplication::translate(
  4608. "configuration",
  4609. currentElement.text().toUtf8().data()));
  4610. if(currentElement.hasAttribute("id"))
  4611. {
  4612. label->setObjectName(currentElement.attribute("id"));
  4613. }
  4614. layout->addWidget(label);
  4615. }
  4616. else if(currentElement.tagName() == "lcdtemperature")
  4617. {
  4618. addTemperatureDisplayToLayout(currentElement, widgetStack,
  4619. layoutStack);
  4620. }
  4621. else if(currentElement.tagName() == "lcdtimer")
  4622. {
  4623. addTimerDisplayToLayout(currentElement, widgetStack,
  4624. layoutStack);
  4625. }
  4626. else if(currentElement.tagName() == "line")
  4627. {
  4628. addLineToLayout(currentElement, widgetStack, layoutStack);
  4629. }
  4630. else if(currentElement.tagName() == "report")
  4631. {
  4632. addReportToLayout(currentElement, widgetStack, layoutStack);
  4633. }
  4634. else if(currentElement.tagName() == "sqldrop")
  4635. {
  4636. addSqlDropToLayout(currentElement, widgetStack, layoutStack);
  4637. }
  4638. else if(currentElement.tagName() == "sqltablearray")
  4639. {
  4640. addSaltToLayout(currentElement, widgetStack, layoutStack);
  4641. }
  4642. else if(currentElement.tagName() == "sqlview")
  4643. {
  4644. addSqlQueryViewToLayout(currentElement, widgetStack,
  4645. layoutStack);
  4646. }
  4647. else if(currentElement.tagName() == "textarea")
  4648. {
  4649. addTextToLayout(currentElement, widgetStack, layoutStack);
  4650. }
  4651. else if(currentElement.tagName() == "spinbox")
  4652. {
  4653. addSpinBoxToLayout(currentElement, widgetStack, layoutStack);
  4654. }
  4655. else if(currentElement.tagName() == "formarray")
  4656. {
  4657. addFormArrayToLayout(currentElement, widgetStack, layoutStack);
  4658. }
  4659. else if(currentElement.tagName() =="hscale")
  4660. {
  4661. addScaleControlToLayout(currentElement, widgetStack,
  4662. layoutStack);
  4663. }
  4664. else if(currentElement.tagName() == "vscale")
  4665. {
  4666. addIntensityControlToLayout(currentElement, widgetStack,
  4667. layoutStack);
  4668. }
  4669. else if(currentElement.tagName() == "webview")
  4670. {
  4671. addWebViewToLayout(currentElement, widgetStack, layoutStack);
  4672. }
  4673. else if(currentElement.tagName() == "stretch")
  4674. {
  4675. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4676. layout->addStretch();
  4677. }
  4678. @<Additional box layout elements@>@;
  4679. }
  4680. }
  4681. }
  4682. @ Box layouts support adding additional layouts to the layout. The form of the
  4683. function is very similar to |addLayoutToWidget()|.
  4684. @<Functions for scripting@>=
  4685. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4686. QStack<QLayout *> *layoutStack)
  4687. {
  4688. QLayout *targetLayout = layoutStack->pop();
  4689. QBoxLayout *boxLayout = qobject_cast<QBoxLayout *>(targetLayout);
  4690. if(element.hasAttribute("type"))
  4691. {
  4692. @<Create and populate layout@>@;
  4693. boxLayout->addLayout(layout);
  4694. layoutStack->pop();
  4695. }
  4696. layoutStack->push(targetLayout);
  4697. }
  4698. @ A splitter is similar to a layout in that it manages the size and position of
  4699. one or more widgets, however it is not a layout and therefore needs to be
  4700. handled separately.
  4701. @<Functions for scripting@>=
  4702. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4703. QStack<QLayout *> *layoutStack)
  4704. {
  4705. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4706. QSplitter *splitter = new(QSplitter);
  4707. layout->addWidget(splitter);
  4708. @<Set up splitter@>@;
  4709. }
  4710. @ As there are multiple places where a splitter element must be examined, the
  4711. common code is set aside.
  4712. @<Set up splitter@>=
  4713. QString orientation = element.attribute("type");
  4714. if(orientation == "horizontal")
  4715. {
  4716. splitter->setOrientation(Qt::Horizontal);
  4717. }
  4718. else if(orientation == "vertical")
  4719. {
  4720. splitter->setOrientation(Qt::Vertical);
  4721. }
  4722. QString id = element.attribute("id");
  4723. if(!id.isEmpty())
  4724. {
  4725. splitter->setObjectName(id);
  4726. }
  4727. if(element.hasChildNodes())
  4728. {
  4729. widgetStack->push(splitter);
  4730. populateSplitter(element, widgetStack, layoutStack);
  4731. widgetStack->pop();
  4732. }
  4733. @ When populating a splitter, it is important to note that only widgets can be
  4734. added. If a layout is needed, this can be handled by adding a |QWidget| and
  4735. applying the layout to that widget.
  4736. @<Functions for scripting@>=
  4737. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4738. QStack<QLayout *> *layoutStack)
  4739. {
  4740. QDomNodeList children = element.childNodes();
  4741. for(int i = 0; i < children.count(); i++)
  4742. {
  4743. QDomNode current;
  4744. QDomElement currentElement;
  4745. current = children.at(i);
  4746. if(current.isElement())
  4747. {
  4748. currentElement = current.toElement();
  4749. currentElement.setAttribute("trcontext", "configuration");
  4750. if(currentElement.tagName() == "decoration")
  4751. {
  4752. addDecorationToSplitter(currentElement, widgetStack,
  4753. layoutStack);
  4754. }
  4755. else if(currentElement.tagName() == "graph")
  4756. {
  4757. addGraphToSplitter(currentElement, widgetStack, layoutStack);
  4758. }
  4759. else if(currentElement.tagName() == "splitter")
  4760. {
  4761. addSplitterToSplitter(currentElement, widgetStack, layoutStack);
  4762. }
  4763. else if(currentElement.tagName() == "lcdtemperature")
  4764. {
  4765. addTemperatureDisplayToSplitter(currentElement, widgetStack,
  4766. layoutStack);
  4767. }
  4768. else if(currentElement.tagName() == "lcdtimer")
  4769. {
  4770. addTimerDisplayToSplitter(currentElement, widgetStack,
  4771. layoutStack);
  4772. }
  4773. else if(currentElement.tagName() == "measurementtable")
  4774. {
  4775. addZoomLogToSplitter(currentElement, widgetStack, layoutStack);
  4776. }
  4777. else if(currentElement.tagName() == "widget")
  4778. {
  4779. addWidgetToSplitter(currentElement, widgetStack, layoutStack);
  4780. }
  4781. }
  4782. }
  4783. }
  4784. @ Adding a splitter to a splitter is similar to adding it to a layout.
  4785. @<Functions for scripting@>=
  4786. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4787. QStack<QLayout *> *layoutStack)
  4788. {
  4789. QSplitter *parent = qobject_cast<QSplitter *>(widgetStack->top());
  4790. QSplitter *splitter = new(QSplitter);
  4791. splitter->setParent(parent);
  4792. parent->addWidget(splitter);
  4793. @<Set up splitter@>@;
  4794. }
  4795. @ Temperature displays are useful to have in an application such as this. At
  4796. present, this code only supports the {\tt id} attribute. It may be useful in the
  4797. future to allow other attributes for changing default attributes of the
  4798. indicator rather than needing to pull the object from script code and set
  4799. changes there.
  4800. @<Functions for scripting@>=
  4801. void addTemperatureDisplayToSplitter(QDomElement element,@|
  4802. QStack<QWidget *> *widgetStack,
  4803. QStack<QLayout *> *)
  4804. {
  4805. TemperatureDisplay *display = new(TemperatureDisplay);
  4806. if(element.hasAttribute("id"))
  4807. {
  4808. display->setObjectName(element.attribute("id"));
  4809. }
  4810. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4811. splitter->addWidget(display);
  4812. }
  4813. void addTemperatureDisplayToLayout(QDomElement element,@|
  4814. QStack<QWidget *> *,
  4815. QStack<QLayout *> *layoutStack)
  4816. {
  4817. TemperatureDisplay *display = new(TemperatureDisplay);
  4818. if(element.hasAttribute("id"))
  4819. {
  4820. display->setObjectName(element.attribute("id"));
  4821. }
  4822. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4823. layout->addWidget(display);
  4824. }
  4825. @ Timer displays are similarly useful to have. The default format for a timer
  4826. display is {\tt hh:mm:ss}, but this can be changed through the {\tt format}
  4827. attribute of an {\tt <lcdtimer>} element.
  4828. @<Functions for scripting@>=
  4829. void addTimerDisplayToSplitter(QDomElement element,@|
  4830. QStack<QWidget *> *widgetStack,
  4831. QStack<QLayout *> *)
  4832. {
  4833. TimerDisplay *display = new(TimerDisplay);
  4834. if(element.hasAttribute("id"))
  4835. {
  4836. display->setObjectName(element.attribute("id"));
  4837. }
  4838. if(element.hasAttribute("format"))
  4839. {
  4840. display->setDisplayFormat(element.attribute("format"));
  4841. }
  4842. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4843. splitter->addWidget(display);
  4844. }
  4845. void addTimerDisplayToLayout(QDomElement element,@|
  4846. QStack<QWidget *> *,
  4847. QStack<QLayout *> *layoutStack)
  4848. {
  4849. TimerDisplay *display = new(TimerDisplay);
  4850. if(element.hasAttribute("id"))
  4851. {
  4852. display->setObjectName(element.attribute("id"));
  4853. }
  4854. if(element.hasAttribute("format"))
  4855. {
  4856. display->setDisplayFormat(element.attribute("format"));
  4857. }
  4858. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4859. layout->addWidget(display);
  4860. }
  4861. @ When multiple timer or temperature displays are required, it can be useful to
  4862. provide a label to indicate just what is being measured.
  4863. @<Functions for scripting@>=
  4864. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *,@|
  4865. QStack<QLayout *> *layoutStack)
  4866. {
  4867. @<Set up decoration@>@;
  4868. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4869. layout->addWidget(decoration);
  4870. }
  4871. void addDecorationToSplitter(QDomElement element,
  4872. QStack<QWidget *> *widgetStack,
  4873. QStack<QLayout *> *)
  4874. {
  4875. @<Set up decoration@>@;
  4876. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4877. splitter->addWidget(decoration);
  4878. }
  4879. @ The decoration needs a label text, an orientation, and the widget to be
  4880. labeled.
  4881. @<Set up decoration@>=
  4882. QString labelText =
  4883. QCoreApplication::translate("configuration",
  4884. element.attribute("name").toUtf8().data());
  4885. Qt::Orientations@, orientation = Qt::Horizontal;
  4886. if(element.hasAttribute("type"))
  4887. {
  4888. if(element.attribute("type") == "horizontal")
  4889. {
  4890. orientation = Qt::Horizontal;
  4891. }
  4892. else if(element.attribute("type") == "vertical")
  4893. {
  4894. orientation = Qt::Vertical;
  4895. }
  4896. }
  4897. @<Find widget to decorate@>@;
  4898. WidgetDecorator *decoration = new WidgetDecorator(theWidget, labelText,
  4899. orientation);
  4900. if(element.hasAttribute("id"))
  4901. {
  4902. decoration->setObjectName(element.attribute("id"));
  4903. }
  4904. @ The widget to decorate should be found as a child of the {\tt <decoration>}
  4905. element.
  4906. @<Find widget to decorate@>=
  4907. QWidget *theWidget = NULL;
  4908. QDomNodeList children = element.childNodes();
  4909. for(int i = 0; i < children.count(); i++)
  4910. {
  4911. QDomNode item = children.at(i);
  4912. if(item.isElement())
  4913. {
  4914. QDomElement itemElement = item.toElement();
  4915. if(itemElement.tagName() == "lcdtemperature")
  4916. {
  4917. TemperatureDisplay *display = new TemperatureDisplay;
  4918. if(itemElement.hasAttribute("id"))
  4919. {
  4920. display->setObjectName(itemElement.attribute("id"));
  4921. }
  4922. theWidget = display;
  4923. }
  4924. else if(itemElement.tagName() == "lcdtimer")
  4925. {
  4926. TimerDisplay *display = new TimerDisplay;
  4927. if(itemElement.hasAttribute("id"))
  4928. {
  4929. display->setObjectName(itemElement.attribute("id"));
  4930. }
  4931. if(itemElement.hasAttribute("format"))
  4932. {
  4933. display->setDisplayFormat(itemElement.attribute("format"));
  4934. }
  4935. theWidget = display;
  4936. }
  4937. }
  4938. }
  4939. @ As splitters cannot contain layouts directly, there is a need to allow
  4940. otherwise empty widgets to be included in a splitter for cases where a splitter
  4941. should manage several widgets together as a group. A row of annotation buttons
  4942. is an example of such a layout.
  4943. When splitters are used as a way to hide optional features it sometimes has the
  4944. effect of forcing a window to stay larger than should be required. To fix this,
  4945. it is possible to set the \tt{ignoreSizePolicy} attribute to true. While this
  4946. does solve the window size issue, this technique is inconsistent with generally
  4947. expected behavior and its use should generally be discouraged.
  4948. @<Functions for scripting@>=
  4949. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4950. QStack<QLayout *> *layoutStack)
  4951. {
  4952. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4953. QWidget *widget = new QWidget;
  4954. if(element.hasAttribute("id"))
  4955. {
  4956. widget->setObjectName(element.attribute("id"));
  4957. }
  4958. if(element.hasAttribute("ignoreSizePolicy"))
  4959. {
  4960. if(element.attribute("ignoreSizePolicy") == "true")
  4961. {
  4962. widget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
  4963. }
  4964. }
  4965. splitter->addWidget(widget);
  4966. if(element.hasChildNodes())
  4967. {
  4968. widgetStack->push(widget);
  4969. populateWidget(element, widgetStack, layoutStack);
  4970. widgetStack->pop();
  4971. }
  4972. }
  4973. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4974. QStack<QLayout *> *layoutStack)
  4975. {
  4976. QDomNodeList children = element.childNodes();
  4977. for(int i = 0; i < children.count(); i++)
  4978. {
  4979. QDomNode current;
  4980. QDomElement currentElement;
  4981. current = children.at(i);
  4982. if(current.isElement())
  4983. {
  4984. currentElement = current.toElement();
  4985. if(currentElement.tagName() == "layout")
  4986. {
  4987. currentElement.setAttribute("trcontext", "configuration");
  4988. addLayoutToWidget(currentElement, widgetStack, layoutStack);
  4989. }
  4990. }
  4991. }
  4992. }
  4993. @ There are two types of buttons that can be added to a layout. There are normal
  4994. push buttons and there are annotation buttons. Other button types may be added
  4995. in the future.
  4996. @<Functions for scripting@>=
  4997. void addButtonToLayout(QDomElement element, QStack<QWidget *> *,@|
  4998. QStack<QLayout *> *layoutStack)
  4999. {
  5000. QAbstractButton *button = NULL;
  5001. QString text =
  5002. QCoreApplication::translate("configuration",
  5003. element.attribute("name").toUtf8().data());
  5004. if(element.hasAttribute("type"))
  5005. {
  5006. QString type = element.attribute("type");
  5007. if(type == "annotation")
  5008. {
  5009. AnnotationButton *abutton = new AnnotationButton(text);
  5010. if(element.hasAttribute("annotation"))
  5011. {
  5012. abutton->setAnnotation(element.attribute("annotation"));
  5013. }
  5014. if(element.hasAttribute("series"))
  5015. {
  5016. abutton->setTemperatureColumn(element.attribute("series").
  5017. toInt());
  5018. }
  5019. if(element.hasAttribute("column"))
  5020. {
  5021. abutton->setAnnotationColumn(element.attribute("column").
  5022. toInt());
  5023. }
  5024. button = abutton;
  5025. }
  5026. else if(type == "check")
  5027. {
  5028. button = new QCheckBox(text);
  5029. }
  5030. else if(type == "push")
  5031. {
  5032. button = new QPushButton(text);
  5033. }
  5034. }
  5035. if(element.hasAttribute("id"))
  5036. {
  5037. button->setObjectName(element.attribute("id"));
  5038. }
  5039. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5040. layout->addWidget(button);
  5041. }
  5042. @ While annotation buttons are useful for many batch notes, a spin box is
  5043. sometimes a better input choice. There are several attributes that can be set on
  5044. a spin box. These include text to be included in the annotation before and after
  5045. the value of the spin box, the temperature and annotation columns, the range of
  5046. values available in the spin box, the precision of allowed values, and the
  5047. amount by which increment and decrement operations change the value.
  5048. @<Functions for scripting@>=
  5049. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *,@|
  5050. QStack<QLayout *> *layoutStack)
  5051. {
  5052. AnnotationSpinBox *box = new AnnotationSpinBox("", "", NULL);
  5053. if(element.hasAttribute("pretext"))
  5054. {
  5055. box->setPretext(QCoreApplication::translate(
  5056. "configuration",
  5057. element.attribute("pretext").toUtf8().data()));
  5058. }
  5059. if(element.hasAttribute("posttext"))
  5060. {
  5061. box->setPosttext(QCoreApplication::translate(
  5062. "configuration",
  5063. element.attribute("posttext").toUtf8().data()));
  5064. }
  5065. if(element.hasAttribute("series"))
  5066. {
  5067. box->setTemperatureColumn(element.attribute("series").toInt());
  5068. }
  5069. if(element.hasAttribute("column"))
  5070. {
  5071. box->setAnnotationColumn(element.attribute("column").toInt());
  5072. }
  5073. if(element.hasAttribute("min"))
  5074. {
  5075. box->setMinimum(element.attribute("min").toDouble());
  5076. }
  5077. if(element.hasAttribute("max"))
  5078. {
  5079. box->setMaximum(element.attribute("max").toDouble());
  5080. }
  5081. if(element.hasAttribute("decimals"))
  5082. {
  5083. box->setDecimals(element.attribute("decimals").toInt());
  5084. }
  5085. if(element.hasAttribute("step"))
  5086. {
  5087. box->setSingleStep(element.attribute("step").toDouble());
  5088. }
  5089. if(element.hasAttribute("id"))
  5090. {
  5091. box->setObjectName(element.attribute("id"));
  5092. }
  5093. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5094. layout->addWidget(box);
  5095. }
  5096. @ Previously, in order to change a |ZoomLog| from the default set of columns,
  5097. script code would need to alter the column set. While this works fine on a Mac,
  5098. this did not work very well under Windows. For the current version, I would like
  5099. to remove the need to deal with table columns from the host environment. The
  5100. first step for this is allowing column descriptions in XML. After this, I'@q'@>d like
  5101. to remove the default column set from the widget code and provide some better
  5102. functionality for dealing with additional data sets.
  5103. When creating the |ZoomLog| here, we check for {\tt <column>} child elements
  5104. which specify the names of the columns.
  5105. @<Functions for scripting@>=
  5106. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  5107. QStack<QLayout *> *)
  5108. {
  5109. ZoomLog *widget = new ZoomLog;
  5110. if(element.hasAttribute("id"))
  5111. {
  5112. widget->setObjectName(element.attribute("id"));
  5113. }
  5114. if(element.hasChildNodes())
  5115. {
  5116. QDomNodeList children = element.childNodes();
  5117. int column = 0;
  5118. for(int i = 0; i < children.count(); i++)
  5119. {
  5120. QDomNode current;
  5121. QDomElement currentElement;
  5122. current = children.at(i);
  5123. if(current.isElement())
  5124. {
  5125. currentElement = current.toElement();
  5126. if(currentElement.tagName() == "column")
  5127. {
  5128. QString text =
  5129. QCoreApplication::translate(
  5130. "configuration",
  5131. currentElement.text().toUtf8().data());
  5132. widget->setHeaderData(column, text);
  5133. column++;
  5134. }
  5135. }
  5136. }
  5137. }
  5138. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  5139. if(splitter)
  5140. {
  5141. splitter->addWidget(widget);
  5142. }
  5143. else
  5144. {
  5145. qDebug() << "Splitter not found at top of widget stack!";
  5146. }
  5147. }
  5148. @ The last of the widgets needed to duplicate the window provided in previous
  5149. versions of \pn{} is the |GraphView|.
  5150. @<Functions for scripting@>=
  5151. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  5152. QStack<QLayout *> *)
  5153. {
  5154. GraphView *view = new GraphView;
  5155. if(element.hasAttribute("id"))
  5156. {
  5157. view->setObjectName(element.attribute("id"));
  5158. }
  5159. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  5160. splitter->addWidget(view);
  5161. }
  5162. @ When interacting with a database, it can be useful to provide a combo box
  5163. populated by the results of a database query. One way to do this is through a
  5164. |SqlComboBox| widget.
  5165. @<Functions for scripting@>=
  5166. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *,@|
  5167. QStack<QLayout *> *layoutStack)
  5168. {
  5169. SqlComboBox *box = new SqlComboBox();
  5170. if(element.hasAttribute("data"))
  5171. {
  5172. box->setDataColumn(element.attribute("data").toInt());
  5173. }
  5174. if(element.hasAttribute("display"))
  5175. {
  5176. box->setDisplayColumn(element.attribute("display").toInt());
  5177. }
  5178. if(element.hasAttribute("showdata"))
  5179. {
  5180. if(element.attribute("showdata") == "true")
  5181. {
  5182. box->showData(true);
  5183. }
  5184. }
  5185. if(element.hasAttribute("editable"))
  5186. {
  5187. if(element.attribute("editable") == "true")
  5188. {
  5189. box->setEditable(true);
  5190. }
  5191. }
  5192. if(element.hasChildNodes())
  5193. {
  5194. QDomNodeList children = element.childNodes();
  5195. for(int i = 0; i < children.count(); i++)
  5196. {
  5197. QDomNode current;
  5198. QDomElement currentElement;
  5199. current = children.at(i);
  5200. if(current.isElement())
  5201. {
  5202. currentElement = current.toElement();
  5203. if(currentElement.tagName() == "null")
  5204. {
  5205. box->addNullOption();
  5206. }
  5207. else if(currentElement.tagName() == "query")
  5208. {
  5209. box->addSqlOptions(currentElement.text());
  5210. }
  5211. }
  5212. }
  5213. }
  5214. if(element.hasAttribute("id"))
  5215. {
  5216. box->setObjectName(element.attribute("id"));
  5217. }
  5218. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5219. layout->addWidget(box);
  5220. }
  5221. @ The next database aware widget that can be useful to have in \pn{} is a
  5222. {\bf S}QL {\bf A}rray {\bf L}iteral {\bf T}able. As might be apparent from the
  5223. name, this is a table view with an associated model and delegates appropriate
  5224. for creating ordered arrays to pass into a database. Each column represents an
  5225. array of values. The most common use of this is in cases where it is important
  5226. to produce multiple arrays of the same size in which each element of one array
  5227. is related to the element in the same position of another array. For example,
  5228. when roasting coffee there are times when some may want to add more than one
  5229. coffee to the roaster at a time. In order to correctly track the green coffee
  5230. inventory and so that the roasting log may have an accurate record of what is
  5231. really happening, insertions on the roasting log provide two arrays, one
  5232. representing all of the coffees being added to the roaster, the other the amount
  5233. of each of these coffees. The database can then use a trigger function to
  5234. examine these arrays and produce the necessary entries in the use table which in
  5235. turn update the record containing the amount of each green coffee currently in
  5236. stock.
  5237. While a generic |QTableView| is used here, there is a need to add functionality
  5238. specific to using this table with a |SaltModel| when obtaining this widget from
  5239. the host environment. In order to accomodate this, we add a dynamic property to
  5240. the view to identify the type of table in the absense of a unique class name.
  5241. @<Functions for scripting@>=
  5242. void addSaltToLayout(QDomElement element, QStack<QWidget *> *,@|
  5243. QStack<QLayout *> *layoutStack)
  5244. {
  5245. QTableView *view = new QTableView;
  5246. view->setProperty("tabletype", QVariant(QString("SaltTable")));
  5247. SaltModel *model = new SaltModel(element.childNodes().count());
  5248. if(element.hasAttribute("id"))
  5249. {
  5250. view->setObjectName(element.attribute("id"));
  5251. }
  5252. if(element.hasChildNodes())
  5253. {
  5254. QDomNodeList children = element.childNodes();
  5255. int currentColumn = 0;
  5256. for(int i = 0; i < children.count(); i++)
  5257. {
  5258. QDomNode current;
  5259. QDomElement currentElement;
  5260. current = children.at(i);
  5261. if(current.isElement())
  5262. {
  5263. currentElement = current.toElement();
  5264. if(currentElement.tagName() == "column")
  5265. {
  5266. if(currentElement.hasAttribute("name"))
  5267. {
  5268. model->setHeaderData(currentColumn,
  5269. Qt::Horizontal,
  5270. QCoreApplication::translate(
  5271. "configuration",
  5272. currentElement.attribute("name").toUtf8().data()));
  5273. }
  5274. if(currentElement.hasAttribute("delegate"))
  5275. {
  5276. @<Set column delegate from XML attribute@>@;
  5277. }
  5278. currentColumn++;
  5279. }
  5280. }
  5281. }
  5282. }
  5283. view->setModel(model);
  5284. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5285. layout->addWidget(view);
  5286. }
  5287. @ It is often desirable to restrict the allowed values in an entry to either a
  5288. set of specific values or to a particular type of value. Delegates can be set
  5289. on a column to enforce such restrictions.
  5290. @<Set column delegate from XML attribute@>=
  5291. if(currentElement.attribute("delegate") == "sql")
  5292. {
  5293. @<Assign column delegate from SQL@>@;
  5294. }
  5295. else if(currentElement.attribute("delegate") == "numeric")
  5296. {
  5297. @<Assign numeric column delegate@>@;
  5298. }
  5299. @ When using a |SaltModel|, there are times where the array values being
  5300. inserted are identification numbers representing some record that already exists
  5301. in the database. For example, the id number representing a green coffee in the
  5302. table of items. In such a case, it is beneficial to provide a delegate capable
  5303. of presenting a human readable list of choices.
  5304. @<Assign column delegate from SQL@>=
  5305. SqlComboBoxDelegate *delegate = new SqlComboBoxDelegate;
  5306. SqlComboBox *widget = new SqlComboBox();
  5307. if(currentElement.hasAttribute("nulltext"))
  5308. {
  5309. widget->setNullText(currentElement.attribute("nulltext"));
  5310. }
  5311. if(currentElement.hasAttribute("nulldata"))
  5312. {
  5313. widget->setNullData(QVariant(currentElement.attribute("nulldata")));
  5314. }
  5315. if(currentElement.hasAttribute("null"))
  5316. {
  5317. if(currentElement.attribute("null") == "true")
  5318. {
  5319. widget->addNullOption();
  5320. }
  5321. }
  5322. if(currentElement.hasAttribute("showdata"))
  5323. {
  5324. if(currentElement.attribute("showdata") == "true")
  5325. {
  5326. widget->showData(true);
  5327. }
  5328. }
  5329. if(currentElement.hasAttribute("data"))
  5330. {
  5331. widget->setDataColumn(currentElement.attribute("data").toInt());
  5332. }
  5333. if(currentElement.hasAttribute("display"))
  5334. {
  5335. widget->setDisplayColumn(currentElement.attribute("display").toInt());
  5336. }
  5337. widget->addSqlOptions(currentElement.text());
  5338. delegate->setWidget(widget);
  5339. view->setItemDelegateForColumn(currentColumn, delegate);
  5340. @ Another common use is allowing numeric values. At present this only
  5341. restricts input to numbers, however it may be useful to provide other options
  5342. such as restricting the range of allowed values in the future.
  5343. @<Assign numeric column delegate@>=
  5344. NumericDelegate *delegate = new NumericDelegate;
  5345. view->setItemDelegateForColumn(currentColumn, delegate);
  5346. @ The |NumericDelegate| will only set the display value to a number, but it
  5347. will perform mathematical calculations that are entered into the editor as
  5348. well. This allows a person to type something like $13.26+5.06$ with the result
  5349. of the expression ($18.32$) appearing in the table.
  5350. @<Class declarations@>=
  5351. class NumericDelegate : public QItemDelegate@/
  5352. {
  5353. @[Q_OBJECT@]@;
  5354. public:@/
  5355. NumericDelegate(QObject *parent = NULL);
  5356. QWidget *createEditor(QWidget *parent,
  5357. const QStyleOptionViewItem &option,@|
  5358. const QModelIndex &index) const;
  5359. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  5360. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  5361. const QModelIndex &index) const;
  5362. void updateEditorGeometry(QWidget *editor,
  5363. const QStyleOptionViewItem &option,@|
  5364. const QModelIndex &index) const;
  5365. };
  5366. @ There is nothing special about the constructor.
  5367. @<NumericDelegate implementation@>=
  5368. NumericDelegate::NumericDelegate(QObject *parent) :
  5369. QItemDelegate(parent)
  5370. {
  5371. /* Nothing needs to be done here. */
  5372. }
  5373. @ Two roles are used by this delegate. The edit role should contain whatever
  5374. text has been entered in the editor while the display role contain the numeric
  5375. result of any expression that has been entered. Our editor only requires the
  5376. first of these.
  5377. @<NumericDelegate implementation@>=
  5378. void NumericDelegate::setEditorData(QWidget *editor,
  5379. const QModelIndex &index) const
  5380. {
  5381. QString value = index.model()->data(index, Qt::EditRole).toString();
  5382. QLineEdit *line = static_cast<QLineEdit*>(editor);
  5383. line->setText(value);
  5384. }
  5385. @ When editing is finished, the expression text must be saved back to the
  5386. model and the expression should be evaluated to set the display role. We make
  5387. use of the existing scripting engine to evaluate the expression, but only
  5388. preserve the result in the display role if the result of that expression is
  5389. numeric.
  5390. @<NumericDelegate implementation@>=
  5391. void NumericDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
  5392. const QModelIndex &index) const
  5393. {
  5394. QLineEdit *line = static_cast<QLineEdit*>(editor);
  5395. model->setData(index, line->text(), Qt::EditRole);
  5396. QScriptEngine *engine = AppInstance->engine;
  5397. engine->pushContext();
  5398. QString script = QString("Number(%1)").arg(line->text());
  5399. QScriptValue result = engine->evaluate(line->text());
  5400. if(result.isNumber())
  5401. {
  5402. model->setData(index, result.toVariant(), Qt::DisplayRole);
  5403. }
  5404. else
  5405. {
  5406. model->setData(index, QVariant(), Qt::DisplayRole);
  5407. }
  5408. engine->popContext();
  5409. }
  5410. @ There is nothing special about the line edit used for this.
  5411. @<NumericDelegate implementation@>=
  5412. QWidget* NumericDelegate::createEditor(QWidget *parent,
  5413. const QStyleOptionViewItem &,
  5414. const QModelIndex &) const
  5415. {
  5416. return (new QLineEdit(parent));
  5417. }
  5418. @ To ensure that the editor is displayed appropriately, we must pass the
  5419. geometry data to our editor.
  5420. @<NumericDelegate implementation@>=
  5421. void NumericDelegate::updateEditorGeometry(QWidget *editor,
  5422. const QStyleOptionViewItem &option,
  5423. const QModelIndex &) const
  5424. {
  5425. editor->setGeometry(option.rect);
  5426. }
  5427. @ The same general technique is useful for input to a |QLineEdit|, but there is
  5428. no model backing that widget to preserve multiple data roles. One way to get
  5429. this functionality without too much effort is to abuse |QValidator| to evaluate
  5430. expressions.
  5431. @<Class declarations@>=
  5432. class ScriptValidator : public QValidator
  5433. {
  5434. Q_OBJECT
  5435. public:
  5436. ScriptValidator(QValidator *validator, QObject *parent = NULL);
  5437. void fixup(QString &input) const;
  5438. QValidator::State validate(QString &input, int &pos) const;
  5439. private:
  5440. QValidator *v;
  5441. };
  5442. @ The key to this is in the |fixup()| method. Here we over-write input with the
  5443. result of the script evaluation.
  5444. @<ScriptValidator implementation@>=
  5445. void ScriptValidator::fixup(QString &input) const
  5446. {
  5447. QScriptEngine *engine = AppInstance->engine;
  5448. engine->pushContext();
  5449. input = engine->evaluate(input).toString();
  5450. engine->popContext();
  5451. }
  5452. @ This validator is intended to be used in conjunction with another one which
  5453. determines if the result of the expression is acceptable. In this case
  5454. |Invalid| is never returned.
  5455. @<ScriptValidator implementation@>=
  5456. QValidator::State ScriptValidator::validate(QString &input, int &pos) const
  5457. {
  5458. if(v)
  5459. {
  5460. if(v->validate(input, pos) == QValidator::Acceptable)
  5461. {
  5462. return QValidator::Acceptable;
  5463. }
  5464. }
  5465. return QValidator::Intermediate;
  5466. }
  5467. @ The constructor is trivial.
  5468. @<ScriptValidator implementation@>=
  5469. ScriptValidator::ScriptValidator(QValidator *validator, QObject *parent)
  5470. : QValidator(parent), v(validator)
  5471. {
  5472. /* Nothing needs to be done here. */
  5473. }
  5474. @ This is included in typica.cpp.
  5475. @<Class implementations@>=
  5476. @<ScriptValidator implementation@>
  5477. @ Line edits are useful when the user is expected to enter text without a
  5478. predetermined set of values.
  5479. Several attributes are supported on line edits. In addition to the usual
  5480. {\tt id} attribute, there is also a {\tt writable} attribute which, if
  5481. {\tt false}, can be used to create read only text areas which can only be edited
  5482. from script code. A {\tt validator} attribute allows entered text to be
  5483. restricted. This can take one of three values. If the value is {\tt "numeric"},
  5484. input is restricted to numeric values. If the value is {\tt "integer"}, input is
  5485. restricted to integer values. Finally, if the value is {\tt "expression"}, input
  5486. is restricted to text which matches a regular expression specified as the value
  5487. of the {\tt expression} attribute.
  5488. Note that when integer and numeric validators are specified, these are set for
  5489. a |ScriptValidator| to enable some basic expression evaluation.
  5490. @<Functions for scripting@>=
  5491. void addLineToLayout(QDomElement element, QStack<QWidget *> *,@|
  5492. QStack<QLayout *> *layoutStack)
  5493. {
  5494. QLineEdit *widget = new QLineEdit(element.text());
  5495. if(element.hasAttribute("id"))
  5496. {
  5497. widget->setObjectName(element.attribute("id"));
  5498. }
  5499. if(element.hasAttribute("writable"))
  5500. {
  5501. if(element.attribute("writable") == "false")
  5502. {
  5503. widget->setReadOnly(true);
  5504. }
  5505. }
  5506. if(element.hasAttribute("validator"))
  5507. {
  5508. if(element.attribute("validator") == "numeric")
  5509. {
  5510. widget->setValidator(new ScriptValidator(new QDoubleValidator));
  5511. }
  5512. else if(element.attribute("validator") == "integer")
  5513. {
  5514. widget->setValidator(new ScriptValidator(new QIntValidator));
  5515. }
  5516. else if(element.attribute("validator") == "expression" &&
  5517. element.hasAttribute("expression"))
  5518. {
  5519. widget->setValidator(new QRegExpValidator(
  5520. QRegExp(element.attribute("expression")),
  5521. NULL));
  5522. }
  5523. }
  5524. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5525. layout->addWidget(widget);
  5526. }
  5527. @ It is natural for certain database fields to enter potentially large amounts
  5528. of free form text, for example, notes and annotations.
  5529. @<Functions for scripting@>=
  5530. void addTextToLayout(QDomElement element, QStack<QWidget *> *,@|
  5531. QStack<QLayout *> *layoutStack)
  5532. {
  5533. QTextEdit *widget = new QTextEdit;
  5534. if(element.hasAttribute("id"))
  5535. {
  5536. widget->setObjectName(element.attribute("id"));
  5537. }
  5538. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5539. layout->addWidget(widget);
  5540. }
  5541. @ The common use of |SqlQueryView| calls for the possibility of changing the
  5542. query during use. As such, there is little reason to accept attributes other
  5543. than an id for obtaining the view in a script.
  5544. @<Functions for scripting@>=
  5545. void addSqlQueryViewToLayout(QDomElement element,
  5546. QStack<QWidget *> *,@|
  5547. QStack<QLayout *> *layoutStack)
  5548. {
  5549. SqlQueryView *view = new SqlQueryView;
  5550. if(element.hasAttribute("id"))
  5551. {
  5552. view->setObjectName(element.attribute("id"));
  5553. }
  5554. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5555. layout->addWidget(view);
  5556. }
  5557. @ When the user is expected to enter a date, it is appropriate to use a date
  5558. editor. This one provides a calendar.
  5559. @<Functions for scripting@>=
  5560. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *,@|
  5561. QStack<QLayout *> *layoutStack)
  5562. {
  5563. QWidget *widget;
  5564. if(element.hasAttribute("time"))
  5565. {
  5566. if(element.attribute("time") == "true")
  5567. {
  5568. QDateTimeEdit *edit = new QDateTimeEdit;
  5569. edit->setDateTime(QDateTime::currentDateTime());
  5570. edit->setCalendarPopup(true);
  5571. edit->setDisplayFormat("yyyy-MM-dd hh:mm:ss");
  5572. widget = qobject_cast<QWidget *>(edit);
  5573. }
  5574. else
  5575. {
  5576. QDateEdit *edit = new QDateEdit;
  5577. edit->setDate(QDate::currentDate());
  5578. edit->setCalendarPopup(true);
  5579. edit->setDisplayFormat("yyyy-MM-dd");
  5580. widget = qobject_cast<QWidget *>(edit);
  5581. }
  5582. }
  5583. else
  5584. {
  5585. QDateEdit *edit = new QDateEdit;
  5586. edit->setDate(QDate::currentDate());
  5587. edit->setCalendarPopup(true);
  5588. edit->setDisplayFormat("yyyy-MM-dd");
  5589. widget = qobject_cast<QWidget *>(edit);
  5590. }
  5591. if(element.hasAttribute("id"))
  5592. {
  5593. widget->setObjectName(element.attribute("id"));
  5594. }
  5595. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5596. layout->addWidget(widget);
  5597. }
  5598. @ Some additional properties are added to this object when it is retrieved by
  5599. the host environment.
  5600. @<Functions for scripting@>=
  5601. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine)
  5602. {
  5603. setQDateTimeEditProperties(value, engine);
  5604. }
  5605. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine)
  5606. {
  5607. setQAbstractSpinBoxProperties(value, engine);
  5608. value.setProperty("setDate", engine->newFunction(QDateTimeEdit_setDate));
  5609. value.setProperty("day", engine->newFunction(QDateTimeEdit_day));
  5610. value.setProperty("month", engine->newFunction(QDateTimeEdit_month));
  5611. value.setProperty("year", engine->newFunction(QDateTimeEdit_year));
  5612. value.setProperty("setToCurrentTime",
  5613. engine->newFunction(QDateTimeEdit_setToCurrentTime));
  5614. }
  5615. @ Certain operations on a |QDateEdit| are easier with a few convenience
  5616. properties that bypass the need to use the built in |date| property. For
  5617. example, an editor that should be set to 1 January of the current year can
  5618. obtain the year and set the date without directly using a |QDate| object.
  5619. @<Functions for scripting@>=
  5620. QScriptValue QDateTimeEdit_setDate(QScriptContext *context, QScriptEngine *)
  5621. {
  5622. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5623. if(context->argumentCount() == 3)
  5624. {
  5625. self->setDate(QDate(argument<int>(0, context),
  5626. argument<int>(1, context),
  5627. argument<int>(2, context)));
  5628. }
  5629. else
  5630. {
  5631. context->throwError("Incorrect number of arguments passed to "
  5632. "QDateTimeEdit::setDate(). This method takes three integer arguments "
  5633. "specifying the year, month, and day.");
  5634. }
  5635. return QScriptValue();
  5636. }
  5637. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *)
  5638. {
  5639. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5640. return QScriptValue(self->date().day());
  5641. }
  5642. QScriptValue QDateTimeEdit_month(QScriptContext *context, QScriptEngine *)
  5643. {
  5644. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5645. return QScriptValue(self->date().month());
  5646. }
  5647. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *)
  5648. {
  5649. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5650. return QScriptValue(self->date().year());
  5651. }
  5652. QScriptValue QDateTimeEdit_setToCurrentTime(QScriptContext *context, QScriptEngine *)
  5653. {
  5654. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5655. self->setDateTime(QDateTime::currentDateTime());
  5656. return QScriptValue();
  5657. }
  5658. @ A few function prototypes are needed for this.
  5659. @<Function prototypes for scripting@>=
  5660. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine);
  5661. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine);
  5662. QScriptValue QDateTimeEdit_setDate(QScriptContext *context,
  5663. QScriptEngine *engine);
  5664. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *engine);
  5665. QScriptValue QDateTimeEdit_month(QScriptContext *context,
  5666. QScriptEngine *engine);
  5667. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *engine);
  5668. QScriptValue QDateTimeEdit_setToCurrentTime(QScriptContext *context, QScriptEngine *engine);
  5669. @ Sometimes it can be useful to allow editing a time or duration value without
  5670. a date field. For this, a |QTimeEdit| can be used.
  5671. @<Functions for scripting@>=
  5672. void addTimeEditToLayout(QDomElement element, QStack<QWidget *> *,@|
  5673. QStack<QLayout *> *layoutStack)
  5674. {
  5675. QTimeEdit *edit = new QTimeEdit;
  5676. if(element.hasAttribute("displayFormat"))
  5677. {
  5678. edit->setDisplayFormat(element.attribute("displayFormat"));
  5679. }
  5680. else
  5681. {
  5682. edit->setDisplayFormat("mm:ss.zzz");
  5683. }
  5684. if(element.hasAttribute("id"))
  5685. {
  5686. edit->setObjectName(element.attribute("id"));
  5687. }
  5688. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5689. layout->addWidget(edit);
  5690. }
  5691. @ Additional properties are added as a |QTimeEdit| is a |QDateTimeEdit|.
  5692. @<Functions for scripting@>=
  5693. void setQTimeEditProperties(QScriptValue value, QScriptEngine *engine)
  5694. {
  5695. setQDateTimeEditProperties(value, engine);
  5696. }
  5697. @ A function prototype is needed.
  5698. @<Function prototypes for scripting@>=
  5699. void setQTimeEditProperties(QScriptValue value, QScriptEngine *engine);
  5700. @ In order to get to objects created from the XML description, it is necessary
  5701. to provide a function that can be called to retrieve children of a given widget.
  5702. When providing such an object to the script, it is necessary to determine the
  5703. type of that object and add the appropriate properties.
  5704. @<Function prototypes for scripting@>=
  5705. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine);
  5706. @ This function must be made available to the scripting engine.
  5707. @<Set up the scripting engine@>=
  5708. engine->globalObject().setProperty("findChildObject",
  5709. engine->newFunction(findChildObject));
  5710. @ This function takes a script value representing some object which may have
  5711. been created from an XML description and a string containing the name of the
  5712. requested child element.
  5713. @<Functions for scripting@>=
  5714. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine)
  5715. {
  5716. QObject *parent = argument<QObject *>(0, context);
  5717. QString name = argument<QString>(1, context);
  5718. QObject *object = parent->findChild<QObject *>(name);
  5719. QScriptValue value;
  5720. if(object)
  5721. {
  5722. value = engine->newQObject(object);
  5723. QString className = object->metaObject()->className();
  5724. @<Set object properties based on class name@>@;
  5725. }
  5726. return value;
  5727. }
  5728. @ Properties are added for a large number of class types.
  5729. @<Set object properties based on class name@>=
  5730. if(className == "TemperatureDisplay")
  5731. {
  5732. setTemperatureDisplayProperties(value, engine);
  5733. }
  5734. else if(className == "TimerDisplay")
  5735. {
  5736. setTimerDisplayProperties(value, engine);
  5737. }
  5738. else if(className == "QAction")
  5739. {
  5740. setQActionProperties(value, engine);
  5741. }
  5742. else if(className == "QBoxLayout")
  5743. {
  5744. setQBoxLayoutProperties(value, engine);
  5745. }
  5746. else if(className == "QDateEdit")
  5747. {
  5748. setQDateEditProperties(value, engine);
  5749. }
  5750. else if(className == "QDateTimeEdit")
  5751. {
  5752. setQDateTimeEditProperties(value, engine);
  5753. }
  5754. else if(className == "QFrame")
  5755. {
  5756. setQFrameProperties(value, engine);
  5757. }
  5758. else if(className == "QHBoxLayout")
  5759. {
  5760. setQBoxLayoutProperties(value, engine);
  5761. }
  5762. else if(className == "QLCDNumber")
  5763. {
  5764. setQLCDNumberProperties(value, engine);
  5765. }
  5766. else if(className == "QMenu")
  5767. {
  5768. setQMenuProperties(value, engine);
  5769. }
  5770. else if(className == "QMenuBar")
  5771. {
  5772. setQMenuBarProperties(value, engine);
  5773. }
  5774. else if(className == "QPushButton")
  5775. {
  5776. setQPushButtonProperties(value, engine);
  5777. }
  5778. else if(className == "QSplitter")
  5779. {
  5780. setQSplitterProperties(value, engine);
  5781. }
  5782. else if(className == "QTableView")
  5783. {
  5784. if(object->property("tabletype").isValid())
  5785. {
  5786. if(object->property("tabletype").toString() == "SaltTable")
  5787. {
  5788. setSaltTableProperties(value, engine);
  5789. }
  5790. }
  5791. }
  5792. else if(className == "QVBoxLayout")
  5793. {
  5794. setQBoxLayoutProperties(value, engine);
  5795. }
  5796. else if(className == "QWidget")
  5797. {
  5798. setQWidgetProperties(value, engine);
  5799. }
  5800. else if(className == "ScriptQMainWindow")
  5801. {
  5802. setQMainWindowProperties(value, engine);
  5803. }
  5804. else if(className == "SqlComboBox")
  5805. {
  5806. setSqlComboBoxProperties(value, engine);
  5807. }
  5808. else if(className == "SqlQueryView")
  5809. {
  5810. setSqlQueryViewProperties(value, engine);
  5811. }
  5812. else if(className == "ZoomLog")
  5813. {
  5814. setZoomLogProperties(value, engine);
  5815. }
  5816. else if(className == "QTextEdit")
  5817. {
  5818. setQTextEditProperties(value, engine);
  5819. }
  5820. else if(className == "QWebView")
  5821. {
  5822. setQWebViewProperties(value, engine);
  5823. }
  5824. else if(className == "QLineEdit")
  5825. {
  5826. setQLineEditProperties(value, engine);
  5827. }
  5828. else if(className == "QSvgWidget")
  5829. {
  5830. setQSvgWidgetProperties(value, engine);
  5831. }
  5832. else if(className == "QTabBar")
  5833. {
  5834. setQTabBarProperties(value, engine);
  5835. }
  5836. else if(className == "PrinterSelector")
  5837. {
  5838. setQComboBoxProperties(value, engine);
  5839. }
  5840. @ In the list of classes, the SaltTable entry is for a class which does not
  5841. strictly exist on its own. It is, however, useful to provide some custom
  5842. properties when passing such an object to the host environment.
  5843. @<Function prototypes for scripting@>=
  5844. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine);
  5845. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  5846. QScriptEngine *engine);
  5847. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  5848. QScriptEngine *engine);
  5849. QScriptValue SaltTable_columnSum(QScriptContext *context,
  5850. QScriptEngine *engine);
  5851. QScriptValue SaltTable_columnArray(QScriptContext *context,
  5852. QScriptEngine *engine);
  5853. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine);
  5854. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine);
  5855. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  5856. QScriptEngine *engine);
  5857. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *engine);
  5858. QScriptValue SaltTable_clear(QScriptContext *context, QScriptEngine *engine);
  5859. QScriptValue SaltTable_removeRow(QScriptContext *context, QScriptEngine *engine);
  5860. QScriptValue SaltTable_findData(QScriptContext *context, QScriptEngine *engine);
  5861. @ There are times when it is useful to obtain the sum of values in a column of
  5862. a SaltTable object. For example, when a column represents the weight of the
  5863. green coffee used in a batch, a sum of that column provides the total weight of
  5864. the batch which, when presented to the user, can be used to catch errors in
  5865. measuring batches or entering data.
  5866. @<Functions for scripting@>=
  5867. QScriptValue SaltTable_columnSum(QScriptContext *context, QScriptEngine *engine)
  5868. {
  5869. QTableView *self = getself<QTableView *>(context);
  5870. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5871. QString datum;
  5872. double total = 0.0;
  5873. int column = argument<int>(0, context);
  5874. int role = argument<int>(1, context);
  5875. for(int i = 0; i < model->rowCount(); i++)
  5876. {
  5877. datum = model->data(model->index(i, column), role).toString();
  5878. if(!datum.isEmpty())
  5879. {
  5880. total += datum.toDouble();
  5881. }
  5882. }
  5883. return QScriptValue(engine, total);
  5884. }
  5885. @ Another common use of the SaltTable is producing the text for an array literal
  5886. to pass into a SQL query. The |SaltModel| used by this table makes this simple.
  5887. There are four functions for this functionality for different use cases.
  5888. @<Functions for scripting@>=
  5889. QScriptValue SaltTable_columnArray(QScriptContext *context,
  5890. QScriptEngine *engine)
  5891. {
  5892. QTableView *self = getself<QTableView *>(context);
  5893. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5894. int column = argument<int>(0, context);
  5895. int role = argument<int>(1, context);
  5896. QString literal = model->arrayLiteral(column, role);
  5897. return QScriptValue(engine, literal);
  5898. }
  5899. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  5900. QScriptEngine *engine)
  5901. {
  5902. QTableView *self = getself<QTableView *>(context);
  5903. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5904. int column = argument<int>(0, context);
  5905. int role = argument<int>(1, context);
  5906. QString literal = model->quotedArrayLiteral(column, role);
  5907. return QScriptValue(engine, literal);
  5908. }
  5909. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  5910. QScriptEngine *engine)
  5911. {
  5912. QTableView *self = getself<QTableView *>(context);
  5913. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5914. int column = argument<int>(0, context);
  5915. int role = argument<int>(1, context);
  5916. QString literal = model->arrayLiteral(column, role);
  5917. literal.chop(1);
  5918. literal = literal.remove(0, 1);
  5919. return QScriptValue(engine, literal);
  5920. }
  5921. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  5922. QScriptEngine *engine)
  5923. {
  5924. QTableView *self = getself<QTableView *>(context);
  5925. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5926. int column = argument<int>(0, context);
  5927. int role = argument<int>(1, context);
  5928. QString literal = model->quotedArrayLiteral(column, role);
  5929. literal.chop(1);
  5930. literal = literal.remove(0, 1);
  5931. return QScriptValue(engine, literal);
  5932. }
  5933. @ In order to obtain signals related to changes in the model, we need a way to
  5934. get to the model from the host environment.
  5935. @<Functions for scripting@>=
  5936. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine)
  5937. {
  5938. QTableView *self = getself<QTableView *>(context);
  5939. QScriptValue value = engine->newQObject(self->model());
  5940. return value;
  5941. }
  5942. @ While this table was originally intended strictly for user input, there are a
  5943. few use cases in which it is useful to allow scripts to set the values in the
  5944. table. This can be done with |setData|. This method takes four arguments: the
  5945. row and column of the table being set, the value to set, and the role of the
  5946. data being set.
  5947. @<Functions for scripting@>=
  5948. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *)
  5949. {
  5950. QTableView *self = getself<QTableView *>(context);
  5951. int row = argument<int>(0, context);
  5952. int column = argument<int>(1, context);
  5953. QVariant value = argument<QVariant>(2, context);
  5954. int role = argument<int>(3, context);
  5955. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5956. QModelIndex cell = model->index(row, column);
  5957. model->setData(cell, value, role);
  5958. self->update(cell);
  5959. return QScriptValue();
  5960. }
  5961. @ It is sometimes useful to obtain the data from a single cell of the table.
  5962. This can be done with the |data()| property.
  5963. @<Functions for scripting@>=
  5964. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine)
  5965. {
  5966. QTableView *self = getself<QTableView *>(context);
  5967. int row = argument<int>(0, context);
  5968. int column = argument<int>(1, context);
  5969. int role = argument<int>(2, context);
  5970. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5971. QModelIndex cell = model->index(row, column);
  5972. QVariant value = model->data(cell, role);
  5973. QScriptValue retval = engine->newVariant(value);
  5974. retval.setProperty("value", QScriptValue(value.toString()));
  5975. return retval;
  5976. }
  5977. @ There are times when it is useful to clear the content of a table. This is
  5978. used, for example, in the green coffees table after changing the roasted coffee
  5979. item to eliminate excess rows in the case where the previously selected item
  5980. was a pre-roast blend.
  5981. @<Functions for scripting@>=
  5982. QScriptValue SaltTable_clear(QScriptContext *context, QScriptEngine *)
  5983. {
  5984. QTableView *self = getself<QTableView *>(context);
  5985. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5986. model->clear();
  5987. return QScriptValue();
  5988. }
  5989. @ It is sometimes useful to remove a row from a table. This is done in the new
  5990. batch window when the coffee for a row is set to a NULL item.
  5991. @<Functions for scripting@>=
  5992. QScriptValue SaltTable_removeRow(QScriptContext *context, QScriptEngine *engine)
  5993. {
  5994. QTableView *self = getself<QTableView *>(context);
  5995. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5996. int row = argument<int>(0, context);
  5997. return engine->newVariant(model->removeRow(row));
  5998. }
  5999. @ To remove the correct row, it is sometimes useful to query the table for
  6000. special values. This is done with the |findData()| method on the underlying
  6001. model.
  6002. @<Functions for scripting@>=
  6003. QScriptValue SaltTable_findData(QScriptContext *context, QScriptEngine *engine)
  6004. {
  6005. QTableView *self = getself<QTableView *>(context);
  6006. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  6007. QVariant value = argument<QVariant>(0, context);
  6008. int column = argument<int>(1, context);
  6009. return engine->newVariant(model->findData(value, column));
  6010. }
  6011. @ These functions need to be added as properties of the table when it is passed
  6012. to the host environment.
  6013. @<Functions for scripting@>=
  6014. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine)
  6015. {
  6016. setQWidgetProperties(value, engine);
  6017. value.setProperty("columnArray",
  6018. engine->newFunction(SaltTable_columnArray));
  6019. value.setProperty("quotedColumnArray",
  6020. engine->newFunction(SaltTable_quotedColumnArray));
  6021. value.setProperty("bindableColumnArray",
  6022. engine->newFunction(SaltTable_bindableColumnArray));
  6023. value.setProperty("bindableQuotedColumnArray",
  6024. engine->newFunction(SaltTable_bindableQuotedColumnArray));
  6025. value.setProperty("columnSum", engine->newFunction(SaltTable_columnSum));
  6026. value.setProperty("data", engine->newFunction(SaltTable_data));
  6027. value.setProperty("model", engine->newFunction(SaltTable_model));
  6028. value.setProperty("setData", engine->newFunction(SaltTable_setData));
  6029. value.setProperty("clear", engine->newFunction(SaltTable_clear));
  6030. value.setProperty("removeRow", engine->newFunction(SaltTable_removeRow));
  6031. value.setProperty("findData", engine->newFunction(SaltTable_findData));
  6032. }
  6033. @ The |SqlComboBox| is another class that is not constructed from scripts but is
  6034. useful to access from them. A property is added to obtain the current user data
  6035. from the widget.
  6036. @<Function prototypes for scripting@>=
  6037. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  6038. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  6039. QScriptValue QComboBox_currentData(QScriptContext *context,
  6040. QScriptEngine *engine);
  6041. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *engine);
  6042. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *engine);
  6043. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine);
  6044. QScriptValue QComboBox_findData(QScriptContext *context, QScriptEngine *engine);
  6045. @ These functions should seem familiar by now.
  6046. @<Functions for scripting@>=
  6047. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  6048. {
  6049. setQComboBoxProperties(value, engine);
  6050. }
  6051. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  6052. {
  6053. setQWidgetProperties(value, engine);
  6054. value.setProperty("currentData",
  6055. engine->newFunction(QComboBox_currentData));
  6056. value.setProperty("addItem", engine->newFunction(QComboBox_addItem));
  6057. value.setProperty("setModel", engine->newFunction(QComboBox_setModel));
  6058. value.setProperty("findText", engine->newFunction(QComboBox_findText));
  6059. value.setProperty("findData", engine->newFunction(QComboBox_findData));
  6060. }
  6061. QScriptValue QComboBox_currentData(QScriptContext *context,
  6062. QScriptEngine *engine)
  6063. {
  6064. QComboBox *self = getself<QComboBox *>(context);
  6065. return QScriptValue(engine,
  6066. self->itemData(self->currentIndex()).toString());
  6067. }
  6068. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *)
  6069. {
  6070. QComboBox *self = getself<QComboBox *>(context);
  6071. self->addItem(argument<QString>(0, context));
  6072. return QScriptValue();
  6073. }
  6074. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *)
  6075. {
  6076. QComboBox *self = getself<QComboBox *>(context);
  6077. self->setModel(argument<QAbstractItemModel *>(0, context));
  6078. return QScriptValue();
  6079. }
  6080. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine)
  6081. {
  6082. QComboBox *self = getself<QComboBox *>(context);
  6083. return QScriptValue(engine, self->findText(argument<QString>(0, context)));
  6084. }
  6085. QScriptValue QComboBox_findData(QScriptContext *context, QScriptEngine *engine)
  6086. {
  6087. QComboBox *self = getself<QComboBox *>(context);
  6088. return QScriptValue(engine, self->findData(argument<QVariant>(0, context)));
  6089. }
  6090. @i abouttypica.w
  6091. @** A representation of temperature measurements.
  6092. \noindent Most of the information in a roast log will be temperature
  6093. measurements. These measurements are made of two components: the measured
  6094. temperature and the time at which that measurement was taken.
  6095. Measurement times are represented as instances of |QTime|.
  6096. @i units.w
  6097. @ We will require the |units.h| header.
  6098. @<Header files to include@>=
  6099. #include "units.h"
  6100. @i measurement.w
  6101. @** The Main Measurement Pipeline.
  6102. \noindent Measurements are sent through \pn{} in a way similar to liquid moving
  6103. through a series of connected pipes. \pn{} is not something that you just dump
  6104. measurements on. It'@q'@>s not a big truck\nfnote{Senator Ted Stevens (R-Alaska) on
  6105. network neutrality, June 28, 2006\par
  6106. \hbox{\indent\pdfURL{http://media.publicknowledge.org/stevens-on-nn.mp3}%
  6107. {http://media.publicknowledge.org/stevens-on-nn.mp3}}}. In most cases the
  6108. connections between classes (represented by arrows in Figure \secno) are made
  6109. with Qt'@q'@>s signals and slots mechanism\nfnote{Qt 4.4.3: Signals and Slots\par
  6110. \hbox{\indent\pdfURL{http://doc.trolltech.com/4.4/signalsandslots.html}%
  6111. {http://doc.trolltech.com/4.4/signalsandslots.html}}}, but
  6112. these
  6113. connections can
  6114. also be made through direct function calls as is the case with the connection
  6115. between |ZoomLog| and |MeasurementModel|.
  6116. \medskip
  6117. \includegraphics{pipes}
  6118. \smallskip
  6119. \centerline{Figure \secno: Example Flow of Measurement objects in \pn}
  6120. \medskip
  6121. Please note that Figure \secno~is representative of a typical configuration. Now
  6122. that the flow of measurements through \pn{} is determined by a script specified
  6123. by the user, whatever pipeline is needed can be specified at run time.
  6124. @* The DAQ class.
  6125. \noindent The |DAQ| class represents a piece of hardware that allows the
  6126. computer to read measurements from one or more thermocouples. Presently this
  6127. class is only handles continuous sampling on devices from National Instruments.
  6128. It should be simple to modify this class to handle similar devices from other
  6129. vendors.
  6130. Each device is represented by a single instance of this class. Multiple channels
  6131. can be used on a device if the device supports it.
  6132. Two enumerations are declared in this class to be used as arguments to
  6133. |newChannel()|. The first is used to set the measurement unit for the channel.
  6134. As the measurements themselves do not carry this information, it is important to
  6135. keep track of this information. The values come from {\tt nidaqmxbase.h} and can
  6136. be used to select among Fahrenheit, Celsius, Kelvin, and Rankine. The
  6137. second enumeration, |ThermocoupleType|, should be used to specify the type of
  6138. thermocouple connected to the device. If this does not match reality, the
  6139. measurements will not be correct. The meanings of the values should be obvious
  6140. from the names.
  6141. \danger When this class was originally written the method of thread handling
  6142. used was considered appropriate. New functionality in |QThread| has made this
  6143. no longer the case. This class is currently planned for depreciation once a
  6144. replacement class hierarchy more suited to multiple hardware types is available
  6145. however if this is not ready soon it may be beneficial to rewrite this class to
  6146. conform to current best practices.\endanger
  6147. @<Class declarations@>=
  6148. class Channel;
  6149. class DAQImplementation;@/
  6150. class DAQ : public QObject@;@/
  6151. {@t\1@>@/
  6152. Q_OBJECT@/
  6153. Q_ENUMS(ThermocoupleType)@;@/
  6154. DAQImplementation *imp;@/
  6155. @t\4@>private slots@t\kern-3pt@>:@/
  6156. void threadFinished();
  6157. public:@;
  6158. DAQ(QString device, const QString &driver = QString("nidaqmxbase"));
  6159. ~DAQ();@/
  6160. Channel* newChannel(int units, int thermocouple);@/
  6161. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  6162. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  6163. @[Q_INVOKABLE@,@, void@]@, stop();@t\2\2@>@/
  6164. enum ThermocoupleType@/
  6165. {
  6166. @!TypeJ = 10072,
  6167. @!TypeK = 10073,
  6168. @!TypeN = 10077,
  6169. @!TypeR = 10082,
  6170. @!TypeS = 10085,
  6171. @!TypeT = 10086,
  6172. @!TypeB = 10047,
  6173. @!TypeE = 10055
  6174. };@t\2@>@/
  6175. }@t\kern-3pt@>;
  6176. @ The |DAQ| class has as a private member an instance of a class called
  6177. |DAQImplementation|. The two classes together create and run a new thread of
  6178. execution. This thread spends most of its time blocking while waiting for a new
  6179. measurement to become available. When a new measurement is available, that
  6180. measurement is passed to the appropriate channel which in turn passes it to any
  6181. interested object.
  6182. @<Class declarations@>=
  6183. class DAQImplementation : public QThread@;@/
  6184. {@;
  6185. Q_OBJECT@;@/
  6186. public:@;
  6187. DAQImplementation(const QString &driverinfo);
  6188. ~DAQImplementation();
  6189. void run();
  6190. void measure();
  6191. @<Library function pointers@>@;
  6192. @<DAQImplementation member data@>@;
  6193. }@+@t\kern-3pt@>;
  6194. @ In order to solve some minor problems, NI-DAQmxBase is no longer linked at
  6195. compile time. Rather, this is now linked at runtime through a |QLibrary| object.
  6196. In order to use functions from this library, these functions must be stored in
  6197. function pointers. Fortunately, all of these functions can be expressed with the
  6198. same pointer type. Unfortunately, this way of doing things offers very little
  6199. debugging information in the event that something is not quite right.
  6200. @<Library function pointers@>=
  6201. typedef int (*daqfp)(...);
  6202. daqfp read;
  6203. daqfp errorInfo;
  6204. daqfp startTask;
  6205. daqfp createTask;
  6206. daqfp createChannel;
  6207. daqfp setClock;
  6208. daqfp stopTask;
  6209. daqfp clearTask;
  6210. daqfp resetDevice;
  6211. daqfp waitForMeasurement;
  6212. @ |DAQImplementation| also maintains information about the device and the
  6213. channels the measurements are sent to.
  6214. @<DAQImplementation member data@>=
  6215. bool useBase;
  6216. QString device;
  6217. QVector<Channel*> channelMap;
  6218. unsigned int handle;@/
  6219. int error;
  6220. int channels;
  6221. bool ready;
  6222. QLibrary driver;
  6223. QVector<Units::Unit> unitMap;
  6224. @ Most of the interesting work associated with the |DAQ| class is handled in
  6225. the |measure()| method of |DAQImplementation|. This function will block until a
  6226. measurement is available. Once |buffer| is filled by |DAQmxBaseReadAnalogF64()|
  6227. that function returns and new |Measurement| objects are created based on the
  6228. information in the buffer. These measurements are sent to |Channel| objects
  6229. tracked by |channelMap|.
  6230. Up until version 1.0.7 there was a bug in this code that would prevent the code
  6231. from working when more than one channel is requested. This has been corrected.
  6232. With version 1.0.9, time measurement is moved out of the loop, reducing the
  6233. number of calls in cases of more than 1 measurement and ensuring that all
  6234. simultaneously obtained measurements have the same time stamp.
  6235. @<DAQ Implementation@>=
  6236. void DAQImplementation::measure()@t\2@>@/
  6237. @t\4@>{@/
  6238. int samplesRead = 0;
  6239. double buffer[channels];
  6240. error = read((unsigned int)(handle), (signed long)(1), (double)(10.0),@|
  6241. (unsigned long)(0), buffer, (unsigned long)(channels),@|
  6242. &samplesRead, (signed long)(0));@/
  6243. if(error)@/
  6244. @t\1@>{@/
  6245. ready = false;@t\2@>@/
  6246. }
  6247. else@/
  6248. {
  6249. if(samplesRead)@/
  6250. {
  6251. QTime time = QTime::currentTime();@/
  6252. for(int i = 0; i < samplesRead; i++)@/
  6253. {
  6254. for(int j = 0; j < channels; j++)@/
  6255. {
  6256. double measuredValue = buffer[j+(i*channels)];
  6257. Measurement measure(measuredValue, time,
  6258. unitMap[j]);
  6259. channelMap[@,j]->input(measure);
  6260. }
  6261. }
  6262. }
  6263. }
  6264. @t\4@>}
  6265. @ It was noted that |DAQmxBaseReadAnalogF64()| blocks until it is able to fill
  6266. the |buffer| passed to it. To prevent this behavior from having adverse effects
  6267. on the rest of the program, measure is called from a loop running in its own
  6268. thread of execution. When the thread is started, it begins its execution from
  6269. the |run()| method of |DAQImplementation| which overrides the |run()| method of
  6270. |QThread|. Here the priority of the thread is set in an attempt to cut down on
  6271. the variation in time between recorded measurements.
  6272. The while loop is controlled by |ready| which is set to |false| when there is an
  6273. error in collecting a measurement or when the user wants to exit the program. It
  6274. could also be set to |false| when the |DAQ| is reconfigured.
  6275. @<DAQ Implementation@>=
  6276. void DAQImplementation::run()
  6277. {
  6278. setPriority(QThread::TimeCriticalPriority);
  6279. while(ready)
  6280. {
  6281. measure();
  6282. }
  6283. }
  6284. @ When this loop exits, |DAQImplementation| emits a finished signal to indicate
  6285. that the thread is no longer running. This could be due to perfectly normal
  6286. conditions, but there could also be a problem that the user must be informed of.
  6287. That signal is connected to a function that checks for error conditions and
  6288. reports them if needed.
  6289. @<DAQ Implementation@>=
  6290. void DAQ::threadFinished()
  6291. {
  6292. if(imp->error)
  6293. {
  6294. @<Display DAQ Error@>@;
  6295. }
  6296. }
  6297. @ Errors are displayed with a |QMessageBox|. NIDAQmxBase provides the message
  6298. strings for these errors, but this should probably change as these error strings
  6299. are generally completely unrelated to what the problem really is. For example,
  6300. ``Error: -1'' usually means that the device is not plugged in.
  6301. ``Error: -200170'' usually means that \pn{} or another program using the device
  6302. did not exit cleanly. A table of replacement warning messages should be added to
  6303. this program.
  6304. \bigskip
  6305. \settabs 5 \columns
  6306. \+Error Code & NIDAQmxBase Text & & Likely Cause\cr
  6307. \+\hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill\cr
  6308. \+ -1 & Not implemented for this device & & The device is not plugged in.\cr
  6309. \+ & type. & \cr
  6310. \+ -200170 & Physical channel specified & & The program did not exit cleanly\cr
  6311. \+ & does not exist on this device. & & or another program is using the\cr
  6312. \+ & Refer to the documentation for & & device.\cr
  6313. \+ & channels available on this device.\cr
  6314. \+ -1073807194 & {\it{(No text)}} & & The device has been unplugged.\cr
  6315. \medskip
  6316. \centerline{Table \secno: Error codes, text, and what they really mean.}
  6317. \bigskip
  6318. There are two calls to |DAQmxBaseGetExtendedErrorInfo()| to obtain the error
  6319. messages. The first is used just to obtain the length of the error string. That
  6320. length is then used to allocate space for the error message. The second call
  6321. fills that string. This isn'@q'@>t allowed by ISO \CPLUSPLUS/\nfnote{%
  6322. \CPLUSPLUS/Dynamic Arrays (Crowl and Austern, May 16, 2008)\par
  6323. \hbox{\indent\pdfURL{%
  6324. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}{%
  6325. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}}} but it
  6326. works with gcc. If this is a problem, the first call can be
  6327. removed and the buffer can be set large enough to fit the largest error message
  6328. that will be produced. Heap allocation could be used, but then we need to
  6329. remember to free the memory allocated to the string. Alternately, we can get rid
  6330. of \CEE/ style strings and write our own error messages. This would be the
  6331. preferred correction.
  6332. @<Display DAQ Error@>=
  6333. imp->ready = false;
  6334. QMessageBox warning;
  6335. warning.setStandardButtons(QMessageBox::Cancel);
  6336. warning.setIcon(QMessageBox::Warning);
  6337. warning.setText(QString(tr("Error: %1")).arg(imp->error));
  6338. unsigned long bytes = imp->errorInfo(NULL, 0);
  6339. char string[bytes];
  6340. imp->errorInfo(string, bytes);
  6341. warning.setInformativeText(QString(string));
  6342. warning.setWindowTitle(QString(PROGRAM_NAME));
  6343. warning.exec();
  6344. @ Starting the thread is almost as simple as ending it. The hardware is
  6345. instructed to begin taking measurements. If there is an error, this is handled.
  6346. Otherwise, the finished signal from |DAQImplementation| is connected to
  6347. |threadFinished()| and the new thread is started. The call to |imp->start()|
  6348. starts a new thread and passes control of that thread to |imp->run()|. The main
  6349. thread of execution returns without waiting for the new thread to do anything.
  6350. The call to |DAQmxBaseStartTask()| requires some time before the first
  6351. measurement is available. This is one of the reasons we start gathering
  6352. measurements before we really need them and continue to collect them until it is
  6353. time to exit the program.
  6354. @<DAQ Implementation@>=
  6355. void DAQ::start()
  6356. {
  6357. if(imp->ready)
  6358. {
  6359. imp->error = imp->startTask(imp->handle);
  6360. if(imp->error)
  6361. {
  6362. @<Display DAQ Error@>@;
  6363. }
  6364. else
  6365. {
  6366. connect(imp, SIGNAL(finished()), this, SLOT(threadFinished()));
  6367. imp->start();
  6368. }
  6369. }
  6370. }
  6371. void DAQ::stop()
  6372. {
  6373. if(imp->useBase)
  6374. {
  6375. imp->ready = @[false@];
  6376. imp->wait(ULONG_MAX);
  6377. imp->stopTask(imp->handle);
  6378. }
  6379. else
  6380. {
  6381. imp->ready = @[false@];
  6382. imp->error = imp->stopTask(imp->handle);
  6383. if(imp->error)
  6384. {
  6385. @<Display DAQ Error@>@;
  6386. }
  6387. imp->error = imp->clearTask(imp->handle);
  6388. if(imp->error)
  6389. {
  6390. @<Display DAQ Error@>@;
  6391. }
  6392. }
  6393. }
  6394. @ Setting up the DAQ begins by constructing a new |DAQ| object. The constructor
  6395. takes as its argument a string indicating the name of the device and will
  6396. typically be something like |"Dev1"|. This creates a new task which is required
  6397. for the setup that follows once a new |DAQ| is created.
  6398. @<DAQ Implementation@>=
  6399. DAQ::DAQ(QString device, const QString &driver) : imp(new DAQImplementation(driver))@/
  6400. @t\4\4@>{@/
  6401. imp->device = device;
  6402. imp->error = imp->createTask(device.toAscii().data(), &(imp->handle));
  6403. if(imp->error)@/
  6404. {
  6405. @<Display DAQ Error@>@;
  6406. }
  6407. else@/
  6408. @t\1@>{@/
  6409. imp->ready = true;@t\2@>@/
  6410. }@/
  6411. @t\4\4@>}
  6412. @ Once the |DAQ| is created, one or more channels can be added to that |DAQ|.
  6413. All |Channel| objects are created by the |DAQ| class and are managed by the
  6414. |DAQ| class. When a new channel is created, a pointer is passed back allowing
  6415. other classes to connect to the channel. Measurements cannot be read from the
  6416. |DAQ| directly. They must at some point pass through a channel.
  6417. @<DAQ Implementation@>=
  6418. Channel* DAQ::newChannel(int units, int thermocouple)
  6419. {
  6420. Channel *retval = new Channel();
  6421. imp->channelMap[imp->channels] = retval;
  6422. imp->unitMap[imp->channels] = (Units::Unit)units;
  6423. imp->channels++;
  6424. if(imp->ready)
  6425. {
  6426. if(imp->useBase)
  6427. {
  6428. imp->error = imp->createChannel(imp->handle,
  6429. QString("%1/ai%2").arg(imp->device).
  6430. arg(imp->channels - 1).
  6431. toAscii().data(),
  6432. "", (double)(-1.0), (double)(100.0),
  6433. (signed long)(units),
  6434. (signed long)(thermocouple),
  6435. (signed long)(10200), (double)(0),
  6436. "");
  6437. }
  6438. else
  6439. {
  6440. imp->error = imp->createChannel(imp->handle,
  6441. QString("%1/ai%2").arg(imp->device).
  6442. arg(imp->channels - 1).
  6443. toAscii().data(),
  6444. "", (double)(50.0), (double)(500.0),
  6445. (signed long)(units),
  6446. (signed long)(thermocouple),
  6447. (signed long)(10200), (double)(0),
  6448. "");
  6449. }
  6450. if(imp->error)
  6451. {
  6452. @<Display DAQ Error@>@;
  6453. }
  6454. }
  6455. return retval;
  6456. }
  6457. @ Once the channels are created, it is necessary to set the clock rate of the
  6458. DAQ. The clock rate chosen must be supported by the hardware. The clock rates
  6459. supported by the hardware may be altered by the number of channels in use.
  6460. The amount of time between measurements may vary slightly. A test configuration
  6461. at Wilson's Coffee \char'046~Tea used a 4Hz clock rate and provides measurements
  6462. every 251$\pm$1ms with 80\% of measurements spaced 251ms apart.
  6463. @<DAQ Implementation@>=
  6464. void DAQ::setClockRate(double Hz)
  6465. {
  6466. if(imp->ready)
  6467. {
  6468. imp->error = imp->setClock(imp->handle, "OnboardClock", Hz,
  6469. (signed long)(10280), (signed long)(10123),
  6470. (unsigned long long)(1));
  6471. if(imp->error)
  6472. {
  6473. @<Display DAQ Error@>@;
  6474. }
  6475. }
  6476. }
  6477. @ Before the program exits, the |DAQ| should be deleted. The destructor
  6478. instructs the measurement thread to stop, waits for it to finish, and resets the
  6479. device. If this is not done, an error would be issued the next time a program
  6480. attempted to use the device.
  6481. @<DAQ Implementation@>=
  6482. DAQ::~DAQ()@/
  6483. {
  6484. if(imp->useBase)
  6485. {
  6486. imp->resetDevice(imp->device.toAscii().data());
  6487. imp->clearTask(imp->handle);
  6488. }
  6489. else
  6490. {
  6491. if(imp->ready)
  6492. {
  6493. imp->ready = @[false@];
  6494. imp->wait(ULONG_MAX);
  6495. imp->stopTask(imp->handle);
  6496. imp->resetDevice(imp->device.toAscii().data());
  6497. imp->clearTask(imp->handle);
  6498. }
  6499. }
  6500. delete imp;
  6501. }
  6502. @ This just leaves the constructor and destructor for |DAQImplementation|. The
  6503. way the program is currently written, the number of channels available on the
  6504. |DAQ| is limited to 4. If a known larger number is required, the value here can
  6505. simply be set larger, however the best long term solution would be to modify
  6506. |newChannel()| to resize |channelMap| as more channels are added.
  6507. The constructor handles loading NI-DAQmxBase and preparing function pointers for
  6508. the symbols used in \pn{}.
  6509. @<DAQ Implementation@>=
  6510. DAQImplementation::DAQImplementation(const QString &driverinfo)
  6511. : QThread(NULL), channelMap(4), handle(0), error(0), channels(0), ready(false),
  6512. unitMap(4)@/
  6513. {
  6514. if(driverinfo == "nidaqmxbase")
  6515. {
  6516. useBase = true;
  6517. }
  6518. else
  6519. {
  6520. useBase = false;
  6521. }
  6522. if(useBase)
  6523. {
  6524. driver.setFileName("nidaqmxbase.framework/nidaqmxbase");
  6525. if(!driver.load())
  6526. {
  6527. driver.setFileName("nidaqmxbase");
  6528. if(!driver.load())
  6529. {
  6530. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  6531. tr("Failed to find nidaqmxbase. Please install it."));
  6532. QApplication::quit();
  6533. }
  6534. }
  6535. }
  6536. else
  6537. {
  6538. driver.setFileName("nicaiu");
  6539. if(!driver.load())
  6540. {
  6541. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  6542. tr("Failed to find nidaqmx. Please install it."));
  6543. QApplication::quit();
  6544. }
  6545. }
  6546. if(useBase)
  6547. {
  6548. if((createTask = (daqfp) driver.resolve("DAQmxBaseCreateTask")) == 0 || @|
  6549. (startTask = (daqfp) driver.resolve("DAQmxBaseStartTask")) == 0 || @|
  6550. (stopTask = (daqfp) driver.resolve("DAQmxBaseStopTask")) == 0 || @|
  6551. (clearTask = (daqfp) driver.resolve("DAQmxBaseClearTask")) == 0 || @|
  6552. (createChannel = (daqfp) driver.resolve("DAQmxBaseCreateAIThrmcplChan"))
  6553. == 0 || @|
  6554. (setClock = (daqfp) driver.resolve("DAQmxBaseCfgSampClkTiming")) ==
  6555. 0 || @|
  6556. (read = (daqfp) driver.resolve("DAQmxBaseReadAnalogF64")) == 0 || @|
  6557. (errorInfo = (daqfp) driver.resolve("DAQmxBaseGetExtendedErrorInfo")) ==
  6558. 0 || @|
  6559. (resetDevice = (daqfp) driver.resolve("DAQmxBaseResetDevice")) == 0)@/
  6560. {
  6561. waitForMeasurement = NULL;
  6562. QMessageBox::critical(NULL, tr("Typica: Link error"),
  6563. tr("Failed to link a required symbol in NI-DAQmxBase."));
  6564. QApplication::quit();
  6565. }
  6566. }
  6567. else
  6568. {
  6569. if((createTask = (daqfp)driver.resolve("DAQmxCreateTask")) == 0 || @|
  6570. (startTask = (daqfp)driver.resolve("DAQmxStartTask")) == 0 || @|
  6571. (stopTask = (daqfp)driver.resolve("DAQmxStopTask")) == 0 || @|
  6572. (clearTask = (daqfp)driver.resolve("DAQmxClearTask")) == 0 || @|
  6573. (createChannel = (daqfp)driver.resolve("DAQmxCreateAIThrmcplChan"))
  6574. == 0 || @|
  6575. (setClock = (daqfp)driver.resolve("DAQmxCfgSampClkTiming")) == 0 || @|
  6576. (read = (daqfp)driver.resolve("DAQmxReadAnalogF64")) == 0 || @|
  6577. (errorInfo = (daqfp)driver.resolve("DAQmxGetExtendedErrorInfo")) ==
  6578. 0 || @|
  6579. (resetDevice = (daqfp)driver.resolve("DAQmxResetDevice")) == 0 ||
  6580. (waitForMeasurement = (daqfp)driver.resolve("DAQmxWaitUntilTaskDone")) == 0)
  6581. {
  6582. QMessageBox::critical(NULL, tr("Typica: Link error"),
  6583. tr("Failed to link a required symbol in NI-DAQmx."));
  6584. QApplication::quit();
  6585. }
  6586. }
  6587. }
  6588. DAQImplementation::~DAQImplementation()
  6589. {
  6590. driver.unload();
  6591. }
  6592. @ When exposing the |DAQ| class to the scripting engine, we need to provide a
  6593. constructor that can be called from a script and we need a way to call
  6594. |DAQ::newChannel()|. Other methods that are useful when called from a script are
  6595. made available automatically with the |Q_INVOKABLE| macro, however this does not
  6596. work for methods such as |newChannel()| which return a pointer to a |Channel|
  6597. object.
  6598. @<Function prototypes for scripting@>=
  6599. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine);
  6600. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  6601. void setDAQProperties(QScriptValue value, QScriptEngine *engine);
  6602. @ These functions and the values from |Units::Unit| must be made available to
  6603. the host environment. The latter because this was widely used in configurations
  6604. before this enumeration was removed from the |DAQ| class. As these properties
  6605. must be available without an instance, the properties must be added here.
  6606. @<Set up the scripting engine@>=
  6607. constructor = engine->newFunction(constructDAQ);
  6608. value = engine->newQMetaObject(&DAQ::staticMetaObject, constructor);
  6609. value.setProperty("Fahrenheit", Units::Fahrenheit);
  6610. value.setProperty("Celsius", Units::Celsius);
  6611. value.setProperty("Kelvin", Units::Kelvin);
  6612. value.setProperty("Rankine", Units::Rankine);
  6613. engine->globalObject().setProperty("DAQ", value);
  6614. @ When creating a new |DAQ|, we make sure that it is owned by the script engine.
  6615. This is necessary to ensure that the destructor is called before \pn{} exits.
  6616. Just as the constructor requires an argument that specifies the device name, the
  6617. constructor available from a script also requires this argument.
  6618. @<Functions for scripting@>=
  6619. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine)
  6620. {
  6621. QScriptValue object;
  6622. if(context->argumentCount() == 1)
  6623. {
  6624. object = engine->newQObject(new DAQ(argument<QString>(0, context)),
  6625. QScriptEngine::ScriptOwnership);
  6626. setDAQProperties(object, engine);
  6627. }
  6628. else if(context->argumentCount() == 2)
  6629. {
  6630. object = engine->newQObject(new DAQ(argument<QString>(0, context),
  6631. argument<QString>(1, context)),
  6632. QScriptEngine::ScriptOwnership);
  6633. setDAQProperties(object, engine);
  6634. }
  6635. else
  6636. {
  6637. context->throwError("Incorrect number of arguments passed to DAQ"@|
  6638. "constructor. The DAQ constructor takes one"@|
  6639. "string as an argument specifying a device name."@|
  6640. "Example: Dev1");
  6641. }
  6642. return object;
  6643. }
  6644. @ As |DAQ| inherits |QObject|, we add the |newChannel()| property after adding
  6645. any |QObject| properties.
  6646. @<Functions for scripting@>=
  6647. void setDAQProperties(QScriptValue value, QScriptEngine *engine)
  6648. {
  6649. setQObjectProperties(value, engine);
  6650. value.setProperty("newChannel", engine->newFunction(DAQ_newChannel));
  6651. }
  6652. @ The |newChannel()| method method also requires that two arguments are provided
  6653. by the script.
  6654. @<Functions for scripting@>=
  6655. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  6656. {
  6657. DAQ *self = getself<@[DAQ *@]>(context);
  6658. QScriptValue object;
  6659. if(self)
  6660. {
  6661. object =
  6662. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  6663. argument<int>(1, context)));
  6664. setChannelProperties(object, engine);
  6665. }
  6666. return object;
  6667. }
  6668. @ Sometimes it can be useful to test other parts of the program (for example,
  6669. when developing new scripts) when the DAQ hardware is not available. In these
  6670. cases, it is possible to temporarily use the |FakeDAQ| class. This class mimics
  6671. the |DAQ| class, but just makes up the measurements sent to the rest of the
  6672. program.
  6673. @<Class declarations@>=
  6674. class FakeDAQImplementation : public QThread@/
  6675. {@/
  6676. Q_OBJECT@;
  6677. public:@/
  6678. FakeDAQImplementation();
  6679. ~FakeDAQImplementation();
  6680. void run();
  6681. void measure();
  6682. QVector<Channel *> channelMap;
  6683. int channels;
  6684. bool ready;
  6685. double clockRate;
  6686. };@/
  6687. class FakeDAQ : public QObject@/
  6688. {@/
  6689. Q_OBJECT@;
  6690. FakeDAQImplementation *imp;
  6691. public:@/
  6692. FakeDAQ(QString device);
  6693. ~FakeDAQ();
  6694. Channel *newChannel(int units, int thermocouple);@/
  6695. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  6696. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  6697. };
  6698. @ Just as in the |DAQ| class, most of the interesting stuff happens in
  6699. |measure()|. For each invokation of the method, we sleep for some amount of time
  6700. based on the clock rate then create a |Measurement| object at random for each
  6701. |Channel| that has been created.
  6702. @<FakeDAQ Implementation@>=
  6703. void FakeDAQImplementation::measure()
  6704. {
  6705. msleep((int)(1000/clockRate));
  6706. QTime time = QTime::currentTime();
  6707. for(int i = 0; i < channels; i++)
  6708. {
  6709. Measurement measure(qrand() % 500, time);
  6710. channelMap[i]->input(measure);
  6711. }
  6712. }
  6713. @ To call |measure|, we need to flesh out the rest of |FakeDAQImplementation|.
  6714. @<FakeDAQ Implementation@>=
  6715. void FakeDAQImplementation::run()
  6716. {
  6717. setPriority(QThread::TimeCriticalPriority);
  6718. while(ready)
  6719. {
  6720. measure();
  6721. }
  6722. }
  6723. FakeDAQImplementation::FakeDAQImplementation() : QThread(NULL), channelMap(4),
  6724. channels(0), ready(false), clockRate(1)@/
  6725. {
  6726. /* Nothing has to be done here. */
  6727. }
  6728. FakeDAQImplementation::~FakeDAQImplementation()
  6729. {
  6730. /* Nothing has to be done here. */
  6731. }
  6732. @ Next we need an implementation for the |FakeDAQ| class. This is simplified by
  6733. the fact that we are just using a random number generator to generate
  6734. measurements rather than special hardware for obtaining measurements.
  6735. @<FakeDAQ Implementation@>=
  6736. void FakeDAQ::start()
  6737. {
  6738. if(imp->ready)
  6739. {
  6740. imp->start();
  6741. }
  6742. }@#
  6743. FakeDAQ::FakeDAQ(QString) : imp(new FakeDAQImplementation())@t\2\2@>@/
  6744. {@t\1@>@/
  6745. imp->ready = true;@t\2@>@/
  6746. }@#
  6747. Channel* FakeDAQ::newChannel(int, int)
  6748. {
  6749. Channel *retval;
  6750. if(imp->ready)
  6751. {
  6752. retval = new Channel();
  6753. imp->channelMap[imp->channels] = retval;
  6754. imp->channels++;
  6755. }
  6756. else
  6757. {
  6758. return NULL;
  6759. }
  6760. return retval;
  6761. }
  6762. void FakeDAQ::setClockRate(double Hz)
  6763. {
  6764. if(imp->ready)
  6765. {
  6766. imp->clockRate = Hz;
  6767. }
  6768. }@#
  6769. FakeDAQ::~FakeDAQ()@t\2\2@>@/
  6770. {@t\1@>@/
  6771. imp->ready = false;
  6772. imp->wait(ULONG_MAX);
  6773. delete imp;@t\2@>@/
  6774. }
  6775. @ As the entire purpose of the |FakeDAQ| class is for testing purposes from
  6776. within the scripting engine, we need to make it available to the scripting
  6777. engine. This is done in a manner very similar to how the |DAQ| class is handled.
  6778. @<Function prototypes for scripting@>=
  6779. QScriptValue constructFakeDAQ(QScriptContext *context, QScriptEngine *engine);
  6780. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  6781. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine);
  6782. @ The scripting engine is informed of the constructor.
  6783. @<Set up the scripting engine@>=
  6784. constructor = engine->newFunction(constructFakeDAQ);
  6785. value = engine->newQMetaObject(&FakeDAQ::staticMetaObject, constructor);
  6786. engine->globalObject().setProperty("FakeDAQ", value);
  6787. @ The constructor sets a property to allow calling |newChannel()| on a |FakeDAQ|
  6788. created from a script.
  6789. @<Functions for scripting@>=
  6790. QScriptValue constructFakeDAQ(QScriptContext *context,
  6791. QScriptEngine *engine)
  6792. {
  6793. QScriptValue object;
  6794. if(context->argumentCount() == 1)
  6795. {
  6796. object =
  6797. engine->newQObject(new FakeDAQ(argument<QString>(0, context)),
  6798. QScriptEngine::ScriptOwnership);
  6799. setFakeDAQProperties(object, engine);
  6800. }
  6801. else
  6802. {
  6803. context->throwError("Incorrect number of arguments passed to DAQ"@|
  6804. "constructor. The DAQ constructor takes one"@|
  6805. "string as an argument specifying a device name."@|
  6806. "Example: Dev1");
  6807. }
  6808. return object;
  6809. }
  6810. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine)
  6811. {
  6812. setQObjectProperties(value, engine);
  6813. value.setProperty("newChannel", engine->newFunction(FakeDAQ_newChannel));
  6814. }
  6815. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  6816. {
  6817. FakeDAQ *self = getself<@[FakeDAQ *@]>(context);
  6818. QScriptValue object;
  6819. if(self)
  6820. {
  6821. object =
  6822. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  6823. argument<int>(1, context)));
  6824. setChannelProperties(object, engine);
  6825. }
  6826. return object;
  6827. }
  6828. @* The Channel class.
  6829. \noindent |Channel| is a simple class. It is a subclass of |QObject| so it can
  6830. use Qt'@q'@>s signals and slots mechanism. Any object that is interested in
  6831. measurements from a channel can connect to the |newData| signal the channel
  6832. emits. Any number of objects can make this connection and each will receive a
  6833. copy of the measurement.
  6834. |Channel| objects should only be created by the |DAQ| class.
  6835. @<Class declarations@>=
  6836. class Channel : public QObject@;@/
  6837. {@t\1@>@/
  6838. Q_OBJECT@/
  6839. public:@;
  6840. Channel();
  6841. ~Channel();@/
  6842. @t\4@>public slots@t\kern-3pt@>:@;
  6843. void input(Measurement measurement);@/
  6844. signals:@;
  6845. void newData(Measurement);@t\2@>@/
  6846. };
  6847. @ The implementation of this class is trivial.
  6848. @<Channel Implementation@>=
  6849. Channel::Channel() : QObject(NULL)@/
  6850. {
  6851. /* Nothing has to be done here. */
  6852. }
  6853. Channel::~Channel()
  6854. {
  6855. /* Nothing has to be done here. */
  6856. }
  6857. void Channel::input(Measurement measurement)
  6858. {
  6859. emit newData(measurement);
  6860. }
  6861. @ A function is provided for use when a channel is created by a DAQ from a
  6862. script.
  6863. @<Function prototypes for scripting@>=
  6864. void setChannelProperties(QScriptValue value, QScriptEngine *engine);
  6865. @ The implementation is trivial.
  6866. @<Functions for scripting@>=
  6867. void setChannelProperties(QScriptValue value, QScriptEngine *engine)
  6868. {
  6869. setQObjectProperties(value, engine);
  6870. }
  6871. @* Calibration and Unit Conversion.
  6872. \noindent One of the planned features for \pn{} is support for hardware that
  6873. collects non-temperature measurements. This is frequently handled with analog
  6874. voltage signals which are proportional to some range in a meaningful unit. Some
  6875. hardware also requires calibration in software. In many cases both of these can
  6876. be handled at the same time with a single mapping in the form:
  6877. $$f(x) = L_1 + (x - L_2){U_1 - L_1\over{U_2 - L_2}}$$
  6878. \noindent where $L_1$ is the logical lower bound, $L_2$ is the measured lower
  6879. bound, $U_1$ is the logical upper bound, $U_2$ is the measured upper bound, and
  6880. $x$ is the value we wish to map from the range $\lbrack L_2, U_2 \rbrack$ to
  6881. the range $\lbrack L_1, U_1 \rbrack$.
  6882. Some use cases require a closed range but others require that this constraint
  6883. is loosened to allow extrapolation. Both are provided by this class.
  6884. Starting in \pn{} 1.6 this class has both the |measurement| and the
  6885. |newData| signals. This allows a |LinearCalibrator| to be treated like a
  6886. |Channel| when used with a |DataqSdkDevice|.
  6887. @<Class declarations@>=
  6888. class LinearCalibrator : public QObject@/
  6889. {@/
  6890. @[Q_OBJECT@]@;
  6891. @[Q_PROPERTY(double measuredLower READ measuredLower
  6892. WRITE setMeasuredLower)@]@;
  6893. @[Q_PROPERTY(double measuredUpper READ measuredUpper
  6894. WRITE setMeasuredUpper)@]@;
  6895. @[Q_PROPERTY(double mappedLower READ mappedLower WRITE setMappedLower)@]@;
  6896. @[Q_PROPERTY(double mappedUpper READ mappedUpper WRITE setMappedUpper)@]@;
  6897. @[Q_PROPERTY(bool closedRange READ isClosedRange WRITE setClosedRange)@]@;
  6898. @[Q_PROPERTY(double sensitivity READ sensitivity WRITE setSensitivity)@]@;
  6899. public:@/
  6900. LinearCalibrator(QObject *parent = NULL);
  6901. double measuredLower();
  6902. double measuredUpper();
  6903. double mappedLower();
  6904. double mappedUpper();
  6905. bool isClosedRange();
  6906. double sensitivity();
  6907. @t\4@>@[public slots@t\kern-3pt@>:@]@;
  6908. void setMeasuredLower(double lower);
  6909. void setMeasuredUpper(double upper);
  6910. void setMappedLower(double lower);
  6911. void setMappedUpper(double upper);
  6912. void setClosedRange(bool closed);
  6913. void setSensitivity(double sensitivity);
  6914. Measurement newMeasurement(Measurement measure);
  6915. @t\4@>@[signals:@]@;
  6916. void measurement(Measurement measure);
  6917. void newData(Measurement measure);
  6918. private:@/
  6919. double Lo1;
  6920. double Lo2;
  6921. double Up1;
  6922. double Up2;
  6923. double sensitivitySetting;
  6924. bool clamp;
  6925. };
  6926. @ When the measured range and the mapped range are identical and the range is
  6927. open, we have an identity mapping. This is the default state in a newly
  6928. constructed |LinearCalibrator| which should quickly be changed.
  6929. @<LinearCalibrator Implementation@>=
  6930. LinearCalibrator::LinearCalibrator(QObject *parent) :
  6931. QObject(parent), Lo1(0), Lo2(0), Up1(1), Up2(1), sensitivitySetting(0.0), clamp(false)@/
  6932. {
  6933. connect(this, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  6934. }
  6935. @ The functional portion of the class is in the |newMeasurement()| slot. This
  6936. will receive measurements as they come in and emit a |measurement()| signal for
  6937. each with the calibration and unit adjustment performed.
  6938. This method also handles any rounding needed if there has been a call to
  6939. |setSensitivity()|.
  6940. @<LinearCalibrator Implementation@>=
  6941. Measurement LinearCalibrator::newMeasurement(Measurement measure)
  6942. {
  6943. double outval = Lo1 + (measure.temperature() - Lo2) * (Up1 - Lo1)/(Up2 - Lo2);
  6944. if(clamp)
  6945. {
  6946. if(outval < Lo1)
  6947. {
  6948. outval = Lo1;
  6949. }
  6950. else if(outval > Up1)
  6951. {
  6952. outval = Up1;
  6953. }
  6954. }
  6955. if(sensitivitySetting >= 0.05)
  6956. {
  6957. int temp = qRound(outval/sensitivitySetting);
  6958. outval = temp * sensitivitySetting;
  6959. }
  6960. Measurement adjusted(outval, measure.time(), measure.scale());
  6961. emit measurement(adjusted);
  6962. return adjusted;
  6963. }
  6964. @ The rest of the class consists of trivial accessor methods.
  6965. @<LinearCalibrator Implementation@>=
  6966. double LinearCalibrator::measuredLower()
  6967. {
  6968. return Lo2;
  6969. }
  6970. double LinearCalibrator::measuredUpper()
  6971. {
  6972. return Up2;
  6973. }
  6974. double LinearCalibrator::mappedLower()
  6975. {
  6976. return Lo1;
  6977. }
  6978. double LinearCalibrator::mappedUpper()
  6979. {
  6980. return Up1;
  6981. }
  6982. bool LinearCalibrator::isClosedRange()
  6983. {
  6984. return clamp;
  6985. }
  6986. void LinearCalibrator::setMeasuredLower(double lower)
  6987. {
  6988. Lo2 = lower;
  6989. }
  6990. void LinearCalibrator::setMeasuredUpper(double upper)
  6991. {
  6992. Up2 = upper;
  6993. }
  6994. void LinearCalibrator::setMappedLower(double lower)
  6995. {
  6996. Lo1 = lower;
  6997. }
  6998. void LinearCalibrator::setMappedUpper(double upper)
  6999. {
  7000. Up1 = upper;
  7001. }
  7002. void LinearCalibrator::setClosedRange(bool closed)
  7003. {
  7004. clamp = closed;
  7005. }
  7006. void LinearCalibrator::setSensitivity(double sensitivity)
  7007. {
  7008. sensitivitySetting = sensitivity;
  7009. }
  7010. double LinearCalibrator::sensitivity()
  7011. {
  7012. return sensitivitySetting;
  7013. }
  7014. @ Finally, we make this class available to the scripting engine. Two functions
  7015. are required for this.
  7016. @<Function prototypes for scripting@>=
  7017. QScriptValue constructLinearCalibrator(QScriptContext *context,
  7018. QScriptEngine *engine);
  7019. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine);
  7020. @ The scripting engine is informed of the constructor.
  7021. @<Set up the scripting engine@>=
  7022. constructor = engine->newFunction(constructLinearCalibrator);
  7023. value = engine->newQMetaObject(&LinearCalibrator::staticMetaObject,
  7024. constructor);
  7025. engine->globalObject().setProperty("LinearCalibrator", value);
  7026. @ The implementation of these functions is typical for this application.
  7027. @<Functions for scripting@>=
  7028. QScriptValue constructLinearCalibrator(QScriptContext *, QScriptEngine *engine)
  7029. {
  7030. QScriptValue object = engine->newQObject(new LinearCalibrator(NULL));
  7031. setLinearCalibratorProperties(object, engine);
  7032. return object;
  7033. }
  7034. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine)
  7035. {
  7036. setQObjectProperties(value, engine);
  7037. }
  7038. @* Linear Spline Interpolation.
  7039. \noindent While linear interpolation is adequate for many purposes, it fails
  7040. when a nonlinear mapping is required. The primary use case is to calibrate
  7041. multiple coffee roasters so that roast profiles can be shared among coffee
  7042. roasters with sufficiently similar heat transfer characteristics even if
  7043. differences in the measurement hardware result in different measured values.
  7044. By recording measured values at several points known to be equivalent due to
  7045. easily observable physical changes in the coffee it is possible to use linear
  7046. spline interpolation to produce a data series that approximates on one machine
  7047. the measurements that would have been produced at another. Acceptable results
  7048. may be available with surprisingly few data points.
  7049. It was originally suspected that cubic spline interpolation would produce a
  7050. more accurate mapping, but testing with linear spline interpolation produced
  7051. results good enough that more complex mappings were not needed. Cubic spline
  7052. interpolation may still be implemented in the future, but it is a low
  7053. priority.
  7054. @<Class declarations@>=
  7055. class LinearSplineInterpolator : public QObject@/
  7056. {@/
  7057. @[Q_OBJECT@]@;@/
  7058. public:@/
  7059. LinearSplineInterpolator(QObject *parent = NULL);
  7060. @[Q_INVOKABLE@,@, void@]@, add_pair(double source, double destination);@t\2\2@>@/
  7061. @[public slots@]:@/
  7062. Measurement newMeasurement(Measurement measure);
  7063. @[signals@]:@/
  7064. void newData(Measurement measure);
  7065. private:@/
  7066. void make_interpolators();
  7067. QMap<double, double> *pairs;
  7068. QList<LinearCalibrator *> *interpolators;@/
  7069. };
  7070. @ We take advantage of the fact that iterating over a QMap always returns
  7071. entries in key order. When new measurement pairs are specified, the
  7072. interpolators are regenerated. There is significant room for performance
  7073. improvement.
  7074. @<LinearSplineInterpolator Implementation@>=
  7075. void LinearSplineInterpolator::add_pair(double source, double destination)
  7076. {
  7077. pairs->insert(source, destination);
  7078. make_interpolators();
  7079. }
  7080. void LinearSplineInterpolator::make_interpolators()
  7081. {
  7082. if(pairs->size() > 1)
  7083. {
  7084. while(interpolators->size() > 0)
  7085. {
  7086. LinearCalibrator *removed = interpolators->takeFirst();
  7087. removed->deleteLater();
  7088. }
  7089. QMap<double, double>::const_iterator i = pairs->constBegin();
  7090. QMap<double, double>::const_iterator j = i + 1;
  7091. while(j != pairs->constEnd())
  7092. {
  7093. LinearCalibrator *segment = new LinearCalibrator();
  7094. segment->setMeasuredLower(i.key());
  7095. segment->setMappedLower(i.value());
  7096. segment->setMeasuredUpper(j.key());
  7097. segment->setMappedUpper(j.value());
  7098. segment->setClosedRange(false);
  7099. interpolators->append(segment);
  7100. connect(segment, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  7101. i++;
  7102. j++;
  7103. }
  7104. }
  7105. }
  7106. LinearSplineInterpolator::LinearSplineInterpolator(QObject *parent) :
  7107. QObject(parent), pairs(new QMap<double, double>),
  7108. interpolators(new QList<LinearCalibrator *>)
  7109. {
  7110. /* Nothing needs to be done here. */
  7111. }
  7112. Measurement LinearSplineInterpolator::newMeasurement(Measurement measure)
  7113. {
  7114. QMap<double, double>::const_iterator i = pairs->constBegin();
  7115. int index = -1;
  7116. while(i != pairs->constEnd())
  7117. {
  7118. if(measure.temperature() <= i.key())
  7119. {
  7120. break;
  7121. }
  7122. i++;
  7123. index++;
  7124. }
  7125. if(index < 0)
  7126. {
  7127. index = 0;
  7128. }
  7129. if(index >= interpolators->size())
  7130. {
  7131. index = interpolators->size() - 1;
  7132. }
  7133. if(interpolators->at(index) != NULL)
  7134. {
  7135. return interpolators->at(index)->newMeasurement(measure);
  7136. }
  7137. return Measurement();
  7138. }
  7139. @ This is exposed to the scripting environment as usual.
  7140. @<Function prototypes for scripting@>=
  7141. QScriptValue constructLinearSplineInterpolator(QScriptContext *context, QScriptEngine *engine);
  7142. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine);
  7143. @ As usual.
  7144. @<Set up the scripting engine@>=
  7145. constructor = engine->newFunction(constructLinearSplineInterpolator);
  7146. value = engine->newQMetaObject(&LinearSplineInterpolator::staticMetaObject, constructor);
  7147. engine->globalObject().setProperty("LinearSplineInterpolator", value);
  7148. @ And again as usual.
  7149. @<Functions for scripting@>=
  7150. QScriptValue constructLinearSplineInterpolator(QScriptContext *, QScriptEngine *engine)
  7151. {
  7152. QScriptValue object = engine->newQObject(new LinearSplineInterpolator(NULL));
  7153. setLinearSplineInterpolatorProperties(object, engine);
  7154. return object;
  7155. }
  7156. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine)
  7157. {
  7158. setQObjectProperties(value, engine);
  7159. }
  7160. @* The TemperatureDisplay class.
  7161. Now that measurements have been generated by the |DAQ| and passed to a
  7162. |Channel|, any object that is interested in these measurements can connect to
  7163. the channel and use the measurements it sends out. So far, the time on each
  7164. measurement is the time at which it was collected. Unfortunately, this is often
  7165. not what we want. It is more useful to have the time relative to some other
  7166. point in time such as the start of the batch.
  7167. Until the measurement time is adjusted, the measurements are really only useful
  7168. to classes that do not care about the measurement time. The |TemperatureDisplay|
  7169. class is such a class. It receives measurements and displays the most recently
  7170. measured temperature.
  7171. This is a specialization of |QLCDNumber|.
  7172. @<Class declarations@>=
  7173. class TemperatureDisplay : public QLCDNumber@/
  7174. {@t\1@>@/
  7175. Q_OBJECT@;
  7176. int unit;
  7177. bool r;
  7178. public:@/
  7179. TemperatureDisplay(QWidget *parent = NULL);
  7180. ~TemperatureDisplay();@/
  7181. @t\4@>public slots@t\kern-3pt@>:@/
  7182. void setValue(Measurement temperature);
  7183. void invalidate();
  7184. void setDisplayUnits(Units::Unit scale);
  7185. void setRelativeMode(bool relative);@t\2@>@/
  7186. };
  7187. @ Starting in version 1.6 this widget is also used for displaying a relative
  7188. temperature value in the form of the rate of change indicator. To calculate
  7189. this correctly in Celsius or Kelvin we must have a way to bypass the
  7190. conversions for absolute measures.
  7191. @<TemperatureDisplay Implementation@>=
  7192. void TemperatureDisplay::setRelativeMode(bool relative)
  7193. {
  7194. r = relative;
  7195. }
  7196. @ Displaying a temperature is a simple matter of taking the temperature
  7197. component from the measurement and converting it to a string. Presently, this
  7198. code assumes that the measurements are in degrees Fahrenheit. If the code
  7199. becomes smarter about measurement units it might be a good idea to change this.
  7200. |QLCDNumber| is capable of displaying more than just numbers, so the call to
  7201. display takes a string which in this case consists of the temperature to the
  7202. $1\over100$th of a degree and might be followed by '@q'@> which will be
  7203. converted to $^\circ$ and the letter F, C, or r to indicate the unit. This
  7204. class should be mofified to allow a user specified precision.
  7205. @<TemperatureDisplay Implementation@>=
  7206. void TemperatureDisplay::setValue(Measurement temperature)
  7207. {
  7208. QString number;
  7209. switch(unit)
  7210. {
  7211. case Units::Fahrenheit:
  7212. display(QString("%1'F").
  7213. arg(number.setNum(temperature.toFahrenheit().temperature(), 'f',
  7214. 2)));
  7215. break;
  7216. case Units::Celsius:
  7217. if(!r) {
  7218. display(QString("%1'C").
  7219. arg(number.setNum(temperature.toCelsius().temperature(), 'f',
  7220. 2)));
  7221. } else {
  7222. number.setNum(temperature.temperature() * (5.0/9.0), 'f', 2);
  7223. display(QString("%1'C").arg(number));
  7224. }
  7225. break;
  7226. case Units::Kelvin:
  7227. if(!r) {
  7228. display(QString("%1").
  7229. arg(number.setNum(temperature.toKelvin().temperature(), 'f',
  7230. 2)));
  7231. } else {
  7232. number.setNum(temperature.temperature() * (5.0/9.0), 'f', 2);
  7233. display(QString("%1").arg(number));
  7234. }
  7235. break;
  7236. case Units::Rankine:
  7237. display(QString("%1'r").
  7238. arg(number.setNum(temperature.toRankine().temperature(), 'f',
  7239. 2)));
  7240. break;
  7241. case Units::Unitless:
  7242. display(QString("%1").arg(number.setNum(temperature.temperature(), 'f', 0)));
  7243. break;
  7244. default:
  7245. switch(temperature.scale())
  7246. {
  7247. case Units::Fahrenheit:
  7248. display(QString("%1'F").
  7249. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7250. break;
  7251. case Units::Celsius:
  7252. display(QString("%1'C").
  7253. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7254. break;
  7255. case Units::Kelvin:
  7256. display(QString("%1").
  7257. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7258. break;
  7259. case Units::Rankine:
  7260. display(QString("%1'r").
  7261. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7262. break;
  7263. case Units::Unitless:
  7264. display(QString("%1").arg(number.setNum(temperature.temperature(), 'f', 0)));
  7265. break;
  7266. default:
  7267. qDebug() << "Warning: Attempting to convert a non-temperature unit to a temperature unit";
  7268. break;
  7269. }
  7270. break;
  7271. }
  7272. }
  7273. @ Before measurements are displayed, we set a more sensible default display
  7274. style and an initial string. These defaults can all be overridden with calls to
  7275. the usual |QLCDNumber| methods.
  7276. \medskip
  7277. \resizebox*{6.3in}{!}{\includegraphics{QLCDNumber.png}}
  7278. \smallskip
  7279. \centerline{Figure \secno: Outline (Qt default) and Filled |QLCDNumber| Example}
  7280. \medskip
  7281. @<TemperatureDisplay Implementation@>=
  7282. TemperatureDisplay::TemperatureDisplay(QWidget *parent) :
  7283. QLCDNumber(8, parent), unit(Units::Fahrenheit), r(false)@/
  7284. {
  7285. setSegmentStyle(Filled);
  7286. display("---.--'F");
  7287. }
  7288. @ While it is not currently used, it would be good to allow an error state to
  7289. be easily discernible from a very stable temperature. Currently, if an error
  7290. occurs that results in the measurement thread exiting, no new measurements will
  7291. be generated and the temperature display will continue to read the most recent
  7292. measured value. If an error signal were emitted, it could be connected to the
  7293. following code to change the display to reflect the fact that the current
  7294. temperature is unknown.
  7295. @<TemperatureDisplay Implementation@>=
  7296. void TemperatureDisplay::invalidate()
  7297. {
  7298. display("---.--'F");
  7299. }
  7300. @ \pn{} supports the display of multiple types of unit. Typically, we use the
  7301. Auto scale which will cause |TemperatureDisplay| objects to display measurements
  7302. in whichever scale the measurement is associated with. Alternately, we can fix
  7303. the scale to a different supported scale and convert measurements to that scale
  7304. prior to display.
  7305. @<TemperatureDisplay Implementation@>=
  7306. void TemperatureDisplay::setDisplayUnits(Units::Unit scale)
  7307. {
  7308. unit = scale;
  7309. }
  7310. @ All that is left to deal with is the empty destructor.
  7311. @<TemperatureDisplay Implementation@>=
  7312. TemperatureDisplay::~TemperatureDisplay()
  7313. {
  7314. /* Nothing has to be done here. */
  7315. }
  7316. @ To use a |TemperatureDisplay| from a script, we need a function to pass a new
  7317. object to the scripting engine.
  7318. @<Function prototypes for scripting@>=
  7319. QScriptValue constructTemperatureDisplay(QScriptContext *context,
  7320. QScriptEngine *engine);
  7321. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine);
  7322. QScriptValue TemperatureDisplay_setDisplayUnits(QScriptContext *context,
  7323. QScriptEngine *engine);
  7324. @ The scripting engine must be informed of this function.
  7325. @<Set up the scripting engine@>=
  7326. constructor = engine->newFunction(constructTemperatureDisplay);
  7327. value = engine->newQMetaObject(&TemperatureDisplay::staticMetaObject,
  7328. constructor);
  7329. engine->globalObject().setProperty("TemperatureDisplay", value);
  7330. @ The constructor is trivial.
  7331. @<Functions for scripting@>=
  7332. QScriptValue constructTemperatureDisplay(QScriptContext *,
  7333. QScriptEngine *engine)
  7334. {
  7335. QScriptValue object = engine->newQObject(new TemperatureDisplay);
  7336. setTemperatureDisplayProperties(object, engine);
  7337. return object;
  7338. }
  7339. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine)
  7340. {
  7341. setQLCDNumberProperties(value, engine);
  7342. value.setProperty("setDisplayUnits",
  7343. engine->newFunction(TemperatureDisplay_setDisplayUnits));
  7344. }
  7345. @ There seems to be a bad interaction when enumerated value types as used as
  7346. the argument to slot methods called through QtScript. Script code that attempts
  7347. to make use of the enumeration appears to get the value without any type
  7348. information. When attempting to use that value as an argument the meta-object
  7349. system cannot find an appropriate match and the script just hangs silently.
  7350. The solution is to wrap such methods in the script bindings and explicitly cast
  7351. the argument value to the enumerated type. This looks stupid but it works.
  7352. @<Functions for scripting@>=
  7353. QScriptValue TemperatureDisplay_setDisplayUnits(QScriptContext *context, QScriptEngine *)
  7354. {
  7355. TemperatureDisplay *self = getself<@[TemperatureDisplay *@]>(context);
  7356. self->setDisplayUnits((Units::Unit)argument<int>(0, context));
  7357. return QScriptValue();
  7358. }
  7359. @* The MeasurementTimeOffset class.
  7360. When a |DAQ| object creates a |Measurement| object, the time component is a
  7361. system time. In most cases, the system time is not interesting and a more useful
  7362. time would be relative to the start of a process. This class should be used as a
  7363. filter, taking measurements with a system time stamp and producing measurements
  7364. with a relative time.
  7365. @<Class declarations@>=
  7366. class MeasurementTimeOffset : public QObject@/
  7367. {@t\1@>@/
  7368. Q_OBJECT@;
  7369. QTime epoch;
  7370. QTime previous;
  7371. bool hasPrevious;@/
  7372. public:@;
  7373. MeasurementTimeOffset(QTime zero);
  7374. QTime zeroTime();@/
  7375. @t\4@>public slots@t\kern-3pt@>:@;
  7376. void newMeasurement(Measurement measure);
  7377. void setZeroTime(QTime zero);
  7378. signals:@;
  7379. void measurement(Measurement measure);@t\2@>@/
  7380. }@t\kern-3pt@>;
  7381. @ The interesting part of this class is the function which takes a measurement
  7382. with a system time and produces a new measurement with a time relative to some
  7383. start time.
  7384. When using this class, it is possible that a measurement will arrive with a time
  7385. slightly before a newly chosen epoch. In such a case we do not want to simply
  7386. subtract the epoch from the measurement time as other classes will interpret
  7387. this incorrectly as a measurement time slightly less than 1 hour. This means
  7388. that we need to check if the measurement time is before the epoch. If it is, we
  7389. consider it to have been generated at the epoch rather than before. Aren't race
  7390. conditions fun?
  7391. Additionally, since we're only getting time of day information, some special
  7392. handling must be done for time series that cross the boundary between days. We
  7393. should never get measurements out of order, so keeping a record of the previous
  7394. measurement and verifying that the new measurement comes after it is sufficient.
  7395. @<MeasurementTimeOffset Implementation@>=
  7396. void MeasurementTimeOffset::newMeasurement(Measurement measure)@t\2\2@>@/
  7397. {@t\1@>@/
  7398. if(measure.time() < epoch)@/
  7399. {
  7400. if(hasPrevious)@/
  7401. {
  7402. QTime jitBase(epoch.hour() - 1, epoch.minute(), epoch.second(),
  7403. epoch.msec());
  7404. QTime jitComp(epoch.hour(), measure.time().minute(),
  7405. measure.time().second(), measure.time().msec());
  7406. int relTime = jitBase.msecsTo(jitComp);
  7407. @<Produce and emit relative time@>@;
  7408. }
  7409. else@/
  7410. {
  7411. Measurement rel = measure;
  7412. rel.setTime(QTime(0, 0, 0, 0));
  7413. emit measurement(rel);
  7414. }
  7415. }
  7416. else@/
  7417. {
  7418. int relTime = epoch.msecsTo(measure.time());
  7419. @<Produce and emit relative time@>@;
  7420. }
  7421. hasPrevious = true;
  7422. previous = measure.time();@t\2@>@/
  7423. }
  7424. @ The measurement emitted has a time with the number of minutes, seconds, and
  7425. milliseconds since the start of the batch. We never generate a time greater
  7426. than 1 hour.
  7427. @<Produce and emit relative time@>=
  7428. QTime newTime(0, 0, 0, 0);
  7429. newTime = newTime.addMSecs(relTime);
  7430. if(newTime.hour() > 0)
  7431. {
  7432. newTime.setHMS(0, newTime.minute(), newTime.second(), newTime.msec());
  7433. }
  7434. Measurement rel = measure;
  7435. rel.setTime(newTime);
  7436. emit measurement(rel);
  7437. @ The rest of the code handles updating and reporting the reference time.
  7438. @<MeasurementTimeOffset Implementation@>=
  7439. MeasurementTimeOffset::MeasurementTimeOffset(QTime zero) : epoch(zero),
  7440. previous(0, 0, 0, 0), hasPrevious(false)
  7441. {
  7442. /* Nothing has to be done here. */
  7443. }
  7444. QTime MeasurementTimeOffset::zeroTime()
  7445. {
  7446. return epoch;
  7447. }
  7448. void MeasurementTimeOffset::setZeroTime(QTime zero)
  7449. {
  7450. epoch = zero;
  7451. hasPrevious = false;
  7452. }
  7453. @ Two functions are required to make this class available to the scripting
  7454. engine.
  7455. @<Function prototypes for scripting@>=
  7456. QScriptValue constructMeasurementTimeOffset(QScriptContext *context,@|
  7457. QScriptEngine *engine);
  7458. void setMeasurementTimeOffsetProperties(QScriptValue value,
  7459. QScriptEngine *engine);
  7460. @ The scripting engine must be informed of the constructor.
  7461. @<Set up the scripting engine@>=
  7462. constructor = engine->newFunction(constructMeasurementTimeOffset);
  7463. value = engine->newQMetaObject(&MeasurementTimeOffset::staticMetaObject,
  7464. constructor);
  7465. engine->globalObject().setProperty("MeasurementTimeOffset", value);
  7466. @ Previously, another property was added to the newly created object. That
  7467. method is believed to be obsolete and has been removed. Careful testing will
  7468. need to be done to verify that this decision was sane. I was very hungry when
  7469. that change was made.
  7470. @<Functions for scripting@>=
  7471. QScriptValue constructMeasurementTimeOffset(QScriptContext *,
  7472. QScriptEngine *engine)
  7473. {
  7474. QScriptValue object =@|
  7475. engine->newQObject(new MeasurementTimeOffset(QTime::currentTime()));
  7476. setMeasurementTimeOffsetProperties(object, engine);
  7477. return object;
  7478. }
  7479. void setMeasurementTimeOffsetProperties(QScriptValue value,
  7480. QScriptEngine *engine)
  7481. {
  7482. setQObjectProperties(value, engine);
  7483. }
  7484. @* Measured value threshold detection.
  7485. \noindent There are times when one might want to detect when a measured value
  7486. from a data series has passed a given value, with the limitation that we are
  7487. only interested in the ascending or descending edge. This can be used, for
  7488. example, to translate roast profile data in a graph along the time axis such
  7489. that the bean temperature series are aligned at a given
  7490. temperature.\nfnote{More details on the reasoning behind why one might want
  7491. to do this are provided at:\par\indent\pdfURL{http://youtu.be/hS0SfzypyFQ}
  7492. {http://youtu.be/hS0SfzypyFQ}} For this we can use a |ThresholdDetector|.
  7493. If we would like to catch changes on both the ascending and descending edge, we
  7494. can use two objects, however it may be a good idea to use more than two to
  7495. allow for sane behavior in the face of hysteresis.
  7496. @<Class declarations@>=
  7497. class ThresholdDetector : public QObject@/
  7498. {
  7499. @[Q_OBJECT@]@;
  7500. @[Q_ENUMS(EdgeDirection)@]@;
  7501. public:@/
  7502. enum EdgeDirection {
  7503. Ascending, Descending
  7504. };
  7505. ThresholdDetector(double value);
  7506. @[public slots@]:@/
  7507. void newMeasurement(Measurement measure);
  7508. void setThreshold(double value);
  7509. void setEdgeDirection(EdgeDirection direction);
  7510. signals:@/
  7511. void timeForValue(double);
  7512. private:@/
  7513. bool previousValueValid;
  7514. double previousValue;
  7515. double threshold;
  7516. EdgeDirection currentDirection;
  7517. };
  7518. @ This class emits the time in seconds when a given measurement crosses the
  7519. threshold value in the appropriate direction.
  7520. This was previously written with |previousValue| initialized negative and a
  7521. check that |previousValue| was non-negative. When the |ThresholdDetector| is
  7522. connected to a data source representing temperature measurements this is a
  7523. reasonable choice, however it breaks when connected to a rate of change series.
  7524. To make this more generally correct, a boolean is checked to determine if a
  7525. previous value has been set.
  7526. @<ThresholdDetector Implementation@>=
  7527. void ThresholdDetector::newMeasurement(Measurement measure)
  7528. {
  7529. if((currentDirection == Ascending && previousValue < threshold &&
  7530. previousValueValid) || (currentDirection == Descending &&
  7531. previousValue > threshold && previousValueValid))
  7532. {
  7533. if((currentDirection == Ascending && measure.temperature() >= threshold) ||
  7534. (currentDirection == Descending && measure.temperature() <= threshold))
  7535. {
  7536. double offset = measure.time().hour() * 60 * 60;
  7537. offset += measure.time().minute() * 60;
  7538. offset += measure.time().second();
  7539. offset += measure.time().msec()/1000;
  7540. emit timeForValue(offset);
  7541. }
  7542. }
  7543. previousValue = measure.temperature();
  7544. previousValueValid = true;
  7545. }
  7546. ThresholdDetector::ThresholdDetector(double value) : QObject(NULL),
  7547. previousValueValid(false),
  7548. previousValue(-1), threshold(value), currentDirection(Ascending)
  7549. {
  7550. /* Nothing needs to be done here. */
  7551. }
  7552. void ThresholdDetector::setThreshold(double value)
  7553. {
  7554. threshold = value;
  7555. }
  7556. void ThresholdDetector::setEdgeDirection(EdgeDirection direction)
  7557. {
  7558. currentDirection = direction;
  7559. }
  7560. @ This is exposed to the host environment.
  7561. @<Function prototypes for scripting@>=
  7562. QScriptValue constructThresholdDetector(QScriptContext *context, QScriptEngine *engine);
  7563. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine);
  7564. @ Inform the engine of the constructor.
  7565. @<Set up the scripting engine@>=
  7566. constructor = engine->newFunction(constructThresholdDetector);
  7567. value = engine->newQMetaObject(&ThresholdDetector::staticMetaObject, constructor);
  7568. engine->globalObject().setProperty("ThresholdDetector", value);
  7569. @ Implementation. At present I'@q'@>m not bothering to implement constructor
  7570. arguments here and am aligning on a fixed point. Another slot method was added
  7571. to restore adjustability.
  7572. @<Functions for scripting@>=
  7573. QScriptValue constructThresholdDetector(QScriptContext *, QScriptEngine *engine)
  7574. {
  7575. QScriptValue object = engine->newQObject(new ThresholdDetector(300));
  7576. return object;
  7577. }
  7578. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine)
  7579. {
  7580. setQObjectProperties(value, engine);
  7581. }
  7582. @* The ZeroEmitter class.
  7583. \noindent Now that it is possible to record the time a measurement was taken
  7584. relative to an arbitrary start time, there is a minor problem left for logging.
  7585. It is extremely unlikely that a measurement will be passed through at the epoch.
  7586. For this, what we want to do is save the previous measurement and make it
  7587. available at time 0 whenever the start time is reset. This is the role of the
  7588. |ZeroEmitter| class.
  7589. Another problem is that most classes that are interested in a relative time are
  7590. also interested in logging multiple sets of temperature data. To facilitate this
  7591. an integer is emitted. Different temperature measurement sources should be set
  7592. to emit different numbers. A table view would place measurements in the
  7593. indicated column. A graph view would use different colors to plot different sets
  7594. of data.
  7595. @<Class declarations@>=
  7596. class ZeroEmitter : public QObject@/
  7597. {@t\1@>@/
  7598. @[Q_OBJECT@]@;
  7599. @[Q_PROPERTY(int column READ column WRITE setColumn)@]@;
  7600. Measurement cache;
  7601. int col;
  7602. public:@/
  7603. ZeroEmitter(int tempcolumn = 1);
  7604. int column();
  7605. double lastTemperature();@/
  7606. @t\4@>public slots@t\kern-3pt@>:@;
  7607. void newMeasurement(Measurement measure);
  7608. void setColumn(int column);
  7609. void emitZero();
  7610. signals:@;
  7611. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  7612. }@t\kern-3pt@>;
  7613. @ The implementation of the class is trivial.
  7614. @<ZeroEmitter Implementation@>=
  7615. ZeroEmitter::ZeroEmitter(int tempcolumn) : QObject(NULL), col(tempcolumn)@;
  7616. {
  7617. /* Nothing has to be done here. */
  7618. }
  7619. int ZeroEmitter::column()
  7620. {
  7621. return col;
  7622. }
  7623. double ZeroEmitter::lastTemperature()
  7624. {
  7625. return cache.temperature();
  7626. }
  7627. void ZeroEmitter::newMeasurement(Measurement measure)
  7628. {
  7629. cache = measure;
  7630. }
  7631. void ZeroEmitter::setColumn(int column)
  7632. {
  7633. col = column;
  7634. }
  7635. void ZeroEmitter::emitZero()
  7636. {
  7637. cache.setTime(QTime(0, 0, 0, 0));
  7638. emit measurement(cache, col);
  7639. }
  7640. @ Making this class available to scripts requires only two functions.
  7641. @<Function prototypes for scripting@>=
  7642. QScriptValue constructZeroEmitter(QScriptContext *context,
  7643. QScriptEngine *engine);
  7644. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine);
  7645. @ To use it, we must inform the engine of the constructor.
  7646. @<Set up the scripting engine@>=
  7647. constructor = engine->newFunction(constructZeroEmitter);
  7648. value = engine->newQMetaObject(&ZeroEmitter::staticMetaObject, constructor);
  7649. engine->globalObject().setProperty("ZeroEmitter", value);
  7650. @ The implementation of the constructor is trivial.
  7651. @<Functions for scripting@>=
  7652. QScriptValue constructZeroEmitter(QScriptContext *context,
  7653. QScriptEngine *engine)
  7654. {
  7655. QScriptValue object =
  7656. engine->newQObject(new ZeroEmitter(argument<int>(0, context)));
  7657. setZeroEmitterProperties(object, engine);
  7658. return object;
  7659. }
  7660. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine)
  7661. {
  7662. setQObjectProperties(value, engine);
  7663. }
  7664. @* The MeasurementAdapter class.
  7665. \noindent The last of the measurement filter classes is the |MeasurementAdapter|
  7666. class. This takes measurements, typically from a |MeasurementTimeOffset|, and
  7667. sends the measurement out with a number to indicate which data series the
  7668. measurement belongs to.
  7669. The measurement pipeline could probably be made simpler by introducing a series
  7670. identifier into the measurement class.
  7671. @<Class declarations@>=
  7672. class MeasurementAdapter : public QObject@/
  7673. {@t\1@>@/
  7674. Q_OBJECT@;
  7675. int col;
  7676. public:@/
  7677. MeasurementAdapter(int tempcolumn);
  7678. int column();@/
  7679. @t\4@>public slots@t\kern-3pt@>:@/
  7680. void newMeasurement(Measurement measure);
  7681. void setColumn(int column);
  7682. signals:@/
  7683. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  7684. }@t\kern-3pt@>;
  7685. @ The implementation of this filter class is trivial.
  7686. @<MeasurementAdapter Implementation@>=
  7687. MeasurementAdapter::MeasurementAdapter(int tempcolumn) : col(tempcolumn)@;
  7688. {
  7689. /* Nothing has to be done here. */
  7690. }
  7691. int MeasurementAdapter::column()
  7692. {
  7693. return col;
  7694. }
  7695. void MeasurementAdapter::newMeasurement(Measurement measure)
  7696. {
  7697. emit measurement(measure, col);
  7698. }
  7699. void MeasurementAdapter::setColumn(int column)
  7700. {
  7701. col = column;
  7702. }
  7703. @ This filter class is also available from the host environment.
  7704. @<Function prototypes for scripting@>=
  7705. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  7706. QScriptEngine *engine);
  7707. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine);
  7708. @ As usual, the engine must be informed of the constructor.
  7709. @<Set up the scripting engine@>=
  7710. constructor = engine->newFunction(constructMeasurementAdapter);
  7711. value = engine->newQMetaObject(&MeasurementAdapter::staticMetaObject,
  7712. constructor);
  7713. engine->globalObject().setProperty("MeasurementAdapter", value);
  7714. @ The implementation is trivial.
  7715. @<Functions for scripting@>=
  7716. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  7717. QScriptEngine *engine)
  7718. {
  7719. QScriptValue object =
  7720. engine->newQObject(new MeasurementAdapter(argument<int>(0, context)));
  7721. setMeasurementAdapterProperties(object, engine);
  7722. return object;
  7723. }
  7724. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine)
  7725. {
  7726. setQObjectProperties(value, engine);
  7727. }
  7728. @* A graph of temperature over time.
  7729. \noindent A useful tool when roasting is a visual depiction of the current batch
  7730. as it happens, possibly laid over a previously recorded target profile. The
  7731. |GraphView| class can take multiple sets of temperature data and produce such a
  7732. visualization.
  7733. \medskip
  7734. \centerline{\includegraphics{roast}}
  7735. \smallskip
  7736. \centerline{Figure \secno: A Typical Roast}
  7737. \medskip
  7738. This class assumes that temperature data will be passed in the correct order.
  7739. @<Class declarations@>=
  7740. class GraphView : public QGraphicsView@/
  7741. {@t\1@>@/
  7742. Q_OBJECT@;
  7743. QGraphicsScene *theScene;@/
  7744. QMap<int, QList<QGraphicsLineItem * > * > *graphLines;@/
  7745. QMap<int, QPointF> *prevPoints;
  7746. QMap<int, double> *translations;
  7747. QList<QGraphicsItem *> *gridLinesF;
  7748. QList<QGraphicsItem *> *gridLinesC;
  7749. QList<QGraphicsItem *> *relativeGridLines;
  7750. bool relativeEnabled;
  7751. bool timeIndicatorEnabled;
  7752. QGraphicsLineItem *timeLine;
  7753. LinearSplineInterpolator *relativeAdjuster;@/
  7754. public:@/
  7755. GraphView(QWidget *parent = NULL);
  7756. void removeSeries(int column);@/
  7757. protected:@/
  7758. void resizeEvent(QResizeEvent *event);@/
  7759. @t\4@>public slots@t\kern-3pt@>:@/
  7760. void newMeasurement(Measurement measure, int tempcolumn);
  7761. void setSeriesTranslation(int column, double offset);
  7762. void setTimeIndicatorEnabled(bool enabled);
  7763. void clear();
  7764. void showF();
  7765. void showC();@t\2@>@/
  7766. }@t\kern-3pt@>;
  7767. @ I decided that it would probably be best to keep the graph area the same even
  7768. with different roast lengths over different temperature ranges so that similar
  7769. portions between these graphs would continue to look similar rather than
  7770. constantly attempting to select the best way to display the data currently in
  7771. the view.
  7772. I have chosen to represent roasting times of up to 20 minutes and temperatures
  7773. between 0 and 500$^\circ$ Fahrenheit. This should certainly be configurable at
  7774. run time, but until that is implemented, roasters who routinely roast batches
  7775. for longer periods of time will want to change the constructor. This class
  7776. should probably be modified to allow the user to specify several characteristics
  7777. of the display.
  7778. This class must also deal with the fact that coordinates in a |QGraphicsScene|
  7779. are not quite the same as coordinates in a cartesian plane. The easiest way to
  7780. deal with this is to negate the y coordinate and translate the viewport to the
  7781. area we draw in.
  7782. A small margin area left around the edges of the graph. This should probably be
  7783. configurable for those with particularly small displays.
  7784. @<GraphView Implementation@>=
  7785. GraphView::GraphView(QWidget *parent) : QGraphicsView(parent),
  7786. theScene(new QGraphicsScene),@/
  7787. graphLines(new QMap<int, QList<QGraphicsLineItem *> *>),@/
  7788. prevPoints(new QMap<int, QPointF>),
  7789. translations(new QMap<int, double>),
  7790. gridLinesF(new QList<QGraphicsItem *>),
  7791. gridLinesC(new QList<QGraphicsItem *>),
  7792. relativeGridLines(new QList<QGraphicsItem *>),
  7793. relativeEnabled(false),
  7794. timeIndicatorEnabled(false),
  7795. timeLine(new QGraphicsLineItem),
  7796. relativeAdjuster(new LinearSplineInterpolator)@/
  7797. {
  7798. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  7799. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  7800. setScene(theScene);
  7801. setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
  7802. QPen timePen;
  7803. timePen.setColor(QColor(160, 160, 164, 127)); //gray, half opacity
  7804. timeLine->setPen(timePen);
  7805. timeLine->setLine(0, 0, 0, -500);
  7806. timeLine->hide();
  7807. theScene->addItem(timeLine);
  7808. @<Draw temperature axis and grid lines@>;
  7809. @<Draw secondary axes@>@;
  7810. @<Draw time axis and ticks@>;
  7811. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  7812. }
  7813. @ Grid lines are drawn every 100 degrees. These lines are labeled with
  7814. |setHtml()| for convenient access to the $^\circ$ symbol. If \pn{} is modified
  7815. to allow different units, this code should also be modified.
  7816. As of version 1.3.3 it is possible to switch the graph between degrees
  7817. Fahrenheit and degrees Celcius. Celcius grid lines are drawn but initially
  7818. hidden. Both the grid lines and the labels are added to a list depending on the
  7819. unit so that when changing from one view to another all that needs to happen is
  7820. hide one list of items and show another.
  7821. @<Draw temperature axis and grid lines@>=
  7822. QGraphicsLineItem *tempaxis = new QGraphicsLineItem;
  7823. tempaxis->setLine(-10, -500, -10, 0);
  7824. theScene->addItem(tempaxis);
  7825. QGraphicsLineItem *gridLine;
  7826. QGraphicsTextItem *label;
  7827. for(int y = -100; y > -600; y -= 100)@/
  7828. {@/
  7829. gridLine = new QGraphicsLineItem;
  7830. gridLine->setLine(0, y, 1200, y);
  7831. theScene->addItem(gridLine);
  7832. label = new QGraphicsTextItem;
  7833. label->setHtml(QString("%1&deg;F").arg(-y));
  7834. label->setPos(-55, y - (label->boundingRect().height() / 2));
  7835. theScene->addItem(label);
  7836. gridLinesF->append(gridLine);
  7837. gridLinesF->append(label);
  7838. }
  7839. for(int degC = 50; degC <= 250; degC += 50)
  7840. {
  7841. gridLine = new QGraphicsLineItem;
  7842. int y = -(degC * (9.0/5.0) + 32);
  7843. gridLine->setLine(0, y, 1200, y);
  7844. gridLine->hide();
  7845. theScene->addItem(gridLine);
  7846. gridLinesC->append(gridLine);
  7847. label = new QGraphicsTextItem;
  7848. label->setHtml(QString("%1&deg;C").arg(degC));
  7849. label->setPos(-55, y - (label->boundingRect().height() / 2));
  7850. label->hide();
  7851. theScene->addItem(label);
  7852. gridLinesC->append(label);
  7853. }
  7854. @ If we are going to plot relative temperature measurements, we must obtain
  7855. information on how we wish to do that from settings. We take advantage of the
  7856. fact that iterating over the keys in a |QMap| produces results in sorted order.
  7857. While drawing the grid lines we also set up the |relativeAdjuster| that will be
  7858. used to transform incoming measurements to our coordinate system.
  7859. @<Draw secondary axes@>=
  7860. QSettings settings;
  7861. if(settings.contains("settings/graph/relative/enable"))
  7862. {
  7863. if(settings.value("settings/graph/relative/enable").toBool())
  7864. {
  7865. relativeEnabled = @[true@];
  7866. QColor relativeColor = QColor(settings.value("settings/graph/relative/color").toString());
  7867. QString unit = QString(settings.value(@|"settings/graph/relative/unit").toInt() == 0 ? "F" : "C");
  7868. QMap<double, QString> relativeAxisPairs;
  7869. QStringList relativeAxisLabels = settings.value(@|"settings/graph/relative/grid").toString().split(QRegExp("[\\s,]+"), QString::SkipEmptyParts);
  7870. foreach(QString item, relativeAxisLabels)
  7871. {
  7872. relativeAxisPairs.insert(item.toDouble(), item);
  7873. }
  7874. if(relativeAxisPairs.size() > 1)
  7875. {
  7876. double skip = 500.0 / (relativeAxisPairs.size() - 1);
  7877. double y = 0;
  7878. foreach(double key, relativeAxisPairs.keys())
  7879. {
  7880. gridLine = new QGraphicsLineItem;
  7881. gridLine->setLine(0, y, 1205, y);
  7882. gridLine->setPen(QPen(relativeColor));
  7883. theScene->addItem(gridLine);
  7884. relativeGridLines->append(gridLine);
  7885. label = new QGraphicsTextItem;
  7886. label->setHtml(QString("%1&deg;%2").arg(relativeAxisPairs.value(key)).arg(unit));
  7887. label->setPos(1210, y - (label->boundingRect().height() / 2));
  7888. theScene->addItem(label);
  7889. relativeGridLines->append(label);
  7890. if(unit == "F")
  7891. {
  7892. relativeAdjuster->add_pair(key, -y);
  7893. }
  7894. else
  7895. {
  7896. relativeAdjuster->add_pair(key * (9.0/5.0), -y);
  7897. }
  7898. y -= skip;
  7899. }
  7900. }
  7901. }
  7902. }
  7903. @ Two slots are used to switch between the different sets of grid lines.
  7904. @<GraphView Implementation@>=
  7905. void GraphView::showF()
  7906. {
  7907. for(int i = 0; i < gridLinesF->size(); i++)
  7908. {
  7909. gridLinesF->at(i)->show();
  7910. }
  7911. for(int i = 0; i < gridLinesC->size(); i++)
  7912. {
  7913. gridLinesC->at(i)->hide();
  7914. }
  7915. }
  7916. void GraphView::showC()
  7917. {
  7918. for(int i = 0; i < gridLinesF->size(); i++)
  7919. {
  7920. gridLinesF->at(i)->hide();
  7921. }
  7922. for(int i = 0; i < gridLinesC->size(); i++)
  7923. {
  7924. gridLinesC->at(i)->show();
  7925. }
  7926. }
  7927. @ The time axis has a tick every two minutes. The use of the |?| tertiary
  7928. operator shifts the labels with two digits a little more than labels with only
  7929. one digit. If it worked, a more resilient approach would be to take the width of
  7930. the label and center it under the tick.
  7931. @<Draw time axis and ticks@>=
  7932. QGraphicsLineItem *timeaxis = new QGraphicsLineItem;
  7933. timeaxis->setLine(0, 10, 1200, 10);
  7934. theScene->addItem(timeaxis);
  7935. for(int x = 0; x < 1201; x += 120)@/
  7936. {@/
  7937. QGraphicsLineItem *tick = new QGraphicsLineItem;
  7938. tick->setLine(x, 0, x, 20);
  7939. theScene->addItem(tick);
  7940. QGraphicsTextItem *label = new QGraphicsTextItem;
  7941. label->setPlainText(QString("%1").arg(x/60));
  7942. label->setPos(x - (label->boundingRect().width() / 2), 20);
  7943. theScene->addItem(label);
  7944. }
  7945. @ Typically, the user will be able to resize the graph. When the widget is
  7946. resized, we should fit the graph to the new size of the widget. This is safe to
  7947. do as we have already turned off the scroll bars.
  7948. @<GraphView Implementation@>=
  7949. void GraphView::resizeEvent(QResizeEvent *)
  7950. {
  7951. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  7952. }
  7953. @ When adding a new measurement, there are three cases that should be
  7954. considered. In the case of the first measurement, no drawing occurs. A |QList|
  7955. of line items is initialized when the second measurement is taken. Subsequent
  7956. measurements are able to simply append new line segments to the list.
  7957. Relative measurements are first converted to the coordinate system of the
  7958. appropriate secondary axis.
  7959. @<GraphView Implementation@>=
  7960. #define FULLTIMETOINT(t) (t.msec() + (t.second() * 1000) + (t.minute() * 60 * 1000))
  7961. void GraphView::newMeasurement(Measurement measure, int tempcolumn)@/
  7962. {@/
  7963. double offset = 0;
  7964. if(measure.contains("relative"))
  7965. {
  7966. if(measure.value("relative").toBool())
  7967. {
  7968. if(relativeEnabled)
  7969. {
  7970. measure.setTemperature(relativeAdjuster->newMeasurement(measure).temperature());
  7971. }
  7972. else
  7973. {
  7974. return;
  7975. }
  7976. }
  7977. }
  7978. if(translations->contains(tempcolumn))
  7979. {
  7980. offset = translations->value(tempcolumn);
  7981. }
  7982. if(prevPoints->contains(tempcolumn))@/
  7983. @t\1@>{@/
  7984. @<At least one measurement exists@>@;
  7985. if(graphLines->contains(tempcolumn))@/
  7986. {@t\1@>
  7987. /* More than one measurement existed. */
  7988. graphLines->value(tempcolumn)->append(segment);@t\2@>@/
  7989. }@/
  7990. else@/
  7991. {@/
  7992. /* This is the second measurement. */
  7993. QList<QGraphicsLineItem *> *newLine =
  7994. new QList<QGraphicsLineItem *>;@/
  7995. newLine->append(segment);
  7996. graphLines->insert(tempcolumn, newLine);
  7997. }@t\2@>@/
  7998. }@/
  7999. else@/
  8000. {@/
  8001. @<Handle the first measurement@>@;
  8002. }
  8003. }
  8004. @ There are some parts of the code that are correct, but seem somewhat goofy.
  8005. This is especially true surrounding the graphics view architecture as this was
  8006. not working correctly when I wrote the code that uses it. The code as it is
  8007. written works for me, but when these workarounds are no longer needed it would
  8008. be better to remove them. Handling values on the time axis is one example of
  8009. this.
  8010. Some might question the use of an integer data type, particularly when storing
  8011. the result of a division operation. While this could be a concern if high
  8012. resolution wall sized displays become common, is is expected that in most cases
  8013. with sufficiently high sample rates, many data points will map to the same pixel
  8014. even with the minor data loss below.
  8015. In the case of the first measurement,
  8016. @<Handle the first measurement@>=
  8017. int x = FULLTIMETOINT(measure.time())/1000;
  8018. prevPoints->insert(tempcolumn, QPointF(x, measure.temperature()));
  8019. if(timeIndicatorEnabled)
  8020. {
  8021. timeLine->setLine(x, 0, x, -500);
  8022. }
  8023. @ When at least one measurement already exists, we need to handle drawing the
  8024. line between the new measurement and the previous measurement.
  8025. \danger At present, the color chosen for these lines is based on the temperature
  8026. column passed to the graph. It would be better if colors could be passed to the
  8027. view for a specified series rather than have this hard coded. \endanger
  8028. @<At least one measurement exists@>=
  8029. QGraphicsLineItem *segment = new QGraphicsLineItem;
  8030. QPointF nextPoint(FULLTIMETOINT(measure.time())/1000, measure.temperature());
  8031. segment->setLine(prevPoints->value(tempcolumn).x() + offset,
  8032. -(prevPoints->value(tempcolumn).y()),
  8033. nextPoint.x() + offset, -(nextPoint.y()));
  8034. static QColor p[12] = {Qt::yellow, Qt::blue, Qt::cyan, Qt::red, Qt::magenta,
  8035. Qt::green, Qt::darkGreen, Qt::darkMagenta,
  8036. Qt::darkRed, Qt::darkCyan, Qt::darkBlue,
  8037. Qt::darkYellow};
  8038. segment->setPen(p[tempcolumn % 12]);
  8039. theScene->addItem(segment);
  8040. prevPoints->insert(tempcolumn, nextPoint);
  8041. if(timeIndicatorEnabled)
  8042. {
  8043. timeLine->setLine(nextPoint.x() + offset, 0, nextPoint.x() + offset, -500);
  8044. }
  8045. @ In addition to adding data to the view, we also sometimes want to clear the
  8046. view of data.
  8047. @<GraphView Implementation@>=
  8048. void GraphView::clear()
  8049. {
  8050. int i;
  8051. foreach(i, prevPoints->keys())
  8052. {
  8053. removeSeries(i);
  8054. }
  8055. translations->clear();
  8056. }
  8057. @ Removing a set of data from the view involves removing the lines from the
  8058. scene and removing the column from a couple data structures.
  8059. @<GraphView Implementation@>=
  8060. void GraphView::removeSeries(int column)
  8061. {
  8062. if(graphLines->contains(column))
  8063. {
  8064. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  8065. QGraphicsLineItem *segment;
  8066. foreach(segment, *series)
  8067. {
  8068. theScene->removeItem(segment);
  8069. }
  8070. qDeleteAll(*series);
  8071. }
  8072. graphLines->remove(column);
  8073. prevPoints->remove(column);
  8074. }
  8075. @ Second prototype for data series translation.
  8076. @<GraphView Implementation@>=
  8077. void GraphView::setSeriesTranslation(int column, double offset)
  8078. {
  8079. if(graphLines->contains(column))
  8080. {
  8081. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  8082. QGraphicsLineItem *segment;
  8083. foreach(segment, *series)
  8084. {
  8085. segment->setPos(segment->pos().x()+offset, segment->pos().y());
  8086. }
  8087. }
  8088. if(translations->contains(column))
  8089. {
  8090. translations->insert(column, offset + translations->value(column));
  8091. }
  8092. else
  8093. {
  8094. translations->insert(column, offset);
  8095. }
  8096. }
  8097. @ Starting in \pn{} 1.6 it is possible to add a vertical line indicating the
  8098. time position of the most recent measurement. This should be hidden for loading
  8099. target roast profiles and shown depending on preference. A new method controls
  8100. this.
  8101. @<GraphView Implementation@>=
  8102. void GraphView::setTimeIndicatorEnabled(bool enabled)
  8103. {
  8104. timeIndicatorEnabled = enabled;
  8105. if(enabled)
  8106. {
  8107. timeLine->show();
  8108. }
  8109. else
  8110. {
  8111. timeLine->hide();
  8112. }
  8113. }
  8114. @ These functions are required to create a |GraphView| object from a script.
  8115. @<Function prototypes for scripting@>=
  8116. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine);
  8117. QScriptValue constructGraphView(QScriptContext *context, QScriptEngine *engine);
  8118. @ The scripting engine must be informed of the constructor.
  8119. @<Set up the scripting engine@>=
  8120. constructor = engine->newFunction(constructGraphView);
  8121. value = engine->newQMetaObject(&GraphView::staticMetaObject, constructor);
  8122. engine->globalObject().setProperty("GraphView", value);
  8123. @ The function implementation is trivial.
  8124. @<Functions for scripting@>=
  8125. QScriptValue constructGraphView(QScriptContext *, QScriptEngine *engine)
  8126. {
  8127. QScriptValue object = engine->newQObject(new GraphView);
  8128. setGraphViewProperties(object, engine);
  8129. return object;
  8130. }
  8131. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine)
  8132. {
  8133. setQGraphicsViewProperties(value, engine);
  8134. }
  8135. @* A table of roasting data.
  8136. \noindent A typical roast log is a table listing temperature measurements taken
  8137. at regular intervals. The introduction of a computer brings several advantages.
  8138. A human does not need to record the measurements. Every measurement taken can be
  8139. logged, but the measurements do not all need to be displayed. The |ZoomLog|
  8140. class presents a table with time, temperature, and annotation for one or more
  8141. sets of roasting data and allows the user to select from a few different levels
  8142. of detail.
  8143. Experience has shown that one measurement every 30 or 15 seconds is most useful,
  8144. but it is also possible to view one measurement every 1, 5, 10, or 60 seconds
  8145. and there is an option to view every measurement collected. This last is what is
  8146. saved to a file.
  8147. The zooming log is implemented by keeping a measurement model with every level
  8148. of detail of interest and making sure that new measurements get to the models
  8149. they belong in. Switching the level of detail of the view then becomes a matter
  8150. of changing which model the view is using. This is very inefficient in terms of
  8151. space, but it is very fast and simple to code.
  8152. Starting in version 1.4, column sizes are persisted automatically using the
  8153. same method as described in the section on |SqlQueryView|.
  8154. Starting in version 1.8, |rowCount()| is |Q_INVOKABLE|. This allows the manual
  8155. log entry interface to easily determine if any roasting data exists to save.
  8156. @<Class declarations@>=
  8157. class MeasurementModel;@/
  8158. class ZoomLog : public QTableView@/
  8159. {@/
  8160. @[Q_OBJECT@]@;
  8161. @<ZoomLog private member data@>@;
  8162. void switchLOD(MeasurementModel *m);@/
  8163. @[private slots@]:@/
  8164. void centerOn(int row);
  8165. void persistColumnResize(int column, int oldsize, int newsize);
  8166. void restoreColumnWidths();
  8167. public:@/
  8168. ZoomLog();
  8169. QVariant data(int row, int column) const;
  8170. @[Q_INVOKABLE@,@, int rowCount();
  8171. bool saveXML(QIODevice *device);
  8172. bool saveCSV(QIODevice *device);
  8173. QString lastTime(int series);
  8174. @[Q_INVOKABLE@,@, Units::Unit displayUnits()@];@t\2\2@>@/
  8175. @[public slots@]:@/
  8176. void setVisible(bool visibility);
  8177. void setHeaderData(int section, QString text);
  8178. void LOD_ms();
  8179. void LOD_1s();
  8180. void LOD_5s();
  8181. void LOD_10s();
  8182. void LOD_15s();
  8183. void LOD_30s();
  8184. void LOD_1m();
  8185. void newMeasurement(Measurement measure, int tempcolumn);
  8186. void newAnnotation(QString annotation, int tempcolumn,
  8187. int annotationcolumn);
  8188. void clear();
  8189. void addOutputTemperatureColumn(int column);
  8190. void addOutputControlColumn(int column);
  8191. void addOutputAnnotationColumn(int column);
  8192. void clearOutputColumns();
  8193. void setDisplayUnits(Units::Unit scale);
  8194. void addToCurrentColumnSet(int column);
  8195. void clearCurrentColumnSet();@/
  8196. protected:@/
  8197. virtual void showEvent(QShowEvent *event);
  8198. };
  8199. @ This class uses a different model for each level of detail and provides logic
  8200. for placing measurements and annotations in the appropriate models. A list of
  8201. each model is provided for conveniently performing operations that apply to
  8202. every model.
  8203. @<ZoomLog private member data@>=
  8204. MeasurementModel *model_ms;
  8205. MeasurementModel *model_1s;
  8206. MeasurementModel *model_5s;
  8207. MeasurementModel *model_10s;
  8208. MeasurementModel *model_15s;
  8209. MeasurementModel *model_30s;
  8210. MeasurementModel *model_1m;
  8211. QList<MeasurementModel *> modelSet;
  8212. QHash<int, Measurement> lastMeasurement;
  8213. MeasurementModel *currentModel;
  8214. QList<int> saveTempCols;
  8215. QList<int> saveControlCols;
  8216. QList<int> saveNoteCols;
  8217. QList<int> currentColumnSet;
  8218. @ Most of the functionality this class provides is in getting measurements to
  8219. the right models. Every measurement goes to the full detail model. We also keep
  8220. track of the most recent measurement to detect the first measurement in a new
  8221. second and pass all of these on to the 1 second level of detail model. Some of
  8222. these are also passed to other models. Additionally, the models that store
  8223. coarser data strip the millisecond portion of the time.
  8224. A decision was made to present data promptly. With a high sample rate, some
  8225. might prefer an average of a few measurements near the reported time, but such
  8226. a feature does not exist in \pn{} currently.
  8227. The first measurement is always added to each model.
  8228. @<ZoomLog Implementation@>=
  8229. void ZoomLog::newMeasurement(Measurement measure, int tempcolumn)
  8230. {
  8231. if(measure.time() != QTime(0, 0, 0, 0))
  8232. {
  8233. @<Synthesize measurements for slow hardware@>@;
  8234. }
  8235. model_ms->newMeasurement(measure, tempcolumn);
  8236. if(lastMeasurement.contains(tempcolumn))
  8237. {
  8238. if(measure.time().second() !=
  8239. lastMeasurement.value(tempcolumn).time().second())
  8240. {
  8241. Measurement adjusted = measure;
  8242. QTime adjtime(0, measure.time().minute(), measure.time().second(), 0);
  8243. adjusted.setTime(adjtime);
  8244. model_1s->newMeasurement(adjusted, tempcolumn);
  8245. if(adjusted.time().second() % 5 == 0)
  8246. {
  8247. model_5s->newMeasurement(adjusted, tempcolumn);
  8248. if(adjusted.time().second() % 10 == 0)
  8249. {
  8250. model_10s->newMeasurement(adjusted, tempcolumn);
  8251. }
  8252. if(adjusted.time().second() % 15 == 0)
  8253. {
  8254. model_15s->newMeasurement(adjusted, tempcolumn);
  8255. if(adjusted.time().second() % 30 == 0)
  8256. {
  8257. model_30s->newMeasurement(adjusted, tempcolumn);
  8258. if(adjusted.time().second() == 0)
  8259. {
  8260. model_1m->newMeasurement(adjusted, tempcolumn);
  8261. }
  8262. }
  8263. }
  8264. }
  8265. }
  8266. @<Synthesize measurements for columns in set@>@;
  8267. }
  8268. else
  8269. {
  8270. @<Add the first measurement to every model@>@;
  8271. }
  8272. lastMeasurement.insert(tempcolumn, measure);
  8273. }
  8274. @ The first measurement in a series should be the epoch measurement. This
  8275. should exist in every level of detail.
  8276. @<Add the first measurement to every model@>=
  8277. MeasurementModel *m;
  8278. foreach(m, modelSet)
  8279. {
  8280. m->newMeasurement(measure, tempcolumn);
  8281. }
  8282. @ Some measurement hardware in use cannot guarantee delivery of at least one
  8283. measurement per second. This causes problems for the current |ZoomLog|
  8284. implementation as, for example, if there is no measurement at a time where
  8285. the seconds are divisible by 5, there will be no entry in that view. This can
  8286. result in situations where the |ZoomLog| at its default view of one measurement
  8287. every 30 seconds might not display any data at all aside from the first
  8288. measurement, the last measurement, and any measurement that happens to have an
  8289. annotation associated with it. The solution in this case is to synthesize
  8290. measurements so that the |ZoomLog| thinks it gets at least one measurement
  8291. every second.
  8292. Prior to version 1.8 this simply replicated the last measurement every second
  8293. until the time for the most recent measurement was reached, however this yields
  8294. problematic results when loading saved data or attempting to use this view for
  8295. manual data entry. The current behavior performs a linear interpolation which
  8296. will match the graph.
  8297. @<Synthesize measurements for slow hardware@>=
  8298. if(lastMeasurement.contains(tempcolumn))
  8299. {
  8300. if(lastMeasurement[tempcolumn].time() < measure.time())
  8301. {
  8302. QList<QTime> timelist;
  8303. QList<double> templist;
  8304. QTime z = QTime(0, 0, 0, 0);
  8305. double ptime = (double)(z.secsTo(lastMeasurement[tempcolumn].time()));
  8306. double ptemp = lastMeasurement[tempcolumn].temperature();
  8307. double ctime = (double)(z.secsTo(measure.time()));
  8308. double ctemp = measure.temperature();
  8309. for(QTime i = lastMeasurement.value(tempcolumn).time().addSecs(1); i < measure.time(); i = i.addSecs(1))
  8310. {
  8311. timelist.append(i);
  8312. double v = ((ptemp * (ctime - z.secsTo(i))) + (ctemp * (z.secsTo(i) - ptime))) / (ctime - ptime);
  8313. templist.append(v);
  8314. }
  8315. for(int i = 0; i < timelist.size(); i++)
  8316. {
  8317. Measurement synthesized = measure;
  8318. synthesized.setTime(timelist[i]);
  8319. synthesized.setTemperature(templist[i]);
  8320. newMeasurement(synthesized, tempcolumn);
  8321. }
  8322. }
  8323. }
  8324. @ New to \pn{} 1.4 is the concept of a current column set. This was added to
  8325. improve support for devices where measurements on different data series may not
  8326. arrive at exactly the same time and for multi-device configurations where
  8327. measurements from different devices are unlikely to arrive at the same time.
  8328. This can cause issues with log annotations and serialization. The solution is
  8329. to group all columns that are logically part of the same data acquisition
  8330. process and as measurements come in, the most recent measurement from other
  8331. columns can be duplicated at the new time. Two methods are responsible for
  8332. managing this measurement set. One adds a column to the set and the other
  8333. removes all columns from the set.
  8334. @<ZoomLog Implementation@>=
  8335. void ZoomLog::addToCurrentColumnSet(int column)
  8336. {
  8337. currentColumnSet.append(column);
  8338. }
  8339. void ZoomLog::clearCurrentColumnSet()
  8340. {
  8341. currentColumnSet.clear();
  8342. }
  8343. @ Replicating the measurements occurs as measurements are delivered. Note
  8344. that this code will not be called for the first measurement in each column.
  8345. @<Synthesize measurements for columns in set@>=
  8346. if(currentColumnSet.contains(tempcolumn))
  8347. {
  8348. int replicationcolumn;
  8349. foreach(replicationcolumn, currentColumnSet)
  8350. {
  8351. if(replicationcolumn != tempcolumn)
  8352. {
  8353. if(lastMeasurement.contains(replicationcolumn))
  8354. {
  8355. if(measure.time() > lastMeasurement.value(replicationcolumn).time())
  8356. {
  8357. Measurement synthetic = lastMeasurement.value(replicationcolumn);
  8358. synthetic.setTime(measure.time());
  8359. model_ms->newMeasurement(synthetic, replicationcolumn);
  8360. if(synthetic.time().second() != lastMeasurement.value(replicationcolumn).time().second())@/
  8361. {
  8362. Measurement adjusted = synthetic;
  8363. adjusted.setTime(QTime(0, synthetic.time().minute(), synthetic.time().second(), 0));
  8364. model_1s->newMeasurement(adjusted, replicationcolumn);
  8365. if(adjusted.time().second() % 5 == 0)
  8366. {
  8367. model_5s->newMeasurement(adjusted, replicationcolumn);
  8368. if(adjusted.time().second() % 10 == 0)
  8369. {
  8370. model_10s->newMeasurement(adjusted, replicationcolumn);
  8371. }
  8372. if(adjusted.time().second() % 15 == 0)
  8373. {
  8374. model_15s->newMeasurement(adjusted, replicationcolumn);
  8375. if(adjusted.time().second() % 30 == 0)
  8376. {
  8377. model_30s->newMeasurement(adjusted, replicationcolumn);
  8378. if(adjusted.time().second() == 0)
  8379. {
  8380. model_1m->newMeasurement(adjusted, replicationcolumn);
  8381. }
  8382. }
  8383. }
  8384. }
  8385. }
  8386. lastMeasurement[replicationcolumn] = synthetic;
  8387. }
  8388. }
  8389. }
  8390. }
  8391. }
  8392. @ Just as the first measurement should exist at every level of detail, so should
  8393. any annotations. The measurement models will, when presented with an annotation,
  8394. apply it to the most recently entered measurement in the specified data series.
  8395. This presents a problem for the coarser views as the data point the annotation
  8396. belongs to most likely does not exist in that view. Furthermore, the model as it
  8397. is currently written will overwrite annotations that already exist on a
  8398. measurement if it is still the most recently entered. When collecting samples
  8399. during profile development, it is common to produce several annotations in a
  8400. short amount of time. The most useful thing to do in such a case is to add the
  8401. most recent measurement to each model and then apply the annotation. This, of
  8402. course, should only be done if there is a most recent measurement. An annotation
  8403. regarding the starting condition of the roaster should apply to the yet to be
  8404. recorded time zero measurement.
  8405. Note that only the value from the temperature column specified is displayed in
  8406. the row with the annotation. It would be better to check the full detail model
  8407. to determine if there are other measurements at the annotation time and present
  8408. these as well. Another possibility in the case of data not existing in other
  8409. temperature columns would be to interpolate a value from the existing data in
  8410. these columns, however this is potentially challenging as I would want to keep
  8411. true measurements distinct from estimations.
  8412. @<ZoomLog Implementation@>=
  8413. void ZoomLog::newAnnotation(QString annotation, int tempcolumn,
  8414. int annotationcolumn)
  8415. {
  8416. model_ms->newAnnotation(annotation, tempcolumn, annotationcolumn);
  8417. MeasurementModel *m;
  8418. if(lastMeasurement.contains(tempcolumn))
  8419. {
  8420. foreach(m, modelSet)
  8421. {
  8422. m->newMeasurement(lastMeasurement.value(tempcolumn), tempcolumn);
  8423. }
  8424. }
  8425. foreach(m, modelSet)
  8426. {
  8427. m->newAnnotation(annotation, tempcolumn, annotationcolumn);
  8428. }
  8429. }
  8430. @ As measurements are added to the model, the model will emit rowChanged
  8431. signals. These signals are connected to a function here that will attempt to
  8432. scroll the view to keep the most recently entered data in the center of the
  8433. view.
  8434. @<ZoomLog Implementation@>=
  8435. void ZoomLog::centerOn(int row)
  8436. {
  8437. scrollTo(currentModel->index(row, 0), QAbstractItemView::PositionAtCenter);
  8438. }
  8439. @ Once we are done with the data in the table, we want to clear it to prepare
  8440. for new data. This also clears the lists holding the output columns to use when
  8441. saving data.
  8442. @<ZoomLog Implementation@>=
  8443. void ZoomLog::clear()
  8444. {
  8445. MeasurementModel *m;
  8446. foreach(m, modelSet)
  8447. {
  8448. m->clear();
  8449. }
  8450. lastMeasurement.clear();
  8451. saveTempCols.clear();
  8452. saveControlCols.clear();
  8453. saveNoteCols.clear();
  8454. }
  8455. @ These are depreciated methods originally written to assist in serializing
  8456. model data prior to the introduction of the |XMLOutput| class. These methods are
  8457. likely to be removed in a future version of the program.
  8458. @<ZoomLog Implementation@>=
  8459. QVariant ZoomLog::data(int row, int column) const
  8460. {
  8461. return model_ms->data(model_ms->index(row, column, QModelIndex()),
  8462. Qt::DisplayRole);
  8463. }
  8464. int ZoomLog::rowCount()
  8465. {
  8466. return model_ms->rowCount();
  8467. }
  8468. @ This method initializes an |XMLOutput| instance, passes the columns that we
  8469. would like to save to that object, and uses it to write an XML file with the
  8470. desired data to the specified device.
  8471. Since the output format does not currently specify a unit, there is an
  8472. assumption that the XML output will always have measurements in Fahrenheit. If
  8473. the model is not currently displaying measurements in Fahrenheit, it is asked to
  8474. do so before writing the XML data. User preference is restored after the XML
  8475. data has been written. Since this change is only performed on |model_ms|, most
  8476. users will never notice this.
  8477. @<ZoomLog Implementation@>=
  8478. bool ZoomLog::saveXML(QIODevice *device)
  8479. {
  8480. Units::Unit prevUnits = model_ms->displayUnits();
  8481. if(prevUnits != Units::Fahrenheit)
  8482. {
  8483. model_ms->setDisplayUnits(Units::Fahrenheit);
  8484. }
  8485. XMLOutput writer(model_ms, device, 0);
  8486. int c;
  8487. foreach(c, saveTempCols)
  8488. {
  8489. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  8490. toString(), c);
  8491. }
  8492. foreach(c, saveControlCols)
  8493. {
  8494. writer.addControlColumn(model_ms->headerData(c, Qt::Horizontal).
  8495. toString(), c);
  8496. }
  8497. foreach(c, saveNoteCols)
  8498. {
  8499. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  8500. toString(), c);
  8501. }
  8502. bool retval = writer.output();
  8503. if(prevUnits != Units::Fahrenheit)
  8504. {
  8505. model_ms->setDisplayUnits(prevUnits);
  8506. }
  8507. return retval;
  8508. }
  8509. @ This method is similar to |saveXML()|. The main difference is that CSV data is
  8510. exported instead of XML.
  8511. @<ZoomLog Implementation@>=
  8512. bool ZoomLog::saveCSV(QIODevice *device)
  8513. {
  8514. CSVOutput writer(currentModel, device, 0);
  8515. int c;
  8516. foreach(c, saveTempCols)
  8517. {
  8518. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  8519. toString(), c);
  8520. }
  8521. foreach(c, saveControlCols)
  8522. {
  8523. writer.addControlColumn(model_ms->headerData(c, Qt::Horizontal).
  8524. toString(), c);
  8525. }
  8526. foreach(c, saveNoteCols)
  8527. {
  8528. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  8529. toString(), c);
  8530. }
  8531. return writer.output();
  8532. }
  8533. @ Several little functions, all alike\nfnote{If you get the reference, you may
  8534. enjoy reading another \cweb{} program:\par\indent\pdfURL{%
  8535. http://www-cs-staff.stanford.edu/$\sim$uno/programs/advent.w.gz}
  8536. {http://www-cs-staff.stanford.edu/~uno/programs/advent.w.gz}}, are used to
  8537. switch the view from one level of detail to another.
  8538. @<ZoomLog Implementation@>=
  8539. void ZoomLog::switchLOD(MeasurementModel *m)
  8540. {
  8541. disconnect(currentModel, SIGNAL(rowChanged(int)), this, 0);
  8542. setModel(m);
  8543. currentModel = m;
  8544. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  8545. }
  8546. void ZoomLog::LOD_ms()
  8547. {
  8548. switchLOD(model_ms);
  8549. }
  8550. void ZoomLog::LOD_1s()
  8551. {
  8552. switchLOD(model_1s);
  8553. }
  8554. void ZoomLog::LOD_5s()
  8555. {
  8556. switchLOD(model_5s);
  8557. }
  8558. void ZoomLog::LOD_10s()
  8559. {
  8560. switchLOD(model_10s);
  8561. }
  8562. void ZoomLog::LOD_15s()
  8563. {
  8564. switchLOD(model_15s);
  8565. }
  8566. void ZoomLog::LOD_30s()
  8567. {
  8568. switchLOD(model_30s);
  8569. }
  8570. void ZoomLog::LOD_1m()
  8571. {
  8572. switchLOD(model_1m);
  8573. }
  8574. @ It can be useful to display temperature measurements in various units. To do
  8575. so, we simply tell all of the models which unit to provide data in. It is also
  8576. possible to obtain the currently selected unit.
  8577. @<ZoomLog Implementation@>=
  8578. void ZoomLog::setDisplayUnits(Units::Unit scale)
  8579. {
  8580. model_ms->setDisplayUnits(scale);
  8581. model_1s->setDisplayUnits(scale);
  8582. model_5s->setDisplayUnits(scale);
  8583. model_10s->setDisplayUnits(scale);
  8584. model_15s->setDisplayUnits(scale);
  8585. model_30s->setDisplayUnits(scale);
  8586. model_1m->setDisplayUnits(scale);
  8587. }
  8588. Units::Unit ZoomLog::displayUnits()
  8589. {
  8590. return model_ms->displayUnits();
  8591. }
  8592. @ For convenience, a method is provided for returning a string containing the
  8593. time of the last inserted measurement in a given data series.
  8594. @<ZoomLog Implementation@>=
  8595. QString ZoomLog::lastTime(int series)
  8596. {
  8597. Measurement measure = lastMeasurement.value(series);
  8598. QTime time = measure.time();
  8599. return time.toString("h:mm:ss.zzz");
  8600. }
  8601. @ This just leaves the initial table setup.
  8602. @<ZoomLog Implementation@>=
  8603. ZoomLog::ZoomLog() : QTableView(NULL), model_ms(new MeasurementModel(this)),
  8604. model_1s(new MeasurementModel(this)),@/ model_5s(new MeasurementModel(this)),
  8605. model_10s(new MeasurementModel(this)),@/ model_15s(new MeasurementModel(this)),
  8606. model_30s(new MeasurementModel(this)),@/ model_1m(new MeasurementModel(this))@/
  8607. {@/
  8608. setEditTriggers(QAbstractItemView::NoEditTriggers);
  8609. setSelectionMode(QAbstractItemView::NoSelection);
  8610. modelSet << model_ms << model_1s << model_5s << model_10s << model_15s <<
  8611. model_30s << model_1m;
  8612. currentModel = model_30s;
  8613. setModel(currentModel);
  8614. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  8615. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  8616. this, SLOT(persistColumnResize(int, int, int)));
  8617. connect(horizontalHeader(), SIGNAL(sectionCountChanged(int, int)),
  8618. this, SLOT(restoreColumnWidths()));
  8619. }
  8620. @ A new method was added to this class for version 1.0.7. This allows header
  8621. data to be set on the log and have it propagate to the model set. The longer
  8622. term plan involves removing the hard coding of some of the header data.
  8623. @<ZoomLog Implementation@>=
  8624. void ZoomLog::setHeaderData(int section, QString text)
  8625. {
  8626. MeasurementModel *m;
  8627. foreach(m, modelSet)
  8628. {
  8629. m->setHeaderData(section, Qt::Horizontal, QVariant(text));
  8630. }
  8631. }
  8632. @ As of version 1.2.3, these methods replace similar methods added for version
  8633. 1.0.8. The main difference is that it is now possible to save multiple data
  8634. series to the same output document.
  8635. Starting in version 1.6 it is possible to save control columns. These should
  8636. contain unitless data which should remain unaffected by the current displayed
  8637. unit.
  8638. @<ZoomLog Implementation@>=
  8639. void ZoomLog::addOutputTemperatureColumn(int column)
  8640. {
  8641. saveTempCols.append(column);
  8642. }
  8643. void ZoomLog::addOutputControlColumn(int column)
  8644. {
  8645. saveControlCols.append(column);
  8646. }
  8647. void ZoomLog::addOutputAnnotationColumn(int column)
  8648. {
  8649. saveNoteCols.append(column);
  8650. }
  8651. void ZoomLog::clearOutputColumns()
  8652. {
  8653. saveTempCols.clear();
  8654. saveControlCols.clear();
  8655. saveNoteCols.clear();
  8656. }
  8657. @ Starting in version 1.4 two methods have been introduced which are used to
  8658. save and restore column widths.
  8659. @<ZoomLog Implementation@>=
  8660. void ZoomLog::persistColumnResize(int column, int, int newsize)
  8661. {
  8662. @<Save updated column size@>@;
  8663. }
  8664. void ZoomLog::restoreColumnWidths()
  8665. {
  8666. @<Restore table column widths@>@;
  8667. }
  8668. void ZoomLog::setVisible(bool visibility)
  8669. {
  8670. QTableView::setVisible(visibility);
  8671. }
  8672. void ZoomLog::showEvent(QShowEvent *)
  8673. {
  8674. @<Restore table column widths@>@;
  8675. }
  8676. @ The |ZoomLog| class is one of the more complicated classes to expose to the
  8677. scripting engine. In addition to a script constructor, we also need functions
  8678. for saving and restoring the state of the display and functions for saving data
  8679. from the log in the supported formats.
  8680. @<Function prototypes for scripting@>=
  8681. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine);
  8682. QScriptValue constructZoomLog(QScriptContext *context, QScriptEngine *engine);
  8683. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine);
  8684. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine);
  8685. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *engine);
  8686. QScriptValue ZoomLog_restoreState(QScriptContext *context,
  8687. QScriptEngine *engine);
  8688. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine);
  8689. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  8690. QScriptEngine *engnie);
  8691. QScriptValue ZoomLog_setDisplayUnits(QScriptContext *context,
  8692. QScriptEngine *engine);
  8693. @ Of these, the global object only needs to know about the constructor.
  8694. @<Set up the scripting engine@>=
  8695. constructor = engine->newFunction(constructZoomLog);
  8696. value = engine->newQMetaObject(&ZoomLog::staticMetaObject, constructor);
  8697. engine->globalObject().setProperty("ZoomLog", value);
  8698. @ The script constructor sets properties on the newly created object to allow
  8699. the other functions to be called.
  8700. @<Functions for scripting@>=
  8701. QScriptValue constructZoomLog(QScriptContext *, QScriptEngine *engine)@/
  8702. {@/
  8703. QScriptValue object = engine->newQObject(new ZoomLog);
  8704. setZoomLogProperties(object, engine);
  8705. return object;@/
  8706. }
  8707. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine)
  8708. {
  8709. setQTableViewProperties(value, engine);
  8710. value.setProperty("saveXML", engine->newFunction(ZoomLog_saveXML));
  8711. value.setProperty("saveCSV", engine->newFunction(ZoomLog_saveCSV));
  8712. value.setProperty("saveState", engine->newFunction(ZoomLog_saveState));
  8713. value.setProperty("restoreState",
  8714. engine->newFunction(ZoomLog_restoreState));
  8715. value.setProperty("lastTime", engine->newFunction(ZoomLog_lastTime));
  8716. value.setProperty("saveTemporary",
  8717. engine->newFunction(ZoomLog_saveTemporary));
  8718. value.setProperty("setDisplayUnits", engine->newFunction(ZoomLog_setDisplayUnits));
  8719. }
  8720. @ The functions for saving data are simple wrappers around the corresponding
  8721. calls in |ZoomLog|, except for a function added for saving data to a temporary
  8722. file. The last provides the name of the file saved for use in copying that data
  8723. to a database entry.
  8724. @<Functions for scripting@>=
  8725. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine)
  8726. {
  8727. ZoomLog *self = getself<ZoomLog *>(context);
  8728. bool retval = self->saveXML(argument<QIODevice *>(0, context));
  8729. return QScriptValue(engine, retval);
  8730. }
  8731. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine)
  8732. {
  8733. ZoomLog *self = getself<ZoomLog *>(context);
  8734. bool retval = self->saveCSV(argument<QIODevice *>(0, context));
  8735. return QScriptValue(engine, retval);
  8736. }
  8737. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  8738. QScriptEngine *engine)
  8739. {
  8740. ZoomLog *self = getself<ZoomLog *>(context);
  8741. QString filename = QDir::tempPath();
  8742. filename.append("/");
  8743. filename.append(QUuid::createUuid().toString());
  8744. filename.append(".xml");
  8745. QFile *file = new QFile(filename);
  8746. self->saveXML(file);
  8747. file->close();
  8748. delete file;
  8749. return QScriptValue(engine, filename);
  8750. }
  8751. @ The remaining functions are convenience functions for use with the scripting
  8752. engine. One will save the column widths to a |QSettings| object. Another will
  8753. restore the column widths from settings. Finally, there is a function for
  8754. obtaining a string representation of the most recent measurement from a data
  8755. series.
  8756. \danger There are a couple of problems with these functions. First, the body of
  8757. these functions would probably be better off as methods in the |ZoomLog| class
  8758. proper, either as slots or |Q_INVOKABLE| so the special scripting functions
  8759. could be eliminated. Second, rather than polluting the settings with separate
  8760. entries for each column, it would probably be better to store all of these
  8761. values in an array.\endanger
  8762. |ZoomLog_saveState()| was changed in version 1.2.3 to not save a new value for
  8763. the column width if that width is |0|. This was done mainly to ease debugging.
  8764. Similarly, |ZoomLog_restoreState()| picks a new default value when |0| is
  8765. encountered.
  8766. @<Functions for scripting@>=
  8767. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *)
  8768. {
  8769. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8770. QString key = argument<QString>(0, context);
  8771. int columns = argument<int>(1, context);
  8772. QSettings settings;
  8773. for(int i = 0; i < columns; i++)
  8774. {
  8775. if(self->columnWidth(i))
  8776. {
  8777. settings.beginGroup(key);
  8778. settings.setValue(QString("%1").arg(i), self->columnWidth(i));
  8779. settings.endGroup();
  8780. }
  8781. }
  8782. return QScriptValue();
  8783. }
  8784. QScriptValue ZoomLog_restoreState(QScriptContext *context, QScriptEngine *)
  8785. {
  8786. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8787. QString key = argument<QString>(0, context);
  8788. int columns = argument<int>(1, context);
  8789. QSettings settings;
  8790. for(int i = 0; i < columns; i++)
  8791. {
  8792. settings.beginGroup(key);
  8793. self->setColumnWidth(i,
  8794. settings.value(QString("%1").arg(i), 80).toInt());
  8795. if(settings.value(QString("%1").arg(i), 80).toInt() == 0)
  8796. {
  8797. self->setColumnWidth(i, 80);
  8798. }
  8799. settings.endGroup();
  8800. }
  8801. return QScriptValue();
  8802. }
  8803. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine)
  8804. {
  8805. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8806. return QScriptValue(engine, self->lastTime(argument<int>(0, context)));
  8807. }
  8808. @ There seems to be a bad interaction when enumerated value types as used as
  8809. the argument to slot methods called through QtScript. Script code that attempts
  8810. to make use of the enumeration appears to get the value without any type
  8811. information. When attempting to use that value as an argument the meta-object
  8812. system cannot find an appropriate match and the script just hangs silently.
  8813. The solution is to wrap such methods in the script bindings and explicitly cast
  8814. the argument value to the enumerated type. This looks stupid but it works.
  8815. @<Functions for scripting@>=
  8816. QScriptValue ZoomLog_setDisplayUnits(QScriptContext *context, QScriptEngine *)
  8817. {
  8818. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8819. self->setDisplayUnits((Units::Unit)argument<int>(0, context));
  8820. return QScriptValue();
  8821. }
  8822. @* A model for roasting data.
  8823. \noindent Qt provides a tool called the model view architecture. This provides a
  8824. uniform interface allowing different types of model classes to work with
  8825. different types of view classes without either needing to know implementation
  8826. details of the other. \pn{} provides the |MeasurementModel| as a specialization
  8827. of |QAbstractItemModel| for use in this architecture.
  8828. @<Class declarations@>=
  8829. class MeasurementList;@/
  8830. class MeasurementModel : public QAbstractItemModel@/
  8831. {@t\1@>@/
  8832. Q_OBJECT@;
  8833. Units::Unit unit;
  8834. QList<MeasurementList *> *entries;
  8835. QStringList *hData;
  8836. int colcount;
  8837. QHash<int, int> *lastTemperature;
  8838. QList<MeasurementList *>::iterator@, lastInsertion;
  8839. QHash<int, bool> *controlColumns;
  8840. public:@/
  8841. MeasurementModel(QObject *parent = NULL);
  8842. ~MeasurementModel();
  8843. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  8844. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  8845. bool setHeaderData(int section, Qt::Orientation orientation,
  8846. const QVariant &value,@|int role = Qt::DisplayRole);
  8847. QVariant data(const QModelIndex &index, int role) const;
  8848. bool setData(const QModelIndex &index, const QVariant &value,
  8849. int role = Qt::EditRole);
  8850. Qt::ItemFlags flags(const QModelIndex &index) const;
  8851. QVariant headerData(int section, Qt::Orientation orientation,
  8852. int role = Qt::DisplayRole) const;
  8853. QModelIndex index(int row, int column,
  8854. const QModelIndex &parent = QModelIndex()) const;
  8855. QModelIndex parent(const QModelIndex &index) const;
  8856. Units::Unit displayUnits();@/
  8857. @t\4@>public slots@t\kern-3pt@>:@/
  8858. void newMeasurement(Measurement measure, int tempcolumn);
  8859. void newAnnotation(QString annotation, int tempcolumn,
  8860. int annotationColumn);
  8861. void clear();
  8862. void setDisplayUnits(Units::Unit scale);
  8863. signals:@/
  8864. void rowChanged(int);@t\2@>@/
  8865. }@t\kern-3pt@>;
  8866. @ The measurement model stores its data in a list of measurement lists. This
  8867. allows the model to store as many sets of data as needed. In order to keep
  8868. measurements in the model sorted by time, the measurement list adds two
  8869. comparison functions.
  8870. @<Class declarations@>=
  8871. class MeasurementList : public QVariantList@/
  8872. {@t\1@>@/
  8873. @t\4@>public:@/
  8874. bool operator<(const MeasurementList &other) const;
  8875. bool operator==(const MeasurementList &other) const;@t\2@>@/
  8876. }@t\kern-3pt@>;
  8877. @ The overload of |<| checks if the time in one list (always stored in the first
  8878. column) is less than the time stored in the second. The overload of |==| is used
  8879. in an optimization that allows us to skip the search procedure on model
  8880. insertion.
  8881. @<MeasurementModel Implementation@>=
  8882. bool MeasurementList::operator<(const MeasurementList &other) const
  8883. {
  8884. return this->first().toTime() < other.first().toTime();
  8885. }
  8886. bool MeasurementList::operator==(const MeasurementList &other) const
  8887. {
  8888. return this->first().toTime() == other.first().toTime();
  8889. }
  8890. @ The |MeasurementModel| class extends the |QAbstractItemModel| class to work
  8891. better with measurements and annotations that are passed around in \pn{}. Many
  8892. of the class methods are required because of that choice. For example, the
  8893. parent function which is never used directly:
  8894. @<MeasurementModel Implementation@>=
  8895. QModelIndex MeasurementModel::parent(const QModelIndex&) const
  8896. {
  8897. return QModelIndex();
  8898. }
  8899. @ Perhaps the most complicated part of this class is the code for dealing with a
  8900. new measurement. This is complicated by the requirement to insert measurements
  8901. while keeping the model sorted by time.
  8902. @<MeasurementModel Implementation@>=
  8903. void MeasurementModel::newMeasurement(Measurement measure, int tempcolumn)
  8904. {
  8905. if(measure.scale() == Units::Unitless)
  8906. {
  8907. controlColumns->insert(tempcolumn, true);
  8908. }
  8909. else
  8910. {
  8911. controlColumns->insert(tempcolumn, false);
  8912. }
  8913. MeasurementList *temp;
  8914. temp = new MeasurementList;
  8915. temp->append(QVariant(measure.time()));
  8916. @<Find the insertion point@>@;
  8917. MeasurementList *newEntry;
  8918. int insertion;
  8919. if(i != entries->end())
  8920. {
  8921. insertion = entries->indexOf(*i);
  8922. if((*i)->first().toTime() == measure.time())
  8923. {
  8924. @<Insert a new measurement at an existing time@>@;
  8925. }
  8926. else
  8927. {
  8928. @<Insert a new measurement somewhere else@>@;
  8929. }
  8930. }
  8931. else
  8932. {
  8933. @<Append a measurement@>@;
  8934. }
  8935. if(tempcolumn >= colcount)
  8936. {
  8937. colcount = tempcolumn + 1;
  8938. }
  8939. emit rowChanged(insertion);
  8940. delete temp;
  8941. }
  8942. @ To find the insertion point for new measurements we use a binary search of the
  8943. existing data. The code below is a direct adaptation of Program B\nfnote{%
  8944. \underbar{The Art of Computer Programming} Volume 3 Sorting and Searching 2nd
  8945. ed. (Knuth, 1997) Section 6.2.1: Searching an Ordered Table} modified to use
  8946. list iterators and control structures more familiar to \CPLUSPLUS/programmers
  8947. rather than {\mc MIX} machine codes. When the loop exits |i| is the insertion
  8948. point.
  8949. \medskip
  8950. \centerline{\includegraphics{search}}
  8951. \smallskip
  8952. \centerline{Figure \secno: Binary Search}
  8953. \medskip
  8954. @<Find the insertion point@>=
  8955. @<Scan from most recent insertion@>@;
  8956. if(quickscan == false)
  8957. {
  8958. i = entries->begin();
  8959. QList<MeasurementList *>::iterator@, u = entries->end();
  8960. QList<MeasurementList *>::iterator@, midpoint;
  8961. int n = u - i;
  8962. int rA;
  8963. while(n > 0)@/
  8964. {
  8965. rA = n>>1; /* |rA = |~$\bigl\lfloor{n\over2}\bigr\rfloor$ */
  8966. midpoint = i + rA;
  8967. if(**midpoint < *temp)@/
  8968. {
  8969. i = midpoint + 1;
  8970. n -= rA + 1;
  8971. }
  8972. else@/
  8973. {
  8974. n = rA;
  8975. }
  8976. }
  8977. }
  8978. @ The binary search, while correct, is not a particularly optimal choice for
  8979. this application. While the average running time for this is on the order of
  8980. $\ln N$ when each insertion point is equally likely, the reality of this
  8981. application is that insertions will likely be at the beginning of the list, at
  8982. the point of the most recent insertion, or a short distance from the most recent
  8983. insertion. By first considering the possibility that the measurement should be
  8984. inserted at or near the most recent measurement, shorter, more constant running
  8985. times as $N$ increases can be obtained.
  8986. To do this, when the number of measurements in the list is above a small number
  8987. which must be greater than 1, we check first if the insertion point is at the
  8988. last insertion (the |<| comparison fails and we do an |==| comparison before
  8989. giving up), then we check a small number of rows for either the end of the list,
  8990. in which case the insertion point is at the end, or for a point at which the |<|
  8991. comparison fails. If neither condition holds for a small number of comparisons
  8992. we resort to the binary search.
  8993. Performance measurements with this modification compared with previous versions
  8994. shows that this provides a huge performance boost.
  8995. @<Scan from most recent insertion@>=
  8996. @[QList<MeasurementList *>::iterator@, i@] = lastInsertion;@/
  8997. bool quickscan = false;@/
  8998. if(entries->size() > 5)@/
  8999. {@t\1@>@/
  9000. if(**i < *temp)@/
  9001. {@t\1@>@/
  9002. i += 1;@/
  9003. for(int j = 10; j > 0; j--)@/
  9004. {@t\1@>@/
  9005. if(i != entries->end())@/
  9006. {@t\1@>@/
  9007. if(**i < *temp)@/
  9008. {
  9009. i += 1;
  9010. }@/
  9011. else@/
  9012. {@t\1@>@/
  9013. quickscan = true;
  9014. break;@t\2@>@/
  9015. }@t\2@>@/
  9016. }@/
  9017. else@/
  9018. {@t\1@>@/
  9019. quickscan = true;
  9020. break;@t\2@>@/
  9021. }@t\2@>@/
  9022. }@t\2@>@/
  9023. }@/
  9024. else@/
  9025. {@t\1@>@/
  9026. if(**i == *temp)@/
  9027. {@t\1@>@/
  9028. quickscan = true;@t\2@>@/
  9029. }@t\2@>@/
  9030. }@t\2@>@/
  9031. }
  9032. @ If the chosen insertion point is at an existing time, we don'@q'@>t need to
  9033. worry about inserting rows. There may be a need to increase the size of the
  9034. measurement list to accept an entry in a new data series.
  9035. @<Insert a new measurement at an existing time@>=
  9036. if((*i)->size() < tempcolumn + 1)
  9037. {
  9038. for(int j = (*i)->size() - 1; j < tempcolumn + 1; j++)
  9039. {
  9040. (*i)->append(QVariant());
  9041. }
  9042. }
  9043. (*i)->replace(tempcolumn, measure);
  9044. lastInsertion = i;
  9045. emit dataChanged(createIndex(insertion, tempcolumn),
  9046. createIndex(insertion, tempcolumn));
  9047. lastTemperature->insert(tempcolumn, insertion);
  9048. @ If the measurement is not past the end of the existing data and the insertion
  9049. point has a different time, we need to use |beginInsertRows()| and
  9050. |endInsertRows()| to notify any attached view that a new row will be added.
  9051. @<Insert a new measurement somewhere else@>=
  9052. beginInsertRows(QModelIndex(), insertion, insertion);
  9053. newEntry = new MeasurementList;
  9054. newEntry->append(QVariant(measure.time()));
  9055. for(int j = 0; j < tempcolumn + 1; j++)
  9056. {
  9057. newEntry->append(QVariant());
  9058. }
  9059. newEntry->replace(tempcolumn, measure);
  9060. lastInsertion = entries->insert(i, newEntry);
  9061. endInsertRows();
  9062. lastTemperature->insert(tempcolumn, insertion);
  9063. @ If the insertion point is past the end of the existing data, a new row should
  9064. be appended to the data. This only needs to be a separate case to prevent the
  9065. comparison with a nonexistent entry. This is very similar to the case of
  9066. inserting at a new time anywhere else.
  9067. @<Append a measurement@>=
  9068. insertion = entries->size();@/
  9069. @<Insert a new measurement somewhere else@>
  9070. @ The other bit of code that'@q'@>s a little bit more complicated than other
  9071. parts of the class handles adding annotations to the data. Two signals are
  9072. emitted in this method. The |dataChanged| signal is expected by view classes
  9073. that can use this model. The |rowChanged| signal is used by |ZoomLog| to scroll
  9074. the view to the row the annotation has been added to. This is mainly useful
  9075. when loading a target profile and entering the first annotation prior to
  9076. starting the batch.
  9077. @<MeasurementModel Implementation@>=
  9078. void MeasurementModel::newAnnotation(QString annotation, int tempcolumn,@|
  9079. int annotationColumn)
  9080. {
  9081. int r;
  9082. if(lastTemperature->contains(tempcolumn))
  9083. {
  9084. r = lastTemperature->value(tempcolumn);
  9085. }
  9086. else
  9087. {
  9088. r = 0;
  9089. }
  9090. if(r == 0 && entries->size() == 0)
  9091. {
  9092. @<Create the first row@>@;
  9093. }
  9094. MeasurementList *row = entries->at(r);
  9095. if(row->size() <= annotationColumn)
  9096. {
  9097. for(int i = row->size() - 1; i < annotationColumn + 1; i++)
  9098. {
  9099. row->append(QVariant());
  9100. }
  9101. }
  9102. row->replace(annotationColumn, annotation);
  9103. emit dataChanged(createIndex(r, annotationColumn),
  9104. createIndex(r, annotationColumn));
  9105. emit rowChanged(r);
  9106. if(annotationColumn > colcount - 1)
  9107. {
  9108. colcount = annotationColumn + 1;
  9109. }
  9110. }
  9111. @ There is no need to further complicate the function by adding the annotation
  9112. when the first row is created.
  9113. @<Create the first row@>=
  9114. beginInsertRows(QModelIndex(), 0, 0);
  9115. MeasurementList *newEntry = new MeasurementList;
  9116. newEntry->append(QVariant(QTime(0, 0, 0, 0)));
  9117. entries->append(newEntry);
  9118. endInsertRows();
  9119. @ Clearing the model data is a simple matter of deleting every row, remembering
  9120. to let any attached views know that we are doing this, and resetting the number
  9121. of columns.
  9122. @<MeasurementModel Implementation@>=
  9123. void MeasurementModel::clear()
  9124. {
  9125. beginRemoveRows(QModelIndex(), 0, entries->size());
  9126. while(entries->size() != 0)
  9127. {
  9128. MeasurementList *row = entries->takeFirst();
  9129. delete row;
  9130. }
  9131. endRemoveRows();
  9132. colcount = hData->size();
  9133. lastTemperature->clear();
  9134. reset();
  9135. }
  9136. @ While these methods for adding measurements and annotations are fine when
  9137. recording a stream of measurements, either from the |DAQ| or when loading saved
  9138. data, there are also cases where we'@q'@>d like to edit the data in the model
  9139. directly from the table view. For this, we need to reimplement |setData()|.
  9140. Note that editing from the |ZoomLog| has never been supported. While stream
  9141. inserted data currently preserves all properties of inserted measurements,
  9142. using |setData| it is possible to insert a numeric value as if it were a
  9143. measurement. Such an entry will not have any additional information associated
  9144. and cannot be expected to exhibit behavior implemented through the use of that
  9145. extra information.
  9146. Very little input checking is done here. Editable views may want to place
  9147. delegates\nfnote{Qt 4.4: Delegate Classes\par\indent\hbox{%
  9148. \pdfURL{http://doc.trolltech.com/4.4/model-view-delegate.html}{%
  9149. http://doc.trolltech.com/4.4/model-view-delegate.html}}} on the columns to make
  9150. editing the data easier and less error prone.
  9151. @<MeasurementModel Implementation@>=
  9152. bool MeasurementModel::setData(const QModelIndex &index,
  9153. const QVariant &value, int role)@t\2\2@>@/
  9154. {@t\1@>@/
  9155. if(role != Qt::EditRole && role != Qt::DisplayRole)@/
  9156. {@t\1@>@/
  9157. return false;@t\2@>@/
  9158. }@/
  9159. @<Check that the index is valid@>@;
  9160. if(!valid)@/
  9161. {@t\1@>@/
  9162. return false;@t\2@>@/
  9163. }@/
  9164. MeasurementList *row = entries->at(index.row());
  9165. if(index.column() >= row->size())
  9166. {
  9167. @<Expand the row to prepare for new data@>@;
  9168. }
  9169. if(index.column() == 0)
  9170. {
  9171. @<Edit data in the time column@>@;
  9172. }
  9173. else
  9174. {
  9175. @<Edit data in other columns@>@;
  9176. }
  9177. return true;@t\2@>@/
  9178. }
  9179. @ There is no sense in attempting to edit the data if there isn'@q'@>t any data
  9180. available to edit. This check is also used when retrieving data from the model.
  9181. @<Check that the index is valid@>=
  9182. bool valid = false;
  9183. if(index.isValid())@/
  9184. {@t\1@>@/
  9185. if(index.row() < entries->size())@/
  9186. {@t\1@>@/
  9187. if(index.column() < colcount)@/
  9188. {@t\1@>@/
  9189. valid = true;@t\2@>@/
  9190. }@t\2@>@/
  9191. }@t\2@>@/
  9192. }
  9193. @ When editing data, there might not be anything where we want to add the data.
  9194. For example, adding an annotation to an otherwise unannotated measurement. This
  9195. is fine, but we need to expand the row instead of inserting data out of bounds.
  9196. @<Expand the row to prepare for new data@>=
  9197. for(int i = row->size() - 1; i < index.column(); i++)
  9198. {
  9199. row->append(QVariant());
  9200. }
  9201. @ Changing time data must be considered separately from other data. As the model
  9202. keeps itself sorted based on the time field, allowing the user to get the model
  9203. data out of order would result in poorly defined behavior later. Our approach is
  9204. to remove the row from the model temporarily then reuse the code from
  9205. |newMeasurement()| to find the new insertion point. No attempt is made to merge
  9206. the contents from two rows with identical times, but an attempt is made to not
  9207. be too rigid in what we expect the user to enter. If an invalid time is entered,
  9208. we give up and leave the data as we found it.
  9209. @<Edit data in the time column@>=
  9210. QTime time;@/
  9211. if(!(time = QTime::fromString(value.toString(), "m:s.z")).isValid())@/
  9212. {@t\1@>@/
  9213. if(!(time = QTime::fromString(value.toString(), "m:s")).isValid())@/
  9214. {@t\1@>@/
  9215. return false;@t\2@>@/
  9216. }@t\2@>@/
  9217. }@/
  9218. row = entries->takeAt(index.row());
  9219. row->replace(index.column(), QVariant(time));
  9220. MeasurementList *temp = row;
  9221. @<Find the insertion point@>@;
  9222. entries->insert(i, row);
  9223. int newRow = entries->indexOf(*i);
  9224. if(newRow < index.row())@/
  9225. {
  9226. emit dataChanged(createIndex(newRow, index.column()), index);
  9227. }
  9228. else@/
  9229. {
  9230. emit dataChanged(index, createIndex(newRow, index.column()));
  9231. }
  9232. @ Data in other columns is a little easier to handle.
  9233. @<Edit data in other columns@>=
  9234. row->replace(index.column(), value);
  9235. emit dataChanged(index, index);
  9236. @ As it has already been established that the first column is always considered
  9237. the time of the measurement, this assumption can be built into the model
  9238. constructor.
  9239. @<MeasurementModel Implementation@>=
  9240. MeasurementModel::MeasurementModel(QObject *parent) : QAbstractItemModel(parent),
  9241. unit(Units::Fahrenheit), hData(new QStringList),
  9242. lastTemperature(new QHash<int, int>),
  9243. controlColumns(new QHash<int, bool>)@/
  9244. {
  9245. colcount = 1;
  9246. entries = new QList<MeasurementList *>;
  9247. lastInsertion = entries->begin();
  9248. hData->append(tr("Time"));
  9249. }
  9250. @ In the destructor we need to remember to clean up after ourselves.
  9251. @<MeasurementModel Implementation@>=
  9252. MeasurementModel::~MeasurementModel()
  9253. {
  9254. clear();
  9255. delete entries;
  9256. delete hData;
  9257. }
  9258. @ A pair of functions are used to determine the number of rows and columns the
  9259. model provides. No entries in the model have children, so the parent should
  9260. always be the invisible root object. If it isn'@q'@>t, we should return 0.
  9261. @<MeasurementModel Implementation@>=
  9262. int MeasurementModel::rowCount(const QModelIndex &parent) const
  9263. {
  9264. if(parent == QModelIndex())
  9265. {
  9266. return entries->size();
  9267. }
  9268. return 0;
  9269. }
  9270. int MeasurementModel::columnCount(const QModelIndex &parent) const
  9271. {
  9272. if(parent == QModelIndex())
  9273. {
  9274. return colcount;
  9275. }
  9276. return 0;
  9277. }
  9278. @ The model maintains a set of header data. At present, it only supports header
  9279. data at the top of the model due to the author'@q'@>s preference to not have row
  9280. numbers littering the left of the table (the time column is sufficient to
  9281. identify the row for the user).
  9282. The model view architecture supports the concept of different data roles in the
  9283. header data. At present, this model ignores the role when setting header data.
  9284. @<MeasurementModel Implementation@>=
  9285. bool MeasurementModel::setHeaderData(int section, Qt::Orientation orientation,@|
  9286. const QVariant &value, int)@t\2@>@/
  9287. @t\4@>{@/
  9288. if(orientation == Qt::Horizontal)@/
  9289. {@t\1@>@/
  9290. if(hData->size() < section + 1)@/
  9291. {@/
  9292. for(int i = hData->size(); i < section + 1; i++)@/
  9293. {@/
  9294. if(colcount < i)@/
  9295. {@/
  9296. beginInsertColumns(QModelIndex(), i, i);
  9297. }
  9298. hData->append(QString());
  9299. if(colcount < i)@/
  9300. {@/
  9301. endInsertColumns();
  9302. }
  9303. }
  9304. }
  9305. hData->replace(section, value.toString());
  9306. emit headerDataChanged(orientation, section, section);
  9307. if(colcount < section + 1)@/
  9308. {@/
  9309. colcount = section + 1;
  9310. }@/
  9311. return true;@t\2@>@/
  9312. }@/
  9313. return false;@/
  9314. @t\4@>}
  9315. @ While the current implementation always receives measurements in degrees
  9316. Fahrenheit, international users often want to see data presented in Celsius. To
  9317. do this, a slot is provided to allow selecting among different units. When this
  9318. method is called, the model indicates that all attached views must update all
  9319. displayed data and requests for temperature data will have any needed conversion
  9320. performed before sending that information to the view. Another method is
  9321. available to request a number identifyin the currently displayed units.
  9322. @<MeasurementModel Implementation@>=
  9323. void MeasurementModel::setDisplayUnits(Units::Unit scale)
  9324. {
  9325. beginResetModel();
  9326. unit = scale;
  9327. endResetModel();
  9328. }
  9329. Units::Unit MeasurementModel::displayUnits()
  9330. {
  9331. return unit;
  9332. }
  9333. @ A model is generally quite useless if the data the model contains cannot be
  9334. retrieved. To do this, we check that the index requested is a valid index that
  9335. is within the bounds of the model data and that a role we understand has been
  9336. requested. If none of these conditions are met, a default constructed |QVariant|
  9337. is returned.
  9338. At present, |Qt::DisplayRole| and |Qt::EditRole| are supported. These return the
  9339. same thing. Views will request the display role for presenting the information
  9340. to the user, but they will request the edit role if the user attempts to modify
  9341. the data through a view.
  9342. As of version 1.6, |Qt::UserRole| allows retrieval of raw measurement data.
  9343. @<MeasurementModel Implementation@>=
  9344. QVariant MeasurementModel::data(const QModelIndex &index, int role) const@/
  9345. {@/
  9346. @<Check that the index is valid@>@;
  9347. if(!valid)
  9348. {
  9349. return QVariant();
  9350. }
  9351. MeasurementList *row = entries->at(index.row());
  9352. if(role == Qt::UserRole)
  9353. {
  9354. return QVariant(row->at(index.column()));
  9355. }
  9356. if(role == Qt::DisplayRole || role == Qt::EditRole)
  9357. {
  9358. if(index.column() > row->size())
  9359. {
  9360. return QVariant();
  9361. }
  9362. else
  9363. {
  9364. if(index.column() == 0)
  9365. {
  9366. return QVariant(row->at(0).toTime().toString("mm:ss.zzz"));
  9367. }
  9368. else if(lastTemperature->contains(index.column()))
  9369. {
  9370. QVariantMap v = row->at(index.column()).toMap();
  9371. if(!v.contains("measurement"))
  9372. {
  9373. return QVariant();
  9374. }
  9375. if((Units::Unit)(v.value("unit").toInt()) == Units::Unitless)
  9376. {
  9377. return v.value("measurement");
  9378. }
  9379. else
  9380. {
  9381. if(v.contains("relative"))
  9382. {
  9383. if(v.value("relative").toBool())
  9384. {
  9385. return QVariant(QString("%1").@|arg(Units::convertRelativeTemperature(v.value("measurement").
  9386. toDouble(),@| (Units::Unit)(v.value("unit").toInt()), unit)));
  9387. }
  9388. }
  9389. return QVariant(QString("%1").@|
  9390. arg(Units::convertTemperature(v.value("measurement").toDouble(),@|
  9391. (Units::Unit)(v.value("unit").toInt()), unit)));
  9392. }
  9393. }
  9394. return QVariant(row->at(index.column()).toString());
  9395. }
  9396. }
  9397. return QVariant();@/
  9398. }
  9399. @ Views also must be able to retrieve the header data.
  9400. @<MeasurementModel Implementation@>=
  9401. QVariant MeasurementModel::headerData(int section, Qt::Orientation orientation,
  9402. int role ) const
  9403. {
  9404. if(orientation == Qt::Horizontal)
  9405. {
  9406. if(role == Qt::DisplayRole)
  9407. {
  9408. if(section < hData->size())
  9409. {
  9410. return QVariant(hData->at(section));
  9411. }
  9412. }
  9413. }
  9414. return QVariant();
  9415. }
  9416. @ Views will sometimes request information about the interactions available for
  9417. an index. In the case of this model, each index is treated in the same way.
  9418. It may be a good idea to extend the model class to allow models that can be
  9419. edited through the view such as the table view presented in the |LogEditWindow|
  9420. and models that probably shouldn'@q'@>t be edited in the view, such as the models
  9421. managed by |ZoomLog|. This could be done by subclassing and only reimplementing
  9422. this method. Otherwise, a new method to specify that the user should not edit
  9423. the model could be provided and a flag would be checked here.
  9424. @<MeasurementModel Implementation@>=
  9425. Qt::ItemFlags MeasurementModel::flags(const QModelIndex &index) const@/
  9426. {@/
  9427. @<Check that the index is valid@>@;
  9428. if(valid)
  9429. {
  9430. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
  9431. }
  9432. return 0;
  9433. }
  9434. @ Much of the way models are interacted with in Qt'@q'@>s model view architecture is
  9435. through model indices. The model is responsible for creating these indices from
  9436. row column pairs.
  9437. @<MeasurementModel Implementation@>=
  9438. QModelIndex MeasurementModel::index(int row, int column,
  9439. const QModelIndex &parent) const@t\2\2@>@/
  9440. {@t\1@>@/
  9441. if(parent == QModelIndex())@/
  9442. {@t\1@>@/
  9443. if(row < entries->size() && entries->isEmpty() == false)@/
  9444. {@/
  9445. if(column < entries->at(row)->size())@/
  9446. {@/
  9447. return createIndex(row, column);@/
  9448. }@/
  9449. }@t\2@>@/
  9450. }@/
  9451. return QModelIndex();@/
  9452. @t\4@>}
  9453. @** Annotating roast data.
  9454. \noindent In addition to recording time temperature pairs, \pn{} allows the user
  9455. to annotate the roasting log to indicate control changes, the end of the batch,
  9456. or samples collected from the roast. It is important that these annotations can
  9457. be applied to the roasting log quickly. This is the purpose of the
  9458. |AnnotationButton| class.
  9459. @<Class declarations@>=
  9460. class AnnotationButton : public QPushButton@/
  9461. {@t\1@>@/
  9462. Q_OBJECT@;
  9463. QString note;
  9464. int tc;
  9465. int ac;
  9466. int count;
  9467. public:@/
  9468. AnnotationButton(const QString &text, QWidget *parent = NULL);@/
  9469. @t\4@>public slots@t\kern-3pt@>:@/
  9470. void setAnnotation(const QString &annotation);
  9471. void setTemperatureColumn(int tempcolumn);
  9472. void setAnnotationColumn(int annotationcolumn);
  9473. void annotate();
  9474. void resetCount();
  9475. signals:@/
  9476. void annotation(QString annotation, int tempcolumn,
  9477. int notecolumn);@t\2@>@/
  9478. }@t\kern-3pt@>;
  9479. @ Setting up a new annotation button begins with the constructor. This takes a
  9480. string specifying the text that will appear on the button and optionally a
  9481. parent widget. This is also a sensible place to set up the desired behavior the
  9482. button should exhibit when clicked.
  9483. @<AnnotationButton Implementation@>=
  9484. AnnotationButton::AnnotationButton(const QString &text, QWidget *parent) :
  9485. QPushButton(text, parent), note(""), tc(0), ac(0), count(0)@/
  9486. {
  9487. connect(this, SIGNAL(clicked()), this, SLOT(annotate()));
  9488. }
  9489. @ The slot that is called when the button is clicked needs to be able to handle
  9490. two types of annotations. Simple annotations send the same annotation every time
  9491. the button is clicked. Counting annotations are annotation strings that have a
  9492. |"%1"| somewhere in the string. That substring will be replaced with an integer
  9493. that is incremented before the annotation is sent. This integer is initialized
  9494. to 0. It will be incremented to 1 the first time the button is clicked and that
  9495. will be the replacement value.
  9496. @<AnnotationButton Implementation@>=
  9497. void AnnotationButton::annotate()
  9498. {
  9499. if(note.contains("%1"))
  9500. {
  9501. count++;
  9502. emit annotation(note.arg(count), tc, ac);
  9503. }
  9504. else
  9505. {
  9506. emit annotation(note, tc, ac);
  9507. }
  9508. }
  9509. @ A few methods are available to indicate which temperature series the
  9510. annotation should be applied to, which column in a table view the annotation
  9511. should be entered in, and what text should be in the annotation.
  9512. @<AnnotationButton Implementation@>=
  9513. void AnnotationButton::setTemperatureColumn(int tempcolumn)
  9514. {
  9515. tc = tempcolumn;
  9516. }
  9517. void AnnotationButton::setAnnotationColumn(int annotationcolumn)
  9518. {
  9519. ac = annotationcolumn;
  9520. }
  9521. void AnnotationButton::setAnnotation(const QString &annotation)
  9522. {
  9523. note = annotation;
  9524. }
  9525. @ Finally, in the case of counting annotations, there should be a way to reset
  9526. the number used in the annotation.
  9527. @<AnnotationButton Implementation@>=
  9528. void AnnotationButton::resetCount()
  9529. {
  9530. count = 0;
  9531. }
  9532. @ A script constructor is needed to allow an |AnnotationButton| to be created
  9533. from a script.
  9534. @<Function prototypes for scripting@>=
  9535. QScriptValue constructAnnotationButton(QScriptContext *context,
  9536. QScriptEngine *engine);
  9537. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine);
  9538. @ In order to use this, the engine needs to be informed of the function.
  9539. @<Set up the scripting engine@>=
  9540. constructor = engine->newFunction(constructAnnotationButton);
  9541. value = engine->newQMetaObject(&AnnotationButton::staticMetaObject,
  9542. constructor);
  9543. engine->globalObject().setProperty("AnnotationButton", value);
  9544. @ The implementation is trivial.
  9545. @<Functions for scripting@>=
  9546. QScriptValue constructAnnotationButton(QScriptContext *context,
  9547. QScriptEngine *engine)
  9548. {
  9549. QScriptValue object =
  9550. engine->newQObject(new AnnotationButton(argument<QString>(0, context)));
  9551. setAnnotationButtonProperties(object, engine);
  9552. return object;
  9553. }
  9554. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine)
  9555. {
  9556. setQPushButtonProperties(value, engine);
  9557. }
  9558. @* A spin box for annotations.
  9559. \noindent While the annotation button is adequate for most log annotation tasks,
  9560. there are some times where the log should contain a small number of numerical
  9561. observations where it is inconvenient or cost prohibitive to enable automated
  9562. logging. For these tasks, a spin box that produces an appropriate annotation may
  9563. be useful.
  9564. @<Class declarations@>=
  9565. class AnnotationSpinBox : public QDoubleSpinBox@/
  9566. {@t\1@>@/
  9567. Q_OBJECT@;
  9568. QString pretext;
  9569. QString posttext;
  9570. int tc;
  9571. int ac;
  9572. bool change;
  9573. public:
  9574. AnnotationSpinBox(const QString &pret, const QString &postt,
  9575. QWidget *parent = NULL);@/
  9576. @t\4@>public slots@t\kern-3pt@>:@/
  9577. void setPretext(const QString &pret);
  9578. void setPosttext(const QString &postt);
  9579. void setTemperatureColumn(int tempcolumn);
  9580. void setAnnotationColumn(int annotationcolumn);
  9581. void annotate();
  9582. void resetChange();
  9583. signals:@/
  9584. void annotation(QString annotation, int tempcolumn,
  9585. int notecolumn);@t\2@>@/
  9586. }@t\kern-3pt@>;
  9587. @ Setting up a new annotation spin box begins with the constructor. This takes
  9588. two strings specifying optional text that may appear before or after the
  9589. numerical value of the spin box in the annotation. No spaces are placed between
  9590. the text and the numerical values, so if such spacing is required, it must be
  9591. included in the relevant string.
  9592. This function also sets up the behavior for firing annotation events. An
  9593. annotation should be fired when the user presses enter while the spin box has
  9594. focus. This implementation will also attempt to fire an annotation when the
  9595. spin box loses focus. No annotation is fired if the value of the spin box has
  9596. not been changed since the previous annotation event.
  9597. @<AnnotationSpinBox Implementation@>=
  9598. AnnotationSpinBox::AnnotationSpinBox(const QString &pret,
  9599. const QString &postt,@|
  9600. QWidget *parent)
  9601. : QDoubleSpinBox(parent), pretext(pret), posttext(postt)@/
  9602. {
  9603. resetChange();
  9604. connect(this, SIGNAL(editingFinished()), this, SLOT(annotate()));
  9605. connect(this, SIGNAL(valueChanged(double)), this, SLOT(resetChange()));
  9606. }
  9607. @ The |resetChange()| signal just sets a boolean which is checked prior to
  9608. sending an annotation. This is called automatically when the value of the spin
  9609. box is changed, but it should also be called when a batch is finished in case
  9610. the first required annotation is the same as the last required annotation from
  9611. the previous batch.
  9612. @<AnnotationSpinBox Implementation@>=
  9613. void AnnotationSpinBox::resetChange()@t\2\2@>@/
  9614. {@t\1@>@/
  9615. change = true;@t\2@>@/
  9616. }
  9617. @ The annotation slot is responsible for determining if an annotation should be
  9618. sent. The current implementation is to only attempt to send such a signal when
  9619. the |editingFinished()| signal is emitted, however this could also be connected
  9620. to other signals.
  9621. @<AnnotationSpinBox Implementation@>=
  9622. void AnnotationSpinBox::annotate()@t\2\2@>@/
  9623. {@t\1@>@/
  9624. if(change)@/
  9625. {@t\1@>@/
  9626. change = false;@/
  9627. emit annotation(QString("%1%2%3").arg(pretext).
  9628. arg(value()).arg(posttext), tc, ac);@t\2@>@/
  9629. }@t\2@>@/
  9630. }
  9631. @ These methods set various properties of the annotation.
  9632. @<AnnotationSpinBox Implementation@>=
  9633. void AnnotationSpinBox::setTemperatureColumn(int tempcolumn)
  9634. {
  9635. tc = tempcolumn;
  9636. }
  9637. void AnnotationSpinBox::setAnnotationColumn(int annotationcolumn)
  9638. {
  9639. ac = annotationcolumn;
  9640. }
  9641. void AnnotationSpinBox::setPretext(const QString &pret)
  9642. {
  9643. pretext = pret;
  9644. }
  9645. void AnnotationSpinBox::setPosttext(const QString &postt)
  9646. {
  9647. posttext = postt;
  9648. }
  9649. @ Two functions are needed to interface |AnnotationSpinBox| with the host
  9650. environment. Additional functions are required for setting up inheritance
  9651. properly.
  9652. @<Function prototypes for scripting@>=
  9653. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  9654. QScriptEngine *engine);
  9655. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9656. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9657. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9658. @ The first of these is passed into the host environment.
  9659. @<Set up the scripting engine@>=
  9660. constructor = engine->newFunction(constructAnnotationSpinBox);
  9661. value = engine->newQMetaObject(&AnnotationSpinBox::staticMetaObject,
  9662. constructor);
  9663. engine->globalObject().setProperty("AnnotationSpinBox", value);
  9664. @ The script constructor creates a new object and passes it to a function that
  9665. is responsible for setting up properties in the inheritance chain.
  9666. @<Functions for scripting@>=
  9667. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  9668. QScriptEngine *engine)
  9669. {
  9670. QScriptValue object = engine->newQObject(new AnnotationSpinBox(
  9671. argument<QString>(0, context), argument<QString>(1, context)));
  9672. setAnnotationSpinBoxProperties(object, engine);
  9673. return object;
  9674. }
  9675. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9676. {
  9677. setQDoubleSpinBoxProperties(value, engine);
  9678. }
  9679. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9680. {
  9681. setQAbstractSpinBoxProperties(value, engine);
  9682. }
  9683. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9684. {
  9685. setQWidgetProperties(value, engine);
  9686. }
  9687. @** A digital timer.
  9688. \noindent Before \pn{} was a data logger, it was a simple digital timer written
  9689. because there were no shops in Racine that could sell a simple dual digital
  9690. count up timer at a time when my first timer was malfunctioning. After
  9691. attempting to purchase a replacement device at several stores that have sold
  9692. such devices in the past, I decided to spend a couple hours writing my own
  9693. timer.
  9694. For historical reasons, the |TimerDisplay| class is considerably more functional
  9695. than \pn{} requires. Those needing only a digital timer can extract the code for
  9696. this class and use it in a timer application. This should work on any platform
  9697. supported by Qt.
  9698. @<Class declarations@>=
  9699. class TimerDisplay : public QLCDNumber@/
  9700. {@t\1@>@/
  9701. Q_OBJECT@/
  9702. @<TimerDisplay Properties@>@;
  9703. @t\4@>private slots@t\kern-3pt@>:@/
  9704. void updateTime();
  9705. void setCountUpMode();
  9706. void setCountDownMode();
  9707. void setClockMode();
  9708. public:@/
  9709. TimerDisplay(QWidget *parent = NULL);
  9710. ~TimerDisplay();
  9711. enum TimerMode
  9712. {
  9713. CountUp,
  9714. CountDown,
  9715. Clock
  9716. };
  9717. QString value();
  9718. QTime seconds();
  9719. TimerMode mode();
  9720. bool isRunning();
  9721. QTime resetValue();
  9722. QString displayFormat();
  9723. bool autoReset();@/
  9724. @t\4@>public slots@t\kern-3pt@>:@/
  9725. void setTimer(QTime value = QTime(0, 0, 0));
  9726. void setMode(TimerMode mode);
  9727. void startTimer();
  9728. void stopTimer();
  9729. void copyTimer();
  9730. void setResetValue(QTime value = QTime(0, 0, 0));
  9731. void reset();
  9732. void setDisplayFormat(QString format);
  9733. void setAutoReset(bool reset);
  9734. void updateDisplay();
  9735. signals:@/
  9736. void valueChanged(QTime);
  9737. void runStateChanged(bool);@/
  9738. private:@/
  9739. @<TimerDisplay Private Variables@>@;@t\2@>@/
  9740. }@t\kern-3pt@>;
  9741. @ Qt provides a property system based on its meta-object system. This allows for
  9742. a number of advanced features which \pn{} does not use. The properties available
  9743. for the TimerDisplay class exist for historical reasons, but there are some
  9744. plans for future development which may make use of them. The properties may also
  9745. be useful for someone using this class in another program.
  9746. @<TimerDisplay Properties@>=
  9747. Q_PROPERTY(QTime seconds READ seconds WRITE setTimer)@/
  9748. Q_PROPERTY(TimerMode mode READ mode WRITE setMode)@/
  9749. Q_PROPERTY(bool running READ isRunning)@/
  9750. Q_PROPERTY(QTime resetValue READ resetValue WRITE setResetValue)@/
  9751. Q_PROPERTY(QString displayFormat READ displayFormat WRITE setDisplayFormat)@/
  9752. Q_PROPERTY(bool autoReset READ autoReset WRITE setAutoReset)@/
  9753. Q_PROPERTY(QString value READ value)@/
  9754. @ A number of private variables are used to implement this class.
  9755. @<TimerDisplay Private Variables@>=
  9756. QTime s;
  9757. QTime r;
  9758. QTimer clock;
  9759. TimerDisplay::TimerMode m;
  9760. bool running;
  9761. bool ar;
  9762. QAction *startAction;
  9763. QAction *stopAction;
  9764. QAction *resetAction;
  9765. QString f;
  9766. QTime relative;
  9767. QTime base;
  9768. @ |TimerDisplay| is a specialization of |QLCDNumber| designed for time keeping
  9769. purposes. It sets up a timer that fires roughly every half second to see if it
  9770. needs to update itself. The constructor sets this up, but does not start the
  9771. timer. The class provides three actions which can be used to start, stop, or
  9772. reset the timer. These actions are also set up in the constructor.
  9773. By default, the timer will display its time in hours, minutes, and seconds. This
  9774. can be changed as is done with the batch timer (it is expected that nobody will
  9775. want to spend an hour or more to roast a batch of coffee). The display style is
  9776. also changed to a sensible default, but this can be changed with the usual
  9777. |QLCDNumber| methods.
  9778. @<TimerDisplay Implementation@>=
  9779. TimerDisplay::TimerDisplay(QWidget *parent) : QLCDNumber(8, parent),
  9780. s(QTime(0, 0, 0)), r(QTime(0, 0, 0)), clock(NULL),@/ m(TimerDisplay::CountUp),
  9781. running(false), ar(false), startAction(new QAction(tr("Start"), NULL)),@/
  9782. stopAction(new QAction(tr("Stop"), NULL)),
  9783. resetAction(new QAction(tr("Reset"), NULL)),@/ f(QString("hh:mm:ss")),
  9784. relative(QTime::currentTime()), base(QTime(0, 0, 0))@/
  9785. {
  9786. connect(startAction, SIGNAL(triggered(bool)), this, SLOT(startTimer()));
  9787. connect(stopAction, SIGNAL(triggered(bool)), this, SLOT(stopTimer()));
  9788. connect(resetAction, SIGNAL(triggered(bool)), this, SLOT(reset()));
  9789. clock.setInterval(500);
  9790. clock.setSingleShot(false);
  9791. connect(&clock, SIGNAL(timeout()), this, SLOT(updateTime()));
  9792. setSegmentStyle(Filled);
  9793. updateDisplay();
  9794. }
  9795. @ The complicated bits are all in the |updateTime()| method. The behavior of
  9796. this function depends on the current |TimerMode| of the display.
  9797. @<TimerDisplay Implementation@>=
  9798. void TimerDisplay::updateTime()
  9799. {
  9800. QTime time;
  9801. int cseconds = 0;
  9802. int oseconds = 0;
  9803. int r = 0;
  9804. QTime nt = QTime(0, 0, 0);
  9805. int n = 0;
  9806. int bseconds = 0;
  9807. switch(m)@/
  9808. {@t\1@>@/
  9809. case TimerDisplay::CountUp:@/
  9810. @<Check for Timer Increment@>;
  9811. break;
  9812. case TimerDisplay::CountDown:@/
  9813. @<Check for Timer Decrement@>;
  9814. break;
  9815. case TimerDisplay::Clock:@/
  9816. @<Check for Clock Change@>;
  9817. break;
  9818. default:@/
  9819. Q_ASSERT_X(false, "updateTime", "invalid timer mode");
  9820. break;@t\2@>@/
  9821. }
  9822. updateDisplay();
  9823. }
  9824. @ To have the timer count up, we calculate the value that the timer should
  9825. indicate and compare it to the time indicated. If there is a difference, we
  9826. update the time to the new value and send emit a signal.
  9827. @<Check for Timer Increment@>=
  9828. @<Load seconds since base time into r@>@;
  9829. nt = nt.addSecs(r);
  9830. if(nt != s)
  9831. {
  9832. s = nt;
  9833. emit valueChanged(s);
  9834. }
  9835. @ Here we want to calculate the number of seconds in the current time, the
  9836. number of seconds in a base time, and the difference between the two. The
  9837. value loaded into oseconds could probably be cached.
  9838. @<Load seconds since base time into r@>=
  9839. #define TIMETOINT(t) ((t.hour() * 60 * 60) + (t.minute() * 60) + (t.second()))
  9840. time = QTime::currentTime();
  9841. cseconds = TIMETOINT(time);
  9842. oseconds = TIMETOINT(relative);
  9843. r = cseconds - oseconds;
  9844. @ The logic for a count down timer is very similar to the logic for a count up
  9845. timer. A key difference is that we don'@q'@>t want to continue counting down if the
  9846. timer has already reached 0.
  9847. @<Check for Timer Decrement@>=
  9848. if(s > QTime(0, 0, 0))@/
  9849. {@/
  9850. @<Load seconds since base time into r@>@;
  9851. bseconds = TIMETOINT(base);
  9852. n = bseconds - r;
  9853. nt = nt.addSecs(n);
  9854. if(nt != s)
  9855. {
  9856. s = nt;
  9857. emit valueChanged(s);
  9858. }
  9859. } else {
  9860. stopTimer();
  9861. }
  9862. @ The clock mode is the simplest case as it just needs to find out if the time
  9863. has changed.
  9864. @<Check for Clock Change@>=
  9865. time = QTime::currentTime();
  9866. if(time != s)
  9867. {
  9868. s = time;
  9869. emit valueChanged(s);
  9870. }
  9871. @ When counting up or down, it is important to record the time at which the
  9872. timer starts. The clock that triggers time updates must also be started. The
  9873. timer also needs to reset its value if that behavior is desired.
  9874. @<TimerDisplay Implementation@>=
  9875. #define TIMESUBTRACT(t1, t2) (t1.addSecs(-(TIMETOINT(t2))).addSecs(-t2.msec()))
  9876. void TimerDisplay::startTimer()@t\2\2@>@/
  9877. {@t\1@>@/
  9878. if(!running)@/
  9879. {@t\1@>@/
  9880. relative = QTime::currentTime();
  9881. if(ar)@/
  9882. {
  9883. reset();
  9884. }
  9885. else
  9886. {
  9887. relative = TIMESUBTRACT(relative, s);
  9888. }
  9889. if(m == Clock)@/
  9890. {
  9891. updateTime();
  9892. }
  9893. base = s;
  9894. clock.start();@/
  9895. running = true;
  9896. emit runStateChanged(true);@t\2@>@/
  9897. }@t\2@>@/
  9898. }
  9899. @ Stopping the timer is a little simpler. Remember to stop the clock so we
  9900. aren'@q'@>t updating senselessly.
  9901. @<TimerDisplay Implementation@>=
  9902. void TimerDisplay::stopTimer()@t\2\2@>@/
  9903. {@t\1@>@/
  9904. if(running)@/
  9905. {@t\1@>@/
  9906. clock.stop();@/
  9907. running = false;
  9908. emit runStateChanged(false);@t\2@>@/
  9909. }@t\2@>@/
  9910. }
  9911. @ The clock is also stopped in the destructor.
  9912. @<TimerDisplay Implementation@>=
  9913. TimerDisplay::~TimerDisplay()
  9914. {
  9915. clock.stop();
  9916. }
  9917. @ The rest of the functions are trivial. There are functions for changing the
  9918. timer mode:
  9919. @<TimerDisplay Implementation@>=
  9920. void TimerDisplay::setCountUpMode()
  9921. {
  9922. m = TimerDisplay::CountUp;
  9923. }
  9924. void TimerDisplay::setCountDownMode()
  9925. {
  9926. m = TimerDisplay::CountDown;
  9927. }
  9928. void TimerDisplay::setClockMode()
  9929. {
  9930. m = TimerDisplay::Clock;
  9931. }
  9932. @ There are a few functions to obtain information about the state of the timer.
  9933. @<TimerDisplay Implementation@>=
  9934. QString TimerDisplay::value()
  9935. {
  9936. return s.toString(f);
  9937. }
  9938. QTime TimerDisplay::seconds()
  9939. {
  9940. return s;
  9941. }
  9942. TimerDisplay::TimerMode TimerDisplay::mode()
  9943. {
  9944. return m;
  9945. }
  9946. bool TimerDisplay::isRunning()
  9947. {
  9948. return running;
  9949. }
  9950. QTime TimerDisplay::resetValue()
  9951. {
  9952. return r;
  9953. }
  9954. QString TimerDisplay::displayFormat()
  9955. {
  9956. return f;
  9957. }
  9958. bool TimerDisplay::autoReset()
  9959. {
  9960. return ar;
  9961. }
  9962. @ There are also some functions for setting aspects of the timer state.
  9963. @<TimerDisplay Implementation@>=
  9964. void TimerDisplay::setTimer(QTime value)
  9965. {
  9966. if(value.isValid())
  9967. {
  9968. s = value;
  9969. updateDisplay();
  9970. emit valueChanged(value);
  9971. }
  9972. }
  9973. void TimerDisplay::setMode(TimerDisplay::TimerMode mode)
  9974. {
  9975. m = mode;
  9976. }
  9977. void TimerDisplay::setResetValue(QTime value)
  9978. {
  9979. r = value;
  9980. }
  9981. void TimerDisplay::setDisplayFormat(QString format)
  9982. {
  9983. f = format;
  9984. setNumDigits(format.length());
  9985. }
  9986. void TimerDisplay::setAutoReset(bool reset)
  9987. {
  9988. ar = reset;
  9989. }
  9990. @ |TimerDisplay| supports using the system clipboard to copy the current timer
  9991. value.
  9992. @<TimerDisplay Implementation@>=
  9993. void TimerDisplay::copyTimer()
  9994. {
  9995. QApplication::clipboard()->setText(value());
  9996. }
  9997. @ Resetting the timer is simple. We don'@q'@>t reset the timer if it is still running
  9998. mainly to prevent accidents.
  9999. @<TimerDisplay Implementation@>=
  10000. void TimerDisplay::reset()
  10001. {
  10002. if(!running)
  10003. {
  10004. s = r;
  10005. updateDisplay();
  10006. }
  10007. }
  10008. @ Finally, there is the function for changing the text of the display to the
  10009. current time value.
  10010. @<TimerDisplay Implementation@>=
  10011. void TimerDisplay::updateDisplay()
  10012. {
  10013. display(value());
  10014. }
  10015. @ Exposing |TimerDisplay| to the host environment is simple.
  10016. @<Function prototypes for scripting@>=
  10017. QScriptValue constructTimerDisplay(QScriptContext *context,
  10018. QScriptEngine *engine);
  10019. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine);
  10020. QScriptValue TimerDisplay_setTimerMode(QScriptContext *context, QScriptEngine *engine);
  10021. @ The engine must be informed of the script constructor.
  10022. @<Set up the scripting engine@>=
  10023. constructor = engine->newFunction(constructTimerDisplay);
  10024. value = engine->newQMetaObject(&TimerDisplay::staticMetaObject, constructor);
  10025. engine->globalObject().setProperty("TimerDisplay", value);
  10026. @ The implementation of these functions is trivial.
  10027. @<Functions for scripting@>=
  10028. QScriptValue constructTimerDisplay(QScriptContext *, QScriptEngine *engine)
  10029. {
  10030. QScriptValue object = engine->newQObject(new TimerDisplay);
  10031. setTimerDisplayProperties(object, engine);
  10032. return object;
  10033. }
  10034. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine)
  10035. {
  10036. setQLCDNumberProperties(value, engine);
  10037. value.setProperty("setTimerMode", engine->newFunction(TimerDisplay_setTimerMode));
  10038. }
  10039. @ A new feature in \pn{} 1.6.4 benefits from having the ability to set the
  10040. timer mode from a script. Rather than exposing the |enum| responsible for this
  10041. to the host environment, a new function is provided to allow integer based
  10042. setting.
  10043. @<Functions for scripting@>=
  10044. QScriptValue TimerDisplay_setTimerMode(QScriptContext *context, QScriptEngine *)
  10045. {
  10046. TimerDisplay *self = getself<TimerDisplay *>(context);
  10047. if(self)
  10048. {
  10049. switch(argument<int>(0, context))
  10050. {
  10051. case 0:
  10052. self->setMode(TimerDisplay::CountUp);
  10053. break;
  10054. case 1:
  10055. self->setMode(TimerDisplay::CountDown);
  10056. break;
  10057. case 2:
  10058. self->setMode(TimerDisplay::Clock);
  10059. break;
  10060. default:
  10061. break;
  10062. }
  10063. }
  10064. return QScriptValue();
  10065. }
  10066. @** The Human Computer Interface.
  10067. \noindent A few classes are required for putting the rest of the program
  10068. together in a way that it can be used by a human. There is a layout class for
  10069. arranging widgets in a way that is not simple with the layouts provided by Qt.
  10070. There are classes for labeling the various indicators. There are also window
  10071. classes that put all of this together in a useful and usable way. One of these
  10072. classes is currently depreciated.
  10073. @* The PackLayout Class.
  10074. \noindent The |PackLayout| class provides functionality similar to the
  10075. |QBoxLayout| class in Qt. It allows the construction of a row or column of
  10076. widgets. Each item will take up space along the orientation of the layout equal
  10077. to its size hint except for the last widget which will take up all remaining
  10078. space. Widgets will be resized in the direction perpendicular to the orientation
  10079. of the layout to use all available space.
  10080. This class was originally written with the |WidgetDecorator| class which we will
  10081. get to later in mind, but it has found use in other places where the left or top
  10082. most widgets should not be resized.
  10083. By default, a new |PackLayout| will arrange widgets horizontally. This can be
  10084. changed with a call to |setOrientation()|.
  10085. @<Class declarations@>=
  10086. class PackLayout : public QLayout@/
  10087. {@/
  10088. int doLayout(const QRect &rect, bool testOnly) const;@/
  10089. QList<QLayoutItem *> itemList;@/
  10090. Qt::Orientations@, orientation;@/
  10091. public:@/
  10092. PackLayout(QWidget *parent, int margin = 0, int spacing = -1);
  10093. PackLayout(int spacing = -1);
  10094. ~PackLayout();
  10095. void addItem(QLayoutItem *item);
  10096. Qt::Orientations@, expandingDirections() const;
  10097. bool hasHeightForWidth() const;
  10098. int heightForWidth(int width) const;
  10099. int count() const;
  10100. QLayoutItem *itemAt(int index) const;
  10101. QSize minimumSize() const;
  10102. void setGeometry(const QRect &rect);
  10103. void setOrientation(Qt::Orientations direction);
  10104. QSize sizeHint() const;
  10105. QLayoutItem *takeAt(int index);
  10106. };
  10107. @ The interesting portion of this class is in |doLayout()|. This function goes
  10108. over the items in the layout and sets the geometry appropriately.
  10109. The seemingly odd choice of returning |y| at the end of this function (indeed of
  10110. having a return value at all) is to allow this function to provide the return
  10111. value needed in |heightForWidth()|.
  10112. If |testOnly| is set to |true|, |y| will be calculated, but the widget geometry
  10113. will not be changed.
  10114. @<PackLayout Implementation@>=
  10115. int PackLayout::doLayout(const QRect &rect, bool testOnly) const
  10116. {
  10117. int x = rect.x();
  10118. int y = rect.y();
  10119. QLayoutItem *item;
  10120. if(orientation == Qt::Horizontal)
  10121. {
  10122. @<Lay the widgets out horizontally@>@;
  10123. }
  10124. else
  10125. {
  10126. @<Lay the widgets out vertically@>@;
  10127. }
  10128. return y;
  10129. }
  10130. @ To lay the widgets out horizontally, we go over each item in the list taking
  10131. the width of the size hint and spacing into account unless the item is the last
  10132. item in the list, in which case the right of the widget needs to be at the end
  10133. of the available space. We use the foreach construction that Qt provides to
  10134. iterate over each item in the list in much the same way as foreach constructions
  10135. are used in languages that support them directly.
  10136. @<Lay the widgets out horizontally@>=
  10137. foreach(item, itemList)
  10138. {
  10139. int nextX = x + item->sizeHint().width() + spacing();
  10140. int right = x + item->sizeHint().width();
  10141. if(item == itemList.last())
  10142. {
  10143. right = rect.right();
  10144. }
  10145. int bottom = rect.bottom();
  10146. if(!testOnly)
  10147. {
  10148. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  10149. }
  10150. x = nextX;
  10151. }
  10152. @ Laying out the widgets vertically is very similar.
  10153. @<Lay the widgets out vertically@>=
  10154. foreach(item, itemList)
  10155. {
  10156. int nextY = y + item->sizeHint().height() + spacing();
  10157. int bottom = y + item->sizeHint().height();
  10158. if(item == itemList.last())
  10159. {
  10160. bottom = rect.bottom();
  10161. }
  10162. int right = rect.right();
  10163. if(!testOnly)
  10164. {
  10165. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  10166. }
  10167. y = nextY;
  10168. }
  10169. @ As a layout class, there are a number of things the class should be able to do
  10170. in order to play nicely with other classes. One of these is determining the
  10171. minimum size of the layout. The minimum size of the layout is equal to the space
  10172. required for each item in the layout plus the margin space. The margin space
  10173. will be equal to twice the specified margin in each direction to account for a
  10174. top, bottom, left, and right margin.
  10175. @<PackLayout Implementation@>=
  10176. QSize PackLayout::minimumSize() const
  10177. {
  10178. QSize size;
  10179. QLayoutItem *item;
  10180. foreach(item, itemList)
  10181. {
  10182. if(orientation == Qt::Horizontal)
  10183. {
  10184. size += QSize(item->minimumSize().width(), 0);
  10185. if(size.height() < item->minimumSize().height())
  10186. {
  10187. size.setHeight(item->minimumSize().height());
  10188. }
  10189. }
  10190. else
  10191. {
  10192. size += QSize(0, item->minimumSize().height());
  10193. if(size.width() < item->minimumSize().width())
  10194. {
  10195. size.setWidth(item->minimumSize().width());
  10196. }
  10197. }
  10198. }
  10199. size += QSize(2*margin(), 2*margin());
  10200. return size;
  10201. }
  10202. @ |PackLayout| features two constructors. One allows for setting the margin,
  10203. spacing, and a parent widget at the time of construction. The other creates a
  10204. parentless layout which will have to be added to another widget or layout.
  10205. @<PackLayout Implementation@>=
  10206. PackLayout::PackLayout(QWidget *parent, int margin, int spacing) :
  10207. QLayout(parent)@/
  10208. {
  10209. setMargin(margin);
  10210. setSpacing(spacing);
  10211. setOrientation(Qt::Horizontal);
  10212. }
  10213. PackLayout::PackLayout(int spacing)
  10214. {
  10215. setSpacing(spacing);
  10216. setOrientation(Qt::Horizontal);
  10217. }
  10218. @ In Qt, items in a layout are owned by that layout. When the layout is
  10219. destroyed, all of the items in that layout must also be deleted.
  10220. @<PackLayout Implementation@>=
  10221. PackLayout::~PackLayout()
  10222. {
  10223. QLayoutItem *item;
  10224. while((item = takeAt(0)))
  10225. {
  10226. delete item;
  10227. }
  10228. }
  10229. @ Deleting the items uses the |takeAt()| method to remove each widget from the
  10230. layout prior to deleting it. The item requested should exist, but if it doesn'@q'@>t,
  10231. |NULL| is returned.
  10232. @<PackLayout Implementation@>=
  10233. QLayoutItem* PackLayout::takeAt(int index)
  10234. {
  10235. if(index >= 0 && index < itemList.size())
  10236. {
  10237. return itemList.takeAt(index);
  10238. }
  10239. else
  10240. {
  10241. return NULL;
  10242. }
  10243. }
  10244. @ If we are interested in which item is in a particular position in the layout
  10245. but do not want to remove it from the layout, |itemAt()| provides that.
  10246. @<PackLayout Implementation@>=
  10247. QLayoutItem* PackLayout::itemAt(int index) const
  10248. {
  10249. if(index >= 0 && index < itemList.size())
  10250. {
  10251. return itemList.at(index);
  10252. }
  10253. else
  10254. {
  10255. return NULL;
  10256. }
  10257. }
  10258. @ A layout class is not very useful unless there is a way to get items into the
  10259. layout. The |QLayoutItem| class is designed in such a way that it is possible to
  10260. pass pointers to objects that inherit |QLayout| or |QWidget|.
  10261. The base |QLayout| class provides an |addWidget()| method that will use our
  10262. version of |addItem()|. That should be used when adding a widget to the layout.
  10263. The Qt documentation recommends also providing an |addLayout()| method so that
  10264. other code does not need to call this method, but that has not been provided
  10265. yet.
  10266. @<PackLayout Implementation@>=
  10267. void PackLayout::addItem(QLayoutItem *item)
  10268. {
  10269. itemList.append(item);
  10270. }
  10271. @ It is sometimes useful to know how many items are in a layout.
  10272. @<PackLayout Implementation@>=
  10273. int PackLayout::count() const@;@/
  10274. {@/
  10275. return itemList.size();@/
  10276. }
  10277. @ A few more functions are needed to make the layout class work well with other
  10278. classes. For more details, please consult the Qt Reference
  10279. Documentation\nfnote{Qt Reference Documentation\par\indent\hbox{%
  10280. \pdfURL{http://doc.trolltech.com/4.3/index.html}%
  10281. {http://doc.trolltech.com/4.3/index.html}}}
  10282. @<PackLayout Implementation@>=
  10283. Qt::Orientations PackLayout::expandingDirections() const
  10284. {
  10285. return Qt::Vertical | Qt::Horizontal;
  10286. }
  10287. bool PackLayout::hasHeightForWidth() const@t\2\2@>@/
  10288. {@t\1@>@/
  10289. return false;@t\2@>@/
  10290. }@/
  10291. int PackLayout::heightForWidth(int width) const
  10292. {
  10293. return doLayout(QRect(0, 0, width, 0), true);
  10294. }
  10295. void PackLayout::setGeometry(const QRect &rect)
  10296. {
  10297. QLayout::setGeometry(rect);
  10298. doLayout(rect, false);
  10299. }
  10300. QSize PackLayout::sizeHint() const
  10301. {
  10302. return minimumSize();
  10303. }
  10304. @ It was mentioned previously that this layout is capable of lining widgets up
  10305. in a row or presenting them in a column. This is done with the
  10306. |setOrientation()| method.
  10307. @<PackLayout Implementation@>=
  10308. void PackLayout::setOrientation(Qt::Orientations direction)
  10309. {
  10310. orientation = direction;
  10311. doLayout(geometry(), false);
  10312. }
  10313. @* The SceneButton Class.
  10314. \noindent Ordinarily, mouse down events that are passed from a |QGraphicsView|
  10315. to an interactive |QGraphicsScene| will continue to pass that click down to an
  10316. item in the scene. This class is used when we are interested in a click anywhere
  10317. in the view and it doesn'@q'@>t really matter where in the scene that click occurred
  10318. or even if there is a graphics item at that point. Any click passed to the
  10319. |SceneButton| will cause the scene to emit a signal containing the screen
  10320. coordinates of the click.
  10321. This was originally designed for use in the |WidgetDecorator| class. While the
  10322. functionality provided is not currently used, the original plan was to use this
  10323. to provide access to configuration options.
  10324. It is possible that this class is no longer necessary even if features it was
  10325. made for are implemented.
  10326. @<Class declarations@>=
  10327. class SceneButton : public QGraphicsScene@/
  10328. {@/
  10329. Q_OBJECT@;
  10330. public:@/
  10331. SceneButton();
  10332. ~SceneButton();
  10333. protected:@/
  10334. void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
  10335. signals:@/
  10336. void clicked(QPoint pos);
  10337. };
  10338. @ The implementation is trivial.
  10339. @<SceneButton Implementation@>=
  10340. SceneButton::SceneButton() : QGraphicsScene()@/
  10341. {
  10342. /* Nothing has to be done here. */
  10343. }
  10344. SceneButton::~SceneButton()
  10345. {
  10346. /* Nothing has to be done here. */
  10347. }
  10348. void SceneButton::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
  10349. {
  10350. emit clicked(mouseEvent->buttonDownScreenPos(mouseEvent->button()));
  10351. }
  10352. @* The WidgetDecorator Class.
  10353. \noindent The |WidgetDecorator| class provides a way to label various widgets
  10354. while also providing additional options for interacting with them. The
  10355. decoration can exist to the left or atop the widget being decorated. When the
  10356. label is to the left of the widget, the label text is rotated.
  10357. This class is likely to change considerably in the future as features are added
  10358. that allow actions to be added to the decoration to allow various configuration
  10359. options.
  10360. @<Class declarations@>=
  10361. class WidgetDecorator : public QWidget@/
  10362. {
  10363. Q_OBJECT@;
  10364. PackLayout *layout;
  10365. QGraphicsView *label;
  10366. QGraphicsTextItem *text;
  10367. SceneButton *scene;
  10368. public:@/
  10369. WidgetDecorator(QWidget *widget, const QString &labeltext,@|
  10370. Qt::Orientations@, orientation = Qt::Horizontal,@|
  10371. QWidget *parent = NULL, Qt::WindowFlags f = 0);
  10372. ~WidgetDecorator();
  10373. void setBackgroundBrush(QBrush background);
  10374. void setTextColor(QColor color);
  10375. };
  10376. @ Almost everything this class currently does is handled in the constructor.
  10377. @<WidgetDecorator Implementation@>=
  10378. WidgetDecorator::WidgetDecorator(QWidget *widget, const QString &labeltext,
  10379. Qt::Orientations orientation,
  10380. QWidget *parent, Qt::WindowFlags f)@/:
  10381. QWidget(parent, f), label(new QGraphicsView()),
  10382. scene(new SceneButton())@t\2@>@/
  10383. {
  10384. layout = new PackLayout(this);
  10385. layout->setOrientation(orientation);
  10386. @<Prepare the graphics view@>@;
  10387. @<Add the label to the scene@>@;
  10388. @<Adjust the decoration width@>@;
  10389. @<Pack widgets into the layout@>@;
  10390. }
  10391. @ The decoration is a |QGraphicsView|. To get this to look right, we need to
  10392. make sure there aren'@q'@>t any scroll bars and there shouldn'@q'@>t be a frame
  10393. surrounding it. While we'@q'@>re at it, we allow it to accept clicks, though this
  10394. functionality is not yet used.
  10395. @<Prepare the graphics view@>=
  10396. label->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  10397. label->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  10398. label->setFrameShape(QFrame::NoFrame);
  10399. label->setInteractive(true);
  10400. @ The |QGraphicsView| needs a scene to display anything. The scene consists of a
  10401. background which, by default is solid cyan. This can be changed later by setting
  10402. a different background brush. Text also needs to be added to the scene. If the
  10403. decoration is to the left of the widget, the text needs to be rotated.
  10404. @<Add the label to the scene@>=
  10405. scene->setBackgroundBrush(Qt::cyan);
  10406. text = scene->addText(labeltext);
  10407. if(orientation == Qt::Horizontal)
  10408. {
  10409. text->rotate(270.0);
  10410. }
  10411. label->setScene(scene);
  10412. @ The decoration should have the text centered in the view. The widget should
  10413. also be no wider (or taller for horizontal orientation) than necessary for the
  10414. text.
  10415. The case for horizontal orientation here may seem a little strange, however the
  10416. dimensions of the bounding rectangle are not affected by rotation. This means
  10417. that even though we want the width of the rotated text, this is the same as the
  10418. height of the text.
  10419. @<Adjust the decoration width@>=
  10420. if(orientation == Qt::Horizontal)
  10421. {
  10422. label->setMaximumWidth((int)(text->boundingRect().height() + 1));
  10423. }
  10424. else
  10425. {
  10426. label->setMaximumHeight((int)(text->boundingRect().height() + 1));
  10427. }
  10428. label->centerOn(text);
  10429. @ Once the decoration is ready, the decoration and the widget being decorated
  10430. can be added to the layout. A minimum size for the compound widget is also
  10431. calculated.
  10432. @<Pack widgets into the layout@>=
  10433. layout->addWidget(label);
  10434. layout->addWidget(widget);
  10435. if(orientation == Qt::Horizontal)
  10436. {
  10437. setMinimumSize(widget->sizeHint().width() + label->sizeHint().width(),
  10438. widget->sizeHint().height());
  10439. }
  10440. else
  10441. {
  10442. setMinimumSize(widget->sizeHint().width(),
  10443. widget->sizeHint().height() + label->sizeHint().height());
  10444. }
  10445. @ As mentioned previously, it is possible to change the background pattern for
  10446. the decoration. It is also possible to change the color of the text.
  10447. @<WidgetDecorator Implementation@>=
  10448. void WidgetDecorator::setBackgroundBrush(QBrush background)
  10449. {
  10450. scene->setBackgroundBrush(background);
  10451. }
  10452. void WidgetDecorator::setTextColor(QColor color)
  10453. {
  10454. text->setDefaultTextColor(color);
  10455. }
  10456. @ Finally, there is a destructor.
  10457. @<WidgetDecorator Implementation@>=
  10458. WidgetDecorator::~WidgetDecorator()
  10459. {
  10460. /* Nothing has to be done here. */
  10461. }
  10462. @ In order to create a decorated widget from a script, we need these functions.
  10463. @<Function prototypes for scripting@>=
  10464. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine);
  10465. QScriptValue constructWidgetDecorator(QScriptContext *context,
  10466. QScriptEngine *engine);
  10467. @ The scripting engine must be informed of this function.
  10468. @<Set up the scripting engine@>=
  10469. constructor = engine->newFunction(constructWidgetDecorator);
  10470. value = engine->newQMetaObject(&WidgetDecorator::staticMetaObject, constructor);
  10471. engine->globalObject().setProperty("WidgetDecorator", value);
  10472. @ The constructor is slightly more complex than other script constructors, but
  10473. still simple.
  10474. @<Functions for scripting@>=
  10475. QScriptValue constructWidgetDecorator(QScriptContext *context,
  10476. QScriptEngine *engine)
  10477. {
  10478. QWidget *widget = argument<QWidget *>(0, context);
  10479. QString text = argument<QString>(1, context);
  10480. Qt::Orientations@, orientation;
  10481. switch(argument<int>(2, context))@/
  10482. {@t\1@>@/
  10483. case 2:@/
  10484. orientation = Qt::Vertical;
  10485. break;
  10486. default:@/
  10487. orientation = Qt::Horizontal;
  10488. break;@t\2@>@/
  10489. }
  10490. QScriptValue object =
  10491. engine->newQObject(new WidgetDecorator(widget, text, orientation));
  10492. setWidgetDecoratorProperties(object, engine);
  10493. return object;
  10494. }
  10495. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine)
  10496. {
  10497. setQWidgetProperties(value, engine);
  10498. }
  10499. @* The LogEditWindow Class.
  10500. \noindent This class will be depreciated in a future release once I have
  10501. confirmed that the class can be replaced by the configuration system. It has not
  10502. been updated to support new functionality added in version 1.2.3 and use of this
  10503. class is highly discouraged.
  10504. While the logging window provided in the example configuration is fine for
  10505. recording an existing roast, there are some who would like to be able to use
  10506. \pn{} to work with data collected with a manual logger. Different controls are
  10507. useful in such a case. The |LogEditWindow| provides this.
  10508. @<Class declarations@>=
  10509. class LogEditWindow : public QMainWindow@/
  10510. {@t\1@>@/
  10511. Q_OBJECT@;
  10512. QWidget *centralWidget;
  10513. PackLayout *mainLayout;
  10514. QHBoxLayout *addRowsLayout;
  10515. QLabel *startTimeLabel;
  10516. QTimeEdit *startTime;
  10517. QLabel *endTimeLabel;
  10518. QTimeEdit *endTime;
  10519. QLabel *intervalLabel;
  10520. QSpinBox *interval;
  10521. QPushButton *addRows;
  10522. QAction *saveXml;
  10523. QAction *saveCsv;
  10524. QAction *openXml;
  10525. MeasurementModel *model;
  10526. QTableView *log;@/
  10527. @t\4@>private slots@t\kern-3pt@>:@/
  10528. void addTheRows();
  10529. void saveXML();
  10530. void saveCSV();
  10531. void openXML();@/
  10532. protected:@/
  10533. void closeEvent(QCloseEvent *event);@/
  10534. public:@/
  10535. LogEditWindow();@t\2@>@/
  10536. }@t\kern-3pt@>;
  10537. @ This window provides controls for adding rows to a measurement. Typically, the
  10538. data on a manual roast log will have measurements at regular intervals with the
  10539. possible exception of a few points where there are control changes or the end of
  10540. the batch. The routine for adding rows is capable of adding a single row, rows
  10541. in a range of times at regular intervals, or rows in a range of times at regular
  10542. intervals plus one time at the end.
  10543. @<LogEditWindow Implementation@>=
  10544. void LogEditWindow::addTheRows()
  10545. {
  10546. QTime s = startTime->time();
  10547. while(s < endTime->time())
  10548. {
  10549. model->newMeasurement(Measurement(0, s), 1);
  10550. s = s.addSecs(interval->value());
  10551. }
  10552. model->newMeasurement(Measurement(0, endTime->time()), 1);
  10553. }
  10554. @ The window is prepared in its constructor.
  10555. @<LogEditWindow Implementation@>=
  10556. LogEditWindow::LogEditWindow() : QMainWindow(NULL),
  10557. centralWidget(new QWidget(NULL)), mainLayout(new PackLayout(0)),@|
  10558. addRowsLayout(new QHBoxLayout(NULL)),
  10559. startTimeLabel(new QLabel("Start Time")),@|
  10560. startTime(new QTimeEdit(QTime(0, 0, 0, 0))),@|
  10561. endTimeLabel(new QLabel("End Time")),
  10562. endTime(new QTimeEdit(QTime(0, 20, 0, 0))),@|
  10563. intervalLabel(new QLabel("Interval (seconds)")),@|
  10564. interval(new QSpinBox()),
  10565. addRows(new QPushButton("Add Rows")),@|
  10566. saveXml(new QAction(tr("Save Profile As..."), NULL)),@|
  10567. saveCsv(new QAction(tr("Export CSV"), NULL)),@|
  10568. openXml(new QAction(tr("Load Target Profile..."), NULL)),@|
  10569. model(new MeasurementModel()),
  10570. log(new QTableView())@/
  10571. {
  10572. @<Restore editor window geometry from settings@>@;
  10573. @<Set up the editor control bar@>@;
  10574. @<Prepare the model@>@;
  10575. @<Prepare the log table@>@;
  10576. mainLayout->addItem(addRowsLayout);
  10577. mainLayout->addWidget(log);
  10578. centralWidget->setLayout(mainLayout);
  10579. setCentralWidget(centralWidget);
  10580. QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
  10581. fileMenu->addAction(openXml);
  10582. connect(openXml, SIGNAL(triggered()), this, SLOT(openXML()));
  10583. fileMenu->addAction(saveXml);
  10584. connect(saveXml, SIGNAL(triggered()), this, SLOT(saveXML()));
  10585. fileMenu->addAction(saveCsv);
  10586. connect(saveCsv, SIGNAL(triggered()), this, SLOT(saveCSV()));
  10587. }
  10588. @ The window keeps its previous size and location in settings. These need to be
  10589. restored when a new window is created.
  10590. @<Restore editor window geometry from settings@>=
  10591. QSettings settings;
  10592. resize(settings.value("logSize", QSize(620,400)).toSize());
  10593. move(settings.value("logPos", QPoint(200,60)).toPoint());
  10594. @ When a new window is opened, it starts with an empty profile. If this is used
  10595. to manually enter a profile rather than edit an existing profile, rows will need
  10596. to be added. For this, we provide a set of controls where a start time, an end
  10597. time, and an interval in seconds is specified along with a button that, when
  10598. pressed, will produce a row in the model for the starting time, the ending time,
  10599. and regularly spaced times between the two. If only a single row is needed, this
  10600. can be produced by setting the start and end times the same.
  10601. @<Set up the editor control bar@>=
  10602. mainLayout->setOrientation(Qt::Vertical);
  10603. addRowsLayout->addSpacing(10);
  10604. addRowsLayout->addWidget(startTimeLabel);
  10605. addRowsLayout->addWidget(startTime);
  10606. addRowsLayout->addSpacing(10);
  10607. startTime->setDisplayFormat("mm:ss");
  10608. addRowsLayout->addWidget(endTimeLabel);
  10609. addRowsLayout->addWidget(endTime);
  10610. addRowsLayout->addSpacing(10);
  10611. endTime->setDisplayFormat("mm:ss");
  10612. addRowsLayout->addWidget(intervalLabel);
  10613. addRowsLayout->addWidget(interval);
  10614. addRowsLayout->addSpacing(10);
  10615. interval->setRange(0, 60);
  10616. interval->setValue(30);
  10617. addRowsLayout->addWidget(addRows);
  10618. addRowsLayout->addSpacing(10);
  10619. connect(addRows, SIGNAL(clicked()), this, SLOT(addTheRows()));
  10620. @ The model will have three columns: Time, Temperature, and Annotation. This
  10621. probably should not be hard coded.
  10622. @<Prepare the model@>=
  10623. model->setHeaderData(0, Qt::Horizontal, "Time");
  10624. model->setHeaderData(1, Qt::Horizontal, "Temperature");
  10625. model->setHeaderData(2, Qt::Horizontal, "Annotation");
  10626. model->clear();
  10627. @ The profile is presented in a table view. The columns should be wide enough to
  10628. contain a label, the data contained in the column, and an editor delegate.
  10629. @<Prepare the log table@>=
  10630. log->setModel(model);
  10631. log->setColumnWidth(0, 100);
  10632. log->setColumnWidth(1, 100);
  10633. log->setColumnWidth(2, 100);
  10634. @ Most users will want to save a profile after they'@q'@>ve edited it. We also
  10635. provide CSV export here. Note that this class only supports logs with a single
  10636. temperature and a single annotation column. As the class is considered
  10637. depreciated, it will not be extended to support arbitrarily many columns.
  10638. @<LogEditWindow Implementation@>=
  10639. void LogEditWindow::saveXML()
  10640. {
  10641. QSettings settings;
  10642. QString lastDir = settings.value("lastDirectory").toString();
  10643. QString filename = QFileDialog::getSaveFileName(this, tr("Save Log As..."),
  10644. lastDir, "", 0);
  10645. QFile file(filename);
  10646. XMLOutput writer(model, &file, 0);
  10647. writer.addTemperatureColumn("Temperature", 1);
  10648. writer.addAnnotationColumn("Annotation", 2);
  10649. if(writer.output())
  10650. {
  10651. QFileInfo info(filename);
  10652. QDir directory = info.dir();
  10653. lastDir = directory.path();
  10654. settings.setValue("lastDirectory", lastDir);
  10655. }
  10656. }
  10657. void LogEditWindow::saveCSV()
  10658. {
  10659. QSettings settings;
  10660. QString lastDir = settings.value("lastDirectory").toString();
  10661. QString filename = QFileDialog::getSaveFileName(this, tr("Export As..."),
  10662. lastDir, "", 0);
  10663. QFile file(filename);
  10664. CSVOutput writer(model, &file, 0);
  10665. writer.addTemperatureColumn("Temperature", 1);
  10666. writer.addAnnotationColumn("Annotation", 2);
  10667. if(writer.output())
  10668. {
  10669. QFileInfo info(filename);
  10670. QDir directory = info.dir();
  10671. lastDir = directory.path();
  10672. settings.setValue("lastDirectory", lastDir);
  10673. }
  10674. }
  10675. @ Some may want to open a previously saved profile, for example, to adjust the
  10676. position of an annotation. Note that this class is not appropriate for editing
  10677. profiles with more than one temperature column.
  10678. @<LogEditWindow Implementation@>=
  10679. void LogEditWindow::openXML()
  10680. {
  10681. QSettings settings;
  10682. QString lastDir = settings.value("lastDirectory").toString();
  10683. QString filename = QFileDialog::getOpenFileName(this, tr("Open XML Log..."),
  10684. lastDir, "", 0);
  10685. if(filename.isNull())
  10686. {
  10687. return;
  10688. }
  10689. QFile file(filename);
  10690. XMLInput reader(&file, 1);
  10691. connect(&reader, SIGNAL(measure(Measurement, int)),
  10692. model, SLOT(newMeasurement(Measurement, int)));
  10693. connect(&reader, SIGNAL(annotation(QString, int, int)),
  10694. model, SLOT(newAnnotation(QString, int, int)));
  10695. if(reader.input())
  10696. {
  10697. QFileInfo info(filename);
  10698. setWindowTitle(QString(tr("%1 - %2")).@|
  10699. arg(QCoreApplication::applicationName()).arg(info.baseName()));
  10700. QDir directory = info.dir();
  10701. lastDir = directory.path();
  10702. settings.setValue("lastDirectory", lastDir);
  10703. }
  10704. }
  10705. @ The window should remember its last size and position, so we store this
  10706. information in settings when the window is closed.
  10707. @<LogEditWindow Implementation@>=
  10708. void LogEditWindow::closeEvent(QCloseEvent *event)
  10709. {
  10710. QSettings settings;
  10711. settings.setValue("logSize", size());
  10712. settings.setValue("logPos", pos());
  10713. event->accept();
  10714. }
  10715. @ One function is required to instantiate this class from a script.
  10716. @<Function prototypes for scripting@>=
  10717. QScriptValue constructLogEditWindow(QScriptContext *context,
  10718. QScriptEngine *engine);
  10719. @ The engine must be informed of this function.
  10720. @<Set up the scripting engine@>=
  10721. constructor = engine->newFunction(constructLogEditWindow);
  10722. value = engine->newQMetaObject(&LogEditWindow::staticMetaObject, constructor);
  10723. engine->globalObject().setProperty("LogEditWindow", value);
  10724. @ The constructor just creates the window and passes it back to the engine.
  10725. @<Functions for scripting@>=
  10726. QScriptValue constructLogEditWindow(QScriptContext *, QScriptEngine *engine)
  10727. {
  10728. QScriptValue object = engine->newQObject(new LogEditWindow);
  10729. return object;
  10730. }
  10731. @** File IO.
  10732. \noindent So far, the data is all stored in memory. It is often useful to save
  10733. data to a file or read back previously saved data. Presently, two formats are
  10734. supported: an XML format which can also be read back in and CSV which can easily
  10735. be used with many external tools.
  10736. File IO is handled by a few classes: one per input format and one per output
  10737. format. The classes in the following sections should be simple enough to follow
  10738. that it should be clear how to extend \pn{} to support other formats if needed.
  10739. Should additional output formats be required, it may be beneficial to
  10740. reimplement the serializers as subclasses of a new abstract serializer class in
  10741. order to share common code among them where reusing \cweb{} chunks is not an
  10742. appropriate technique.
  10743. @* XML Output.
  10744. \noindent An XML format has been chosen as the native format for \pn{} because
  10745. of Qt'@q'@>s excellent support for reading and writing such documents. Using this
  10746. capability is less error prone than developing a new, more compact format.
  10747. Another reason to choose XML is that it becomes quite easy to modify saved data
  10748. in a text editor and still end up with something \pn{} will understand.
  10749. The structure of the file we will produce is simple, however it has been
  10750. modified from a simpler structure that was used in versions of Typica prior to
  10751. 1.2.3. How to read these files can be determined by the document type found at
  10752. the start of the file. At the start of the file, there should be one or more
  10753. {\tt <tempseries>} elements and one or more {\tt <noteseries>} elements. These
  10754. are empty elements with a {\tt name} attribute which can be used to label the
  10755. column in a view. Once these column declarations have been written, a
  10756. {\tt <roast>} element is produced which contains a set of zero or more
  10757. {\tt <tuple>} elements. Each tuple contains one {\tt <time>} element containing
  10758. the time of the measurement relative to the start of the batch and optionally
  10759. one or more {\tt <temperature>} and {\tt <annotation>} elements containing
  10760. measurement and annotation data associated with that time. The
  10761. {\tt <temperature>} and {\tt <annotation>} elements have a {\tt series}
  10762. attribute where the value of the attribute matches the {\tt name} attribute of a
  10763. {\tt <tempseries>} or {\tt <noteseries>} element which allows each measurement
  10764. to be placed in the correct data series regardless of element ordering in the
  10765. document.
  10766. There are certain oddities about this format compared with other XML based
  10767. formats. The order of some elements in the current implementation affects the
  10768. behavior of the program and there is no longer a proper root element. This
  10769. format may be extended in future versions of \pn{} to support additional
  10770. functionality or to improve the robustness of the format. Should such
  10771. modifications occur, an effort should be made to ensure that \pn{} continues to
  10772. support the import of old data.
  10773. As of version 1.0.8, this class is derived from |QObject| for easier integration
  10774. with the scripting engine.
  10775. The |temperatureColumns| and |annotationColumns| member data structures are
  10776. currently a |QMap| rather than a |QHash| because the number of data series in a
  10777. single file is likely to be small enough that the difference in lookup time
  10778. should be negligeable and the ability to iterate over the keys in the |QMap| in
  10779. sorted order is useful.
  10780. @<Class declarations@>=
  10781. class XMLOutput : public QObject@/
  10782. {@/
  10783. Q_OBJECT@;@/
  10784. MeasurementModel *data;
  10785. QIODevice *out;
  10786. int time;
  10787. QMap<int, QString> temperatureColumns;
  10788. QMap<int, QString> controlColumns;
  10789. QMap<int, QString> annotationColumns;
  10790. public:@/
  10791. XMLOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  10792. void addTemperatureColumn(const QString &series, int column);
  10793. void addControlColumn(const QString &series, int column);
  10794. void addAnnotationColumn(const QString &series, int column);
  10795. void setModel(MeasurementModel *model);
  10796. void setTimeColumn(int column);
  10797. void setDevice(QIODevice *device);
  10798. bool output();
  10799. };
  10800. @ The interesting part of this class is the |output| routine. This goes over the
  10801. data in the model and constructs an appropriate XML document. If the operation
  10802. fails, the function returns |false|, otherwise it returns |true|.
  10803. @<XMLOutput Implementation@>=
  10804. bool XMLOutput::output()@t\2\2@>@/
  10805. {@t\1@>@/
  10806. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  10807. {@t\1@>@/
  10808. return false;@t\2@>@/
  10809. }@/
  10810. QXmlStreamWriter xmlout(out);
  10811. xmlout.writeStartDocument("1.0");
  10812. xmlout.writeDTD("<!DOCTYPE roastlog3.0>");
  10813. xmlout.writeStartElement("roastlog");
  10814. @<Output the column declarations@>@;
  10815. xmlout.writeStartElement("roast");
  10816. bool oresult;
  10817. for(int i = 0; i < data->rowCount(); i++)@/
  10818. {
  10819. @<Check if row should be output@>@;
  10820. if(oresult)
  10821. {
  10822. @<Output tuple element@>@;
  10823. }
  10824. }
  10825. xmlout.writeEndElement();
  10826. xmlout.writeEndElement();
  10827. xmlout.writeEndDocument();
  10828. out->close();@/
  10829. return true;@t\2@>@/
  10830. }
  10831. @ Temperature column declarations are output before annotation column
  10832. declarations. Within each category, column declarations are output in order by
  10833. column number.
  10834. @<Output the column declarations@>=
  10835. foreach(int c, temperatureColumns.keys())
  10836. {
  10837. xmlout.writeStartElement("tempseries");
  10838. xmlout.writeAttribute("name", temperatureColumns.value(c));
  10839. xmlout.writeEndElement();
  10840. }
  10841. foreach(int c, controlColumns.keys())
  10842. {
  10843. xmlout.writeStartElement("controlseries");
  10844. xmlout.writeAttribute("name", controlColumns.value(c));
  10845. xmlout.writeEndElement();
  10846. }
  10847. foreach(int c, annotationColumns.keys())
  10848. {
  10849. xmlout.writeStartElement("noteseries");
  10850. xmlout.writeAttribute("name", annotationColumns.value(c));
  10851. xmlout.writeEndElement();
  10852. }
  10853. @ When checking a row in the model to determine if it contains values that need
  10854. to be written, we want to know if any of the temperature or annotation columns
  10855. contain a value. If at least one of these columns is not empty for this row, we
  10856. need to output a tuple for that row.
  10857. @<Check if row should be output@>=
  10858. oresult = false;@/
  10859. foreach(int c, temperatureColumns.keys())@/
  10860. {@t\1@>@/
  10861. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10862. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10863. {@t\1@>@/
  10864. oresult = true;
  10865. break;@t\2@>@/
  10866. }@t\2@>@/
  10867. }@/
  10868. foreach(int c, controlColumns.keys())
  10869. {
  10870. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10871. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))
  10872. {
  10873. oresult = true;
  10874. break;
  10875. }
  10876. }
  10877. if(oresult == false)@/
  10878. {@t\1@>@/
  10879. foreach(int c, annotationColumns.keys())@/
  10880. {@t\1@>@/
  10881. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10882. !(data->data(data->index(i, c), Qt::DisplayRole).toString().
  10883. isEmpty()))@/
  10884. {@t\1@>@/
  10885. oresult = true;
  10886. break;@t\2@>@/
  10887. }@t\2@>@/
  10888. }@t\2@>@/
  10889. }
  10890. @ Now that we know that values from the current row should be output, we can
  10891. produce a {\tt <tuple>} element, a {\tt <time>} element for that tuple, and then
  10892. iterate over the set of columns we might want to output, producing an
  10893. appropriate element for each non-empty column for that row.
  10894. @<Output tuple element@>=
  10895. xmlout.writeStartElement("tuple");
  10896. xmlout.writeTextElement("time", data->data(data->index(i, time),
  10897. Qt::DisplayRole).toString());
  10898. foreach(int c, temperatureColumns.keys())@/
  10899. {
  10900. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10901. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10902. {
  10903. xmlout.writeStartElement("temperature");
  10904. xmlout.writeAttribute("series", temperatureColumns.value(c));
  10905. if(data->data(data->index(i, c), Qt::UserRole).toMap().contains("relative"))
  10906. {
  10907. if(data->data(data->index(i, c), Qt::UserRole).toMap().value("relative").toBool())
  10908. {
  10909. xmlout.writeAttribute("relative", "true");
  10910. }
  10911. }
  10912. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  10913. toString());
  10914. xmlout.writeEndElement();
  10915. }
  10916. }
  10917. foreach(int c, controlColumns.keys())
  10918. {
  10919. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10920. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))
  10921. {
  10922. xmlout.writeStartElement("control");
  10923. xmlout.writeAttribute("series", controlColumns.value(c));
  10924. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).toString());
  10925. xmlout.writeEndElement();
  10926. }
  10927. }
  10928. foreach(int c, annotationColumns.keys())@/
  10929. {
  10930. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10931. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10932. {
  10933. xmlout.writeStartElement("annotation");
  10934. xmlout.writeAttribute("series", annotationColumns.value(c));
  10935. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  10936. toString());
  10937. xmlout.writeEndElement();
  10938. }
  10939. }
  10940. xmlout.writeEndElement();
  10941. @ The rest of the class just initializes the private member data.
  10942. @<XMLOutput Implementation@>=
  10943. XMLOutput::XMLOutput(MeasurementModel *model, QIODevice *device, int timec)
  10944. : QObject(NULL), data(model), out(device), time(timec)@/
  10945. {
  10946. /* Nothing has to be done here. */
  10947. }@;
  10948. void XMLOutput::setModel(MeasurementModel *model)
  10949. {
  10950. data = model;
  10951. }
  10952. void XMLOutput::setTimeColumn(int column)
  10953. {
  10954. time = column;
  10955. }
  10956. void XMLOutput::setDevice(QIODevice *device)
  10957. {
  10958. out = device;
  10959. }
  10960. @ As of version 1.2.3, the old |setTemperatureColumn()| and
  10961. |setAnnotationColumn()| methods have been replaced with the
  10962. |addTemperatureColumn()| and |addAnnotationColumn()| methods respectively. The
  10963. main difference is that the new methods take a column name in addition to a
  10964. number and it is now possible to specify multiple columns of each category for
  10965. export.
  10966. @<XMLOutput Implementation@>=
  10967. void XMLOutput::addTemperatureColumn(const QString &series, int column)
  10968. {
  10969. temperatureColumns.insert(column, series);
  10970. }
  10971. void XMLOutput::addControlColumn(const QString &series, int column)
  10972. {
  10973. controlColumns.insert(column, series);
  10974. }
  10975. void XMLOutput::addAnnotationColumn(const QString &series, int column)
  10976. {
  10977. annotationColumns.insert(column, series);
  10978. }
  10979. @* XML Input.
  10980. \noindent Once model data can be saved to a file, it is useful to be able to
  10981. read that data back in. This is a little different from reading data out of a
  10982. model as more than one object is potentially interested in the data. Instead, we
  10983. emit signals for measurements and annotations. This class has been modified to
  10984. support both the current (as of version 1.2.3) output of the |XMLOutput| class
  10985. and the older version. If changes are made to |XMLOutput| this class may also
  10986. need to be modified.
  10987. The main differences in the current version of this class are that the first
  10988. column is specified rather than specifying temperature and annotation columns
  10989. separately and additional signals are emitted to allow views to prepare for an
  10990. arbitrary number of columns.
  10991. The |newTemperatureColumn| and |newAnnotationColumn| signals can be used to set
  10992. up column headers while the |lastColumn| signal can be used to shift live data
  10993. streams to unoccupied columns.
  10994. @<Class declarations@>=
  10995. class XMLInput : public QObject@/
  10996. {
  10997. Q_OBJECT@;
  10998. int firstc;
  10999. QIODevice *in;
  11000. public:@/
  11001. XMLInput(QIODevice *input, int c);
  11002. void setFirstColumn(int column);
  11003. void setDevice(QIODevice *device);
  11004. bool input();
  11005. signals:@/
  11006. void measure(Measurement, int);
  11007. void annotation(QString, int, int);
  11008. void newTemperatureColumn(int, QString);
  11009. void newAnnotationColumn(int, QString);
  11010. void lastColumn(int);
  11011. };
  11012. @ The main point of interest here is the |input()| method. If the file is read
  11013. successfully, |true| is returned. Otherwise, |false| is returned.
  11014. @<XMLInput Implementation@>=
  11015. bool XMLInput::input()@t\2\2@>@/
  11016. {@t\1@>@/
  11017. if(!in->open(QIODevice::ReadOnly | QIODevice::Text))@/
  11018. {@t\1@>@/
  11019. return false;@t\2@>@/
  11020. }@/
  11021. QXmlStreamReader xmlin(in);
  11022. QMap<QString, int> temperatureColumns;
  11023. QMap<QString, int> annotationColumns;
  11024. int nextColumn = firstc;
  11025. @<Read column declarations@>@;
  11026. QTime timeval = QTime();
  11027. double tempval = 0;
  11028. QString noteval = QString();
  11029. int column;
  11030. int counter = 0;@/
  11031. while(!xmlin.atEnd())@/
  11032. {@/
  11033. @<Read XML file@>@;
  11034. }@/
  11035. return true;@t\2@>@/
  11036. }
  11037. @ A data file may or may not contain elements that specify the name of a column.
  11038. In order to determine how to proceed, we should check the doctype of the input
  11039. file. This should be the first element of the input file encountered.
  11040. \danger There is not nearly enough error checking here.
  11041. \endanger
  11042. @<Read column declarations@>=
  11043. while(!xmlin.isDTD())
  11044. {
  11045. xmlin.readNext();
  11046. }
  11047. if(xmlin.isDTD())
  11048. {
  11049. if(xmlin.text() == "<!DOCTYPE roastlog>")
  11050. {
  11051. @<Emit old format column specification@>@;
  11052. }
  11053. else
  11054. {
  11055. xmlin.readNext();
  11056. @<Scan for column declarations and emit@>@;
  11057. }
  11058. }
  11059. @ Old format data will not have column declarations. This means that we must
  11060. produce a default set of signals rather than waiting to read elements describing
  11061. the columns.
  11062. @<Emit old format column specification@>=
  11063. emit newTemperatureColumn(firstc, "Bean");
  11064. emit newAnnotationColumn(firstc + 1, "Note");
  11065. emit lastColumn(firstc + 1);
  11066. @ The current format will have column declarations prior to the {\tt <roast>}
  11067. element. We can just read until we hit that element and emit the appropriate
  11068. signals as elements are encountered.
  11069. @<Scan for column declarations and emit@>=
  11070. while(xmlin.name() != "roast")
  11071. {
  11072. if(xmlin.isStartElement())
  11073. {
  11074. if((xmlin.name() == "tempseries") || (xmlin.name() == "controlseries"))
  11075. {
  11076. temperatureColumns.insert(xmlin.attributes().value("name").
  11077. toString(),
  11078. nextColumn);
  11079. emit newTemperatureColumn(nextColumn,
  11080. xmlin.attributes().value("name").
  11081. toString());
  11082. nextColumn++;
  11083. }
  11084. else if(xmlin.name() == "noteseries")
  11085. {
  11086. annotationColumns.insert(xmlin.attributes().value("name").
  11087. toString(), nextColumn);
  11088. emit newAnnotationColumn(nextColumn,
  11089. xmlin.attributes().value("name").
  11090. toString());
  11091. nextColumn++;
  11092. }
  11093. }
  11094. xmlin.readNext();
  11095. }
  11096. emit lastColumn(nextColumn - 1);
  11097. @ Now we are ready to read measurements from the file. When encountering a
  11098. {\tt <time>} element, we record the time and move on. For {\tt <temperature>}
  11099. and {\tt <annotation>} elements, we emit the appropriate signal. This is handled
  11100. slightly differently depending on which version of the file format is being
  11101. used. Note that there is not nearly enough error checking here and we are
  11102. basically ignoring {\tt <tuple>} elements.
  11103. Due to the typically large number of measurements taken over the course of a
  11104. roast and the amount of time often taken to process these measurements when they
  11105. are read from a file, there is a need to periodically pass control back to the
  11106. event loop to remain responsive to user input.
  11107. @<Read XML file@>=
  11108. xmlin.readNext();
  11109. if(xmlin.isStartElement())
  11110. {
  11111. @<Read measurement data@>@;
  11112. }
  11113. counter++;
  11114. if(counter % 100 == 0)
  11115. {
  11116. QCoreApplication::processEvents();
  11117. }
  11118. @ When reading start elements, it is safe to ignore {\tt <tuple>} and
  11119. {\tt <roast>}. Technically, this means that the program can read certain types
  11120. of invalid data. The Robustness Principle\nfnote{``Be liberal in what you
  11121. accept, and conservative in what you send,'' --- Robert Braden, {\it RFC 1122
  11122. \S 1.2.2}} is generally applicable to any type of data exchange. That said,
  11123. malformed data is not guaranteed readable in the future, even if it does work
  11124. now.
  11125. \danger One set of test input caused this code to emit an empty annotation for
  11126. every measurement. This is the reason for wrapping the annotation signal
  11127. emission to check for this. The detected annotation elements were not present in
  11128. the input stream and I have absolutely no idea where the program came up with
  11129. them. \endanger
  11130. @<Read measurement data@>=
  11131. if(xmlin.name() == "time")
  11132. {
  11133. timeval = QTime::fromString(xmlin.readElementText(), "mm:ss.zzz");
  11134. }
  11135. else if(xmlin.name() == "temperature")
  11136. {
  11137. column = xmlin.attributes().hasAttribute("series") ?
  11138. temperatureColumns.value(xmlin.attributes().value("series").toString()) : firstc;
  11139. bool relative = (xmlin.attributes().value("relative") == "true");
  11140. tempval = xmlin.readElementText().toDouble();
  11141. Measurement measurement(tempval, timeval);
  11142. if(relative)
  11143. {
  11144. measurement.insert("relative", true);
  11145. }
  11146. emit measure(measurement, column);
  11147. }
  11148. else if(xmlin.name() == "control")
  11149. {
  11150. column = xmlin.attributes().value("series").toString().isEmpty() ?
  11151. firstc : temperatureColumns.value(xmlin.attributes().
  11152. value("series").toString());
  11153. tempval = xmlin.readElementText().toDouble();
  11154. Measurement measurement(tempval, timeval, Units::Unitless);
  11155. emit measure(measurement, column);
  11156. }
  11157. else if(xmlin.name() == "annotation")
  11158. {
  11159. column = xmlin.attributes().value("series").toString().isEmpty() ?
  11160. firstc + 1 : annotationColumns.value(xmlin.attributes().
  11161. value("series").toString());
  11162. noteval = xmlin.readElementText();
  11163. if(!noteval.isEmpty())
  11164. {
  11165. emit annotation(noteval, firstc, column);
  11166. }
  11167. }
  11168. @ The other methods just set the private member data.
  11169. @<XMLInput Implementation@>=
  11170. XMLInput::XMLInput(QIODevice *input, int c) :
  11171. firstc(c), in(input)@/
  11172. {@/
  11173. /* Nothing has to be done here. */
  11174. }
  11175. void XMLInput::setFirstColumn(int column)
  11176. {
  11177. firstc = column;
  11178. }
  11179. void XMLInput::setDevice(QIODevice *device)
  11180. {
  11181. in = device;
  11182. }
  11183. @ In order to allow scripts to instantiate the |XMLInput| class, we need a
  11184. constructor and a wrapper around the |input()| method.
  11185. @<Function prototypes for scripting@>=
  11186. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine);
  11187. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *engine);
  11188. @ The script constructor is passed to the scripting engine.
  11189. @<Set up the scripting engine@>=
  11190. constructor = engine->newFunction(constructXMLInput);
  11191. value = engine->newQMetaObject(&XMLInput::staticMetaObject, constructor);
  11192. engine->globalObject().setProperty("XMLInput", value);
  11193. @ The implementation should seem familiar.
  11194. @<Functions for scripting@>=
  11195. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine)
  11196. {
  11197. QIODevice *device = argument<QIODevice *>(0, context);
  11198. QScriptValue object = engine->newQObject(new XMLInput(&*device,
  11199. argument<int>(1, context)));
  11200. object.setProperty("input", engine->newFunction(XMLInput_input));
  11201. return object;
  11202. }
  11203. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *)
  11204. {
  11205. XMLInput *self = getself<@[XMLInput *@]>(context);
  11206. self->input();
  11207. return QScriptValue();
  11208. }
  11209. @* CSV Output.
  11210. \noindent While XML is convenient for \pn{}, other programs may not handle this
  11211. format well. For this purpose, we use a text file with comma separated values.
  11212. Data in this format can easily be handled by shell scripts, simple programs, and
  11213. any spreadsheet (though some may handle the time column poorly).
  11214. We do not need to concern ourselves with reading data in this format back in,
  11215. but there is no reason a class could not be written to do this.
  11216. The structure of this class is very similar to the |XMLOutput| class.
  11217. @<Class declarations@>=
  11218. class CSVOutput@/
  11219. {@/
  11220. MeasurementModel *data;
  11221. QIODevice *out;
  11222. int time;
  11223. QMap<int, QString> temperatureColumns;
  11224. QMap<int, QString> controlColumns;
  11225. QMap<int, QString> annotationColumns;@/
  11226. public:@/
  11227. CSVOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  11228. void addTemperatureColumn(const QString &series, int column);
  11229. void addControlColumn(const QString &series, int column);
  11230. void addAnnotationColumn(const QString &series, int column);
  11231. void setModel(MeasurementModel *model);
  11232. void setTimeColumn(int column);
  11233. void setDevice(QIODevice *device);
  11234. bool output();@/
  11235. };
  11236. @ Very little needs to be done to output the data. We open the output stream
  11237. and, if the output stream was successfully opened, we look for measurements and
  11238. output the text, remembering to output a comma between items and a newline after
  11239. each record. If the data is successfully output, |true| is returned, otherwise
  11240. we return |false|.
  11241. The comparably simple structure of the CSV format allows us to just fling the
  11242. data onto a text stream.
  11243. @<CSVOutput Implementation@>=
  11244. bool CSVOutput::output()@t\2\2@>@/
  11245. {@t\1@>@/
  11246. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  11247. {@t\1@>@/
  11248. return false;@t\2@>@/
  11249. }@/
  11250. QTextStream output(out);
  11251. @<Output CSV column headers@>@;
  11252. bool oresult;
  11253. for(int i = 0; i < data->rowCount(); i++)@/
  11254. {
  11255. @<Check if row should be output@>@;
  11256. if(oresult)
  11257. {
  11258. @<Output CSV row@>@;
  11259. }
  11260. }
  11261. out->close();@/
  11262. return true;@t\2@>@/
  11263. }
  11264. @ Before writing the data, we output a row containing the name of each column.
  11265. @<Output CSV column headers@>=
  11266. output << "Time";
  11267. foreach(int c, temperatureColumns.keys())
  11268. {
  11269. output << ',' << temperatureColumns.value(c);
  11270. }
  11271. foreach(int c, controlColumns.keys())
  11272. {
  11273. output << ',' << controlColumns.value(c);
  11274. }
  11275. foreach(int c, annotationColumns.keys())
  11276. {
  11277. output << ',' << annotationColumns.value(c);
  11278. }
  11279. output << '\n';
  11280. @ Once the header information has been written, we can proceed to output the
  11281. real data. The algorithm for doing this has been changed as of version 1.2.3
  11282. with the result that most uses will now produce more delimiters than the same
  11283. data in previous versions. This should have no impact on the ability of other
  11284. programs to interact with data produced by \pn{}. The code to handle output in
  11285. this way is much easier to read. A future version might once again suppress
  11286. superfluous commas, however the presence of these commas is not considered a
  11287. serious issue at this time.
  11288. @<Output CSV row@>=
  11289. output << data->data(data->index(i, time), Qt::DisplayRole).toString();
  11290. foreach(int c, temperatureColumns.keys())
  11291. {
  11292. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11293. }
  11294. foreach(int c, controlColumns.keys())
  11295. {
  11296. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11297. }
  11298. foreach(int c, annotationColumns.keys())
  11299. {
  11300. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11301. }
  11302. output << '\n';
  11303. @ The rest of the class just initializes the private member data. See notes
  11304. on the implementation of |XMLOutput|.
  11305. @<CSVOutput Implementation@>=
  11306. CSVOutput::CSVOutput(MeasurementModel *model, QIODevice *device, int timec) :
  11307. data(model), out(device), time(timec)@/
  11308. {
  11309. /* Nothing has to be done here. */
  11310. }@;
  11311. void CSVOutput::setModel(MeasurementModel *model)
  11312. {
  11313. data = model;
  11314. }
  11315. void CSVOutput::setTimeColumn(int column)
  11316. {
  11317. time = column;
  11318. }
  11319. void CSVOutput::addTemperatureColumn(const QString &series, int column)
  11320. {
  11321. temperatureColumns.insert(column, series);
  11322. }
  11323. void CSVOutput::addControlColumn(const QString &series, int column)
  11324. {
  11325. controlColumns.insert(column, series);
  11326. }
  11327. void CSVOutput::addAnnotationColumn(const QString &series, int column)
  11328. {
  11329. annotationColumns.insert(column, series);
  11330. }
  11331. void CSVOutput::setDevice(QIODevice *device)
  11332. {
  11333. out = device;
  11334. }
  11335. @i webview.w
  11336. @i printerselector.w
  11337. @* The Application class.
  11338. The |Application| class represents the \pn{} program. It is responsible for
  11339. setting up the settings object and localization in addition to the normal
  11340. responsibilities of |QApplication|. In addition to declaring the class, we also
  11341. define a macro that returns the |Application| instance.
  11342. @<Class declarations@>=
  11343. #define AppInstance (qobject_cast<@[Application *@]>(qApp))
  11344. class NodeInserter;
  11345. class DeviceTreeModel;
  11346. class DatabaseNotification;
  11347. class Application : public QApplication@/
  11348. {@/
  11349. @[Q_OBJECT@]@;
  11350. public:@/
  11351. Application(int &argc, char **argv);
  11352. QDomDocument* configuration();
  11353. @<Device configuration members@>@;
  11354. QSqlDatabase database();
  11355. Q_INVOKABLE bool databaseConnected();
  11356. Q_INVOKABLE QString currentTypicaUser();
  11357. Q_INVOKABLE bool login(const QString &user, const QString &password);
  11358. Q_INVOKABLE bool autoLogin();
  11359. QScriptEngine *engine;
  11360. QNetworkAccessManager *network;
  11361. DatabaseNotification *subscribe(const QString &notification);@/
  11362. @[public slots@]:@/
  11363. void setDatabaseConnected(bool status);
  11364. void setCurrentTypicaUser(const QString &user);
  11365. void notify(const QString &notification);
  11366. @<Extended Application slots@>@;
  11367. @[signals@]:@/
  11368. void userChanged(const QString &user);
  11369. private:@/
  11370. @<Application private data members@>@;
  11371. QDomDocument conf;
  11372. bool connectionStatus;
  11373. QString currentUser;
  11374. QMap<QString, DatabaseNotification*> notifiers;
  11375. QSqlDriver *notificationDriver;
  11376. };
  11377. @ The constructor for this class handles a few things that had previously been
  11378. handled in |main()|.
  11379. @<Application Implementation@>=
  11380. Application::Application(int &argc, char **argv) : QApplication(argc, argv),
  11381. connectionStatus(false), currentUser(QString())@/
  11382. {
  11383. network = new QNetworkAccessManager(this);
  11384. @<Allow use of the default QSettings constructor@>@;
  11385. @<Load translation objects@>@;
  11386. @<Register meta-types@>@;
  11387. @<Register top level device configuration nodes@>@;
  11388. }
  11389. @ We use |QSettings| objects throughout \pn{} to remember details such as the
  11390. size and position of windows and the most recently used directory. To simplify
  11391. the creation of these objects, we specify some details up front. This allows us
  11392. to use the default constructor rather than specifying these things every time we
  11393. need an object.
  11394. @<Allow use of the default QSettings constructor@>=
  11395. setOrganizationName("Wilson's Coffee & Tea");
  11396. setOrganizationDomain("wilsonscoffee.com");
  11397. setApplicationName(PROGRAM_NAME);
  11398. @ Much of the user visible text in \pn{} is wrapped in a call to |tr()|. Such
  11399. text can be replaced with translated text based on the user'@q'@>s locale. For more
  11400. details, see the Qt Linguist manual.
  11401. @<Load translation objects@>=
  11402. QTranslator *base = new QTranslator;
  11403. if(base->load(QString("qt_%1").arg(QLocale::system().name()), QString("%1/Translations").arg(QCoreApplication::applicationDirPath())))
  11404. {
  11405. installTranslator(base);
  11406. }
  11407. QTranslator *app = new QTranslator;
  11408. if(app->load(QString("%1_%2").arg("Typica").arg(QLocale::system().name()), QString("%1/Translations").arg(QCoreApplication::applicationDirPath())))
  11409. {
  11410. installTranslator(app);
  11411. }
  11412. @ We also want to be able to access the application instance from within the
  11413. scripting engine. We don'@q'@>t need to be able to create new instances, just access the one that already exists.
  11414. @<Set up the scripting engine@>=
  11415. value = engine->newQObject(AppInstance);
  11416. value.setProperty("subscribe", engine->newFunction(Application_subscribe));
  11417. engine->globalObject().setProperty("Application", value);
  11418. @ The |configuration()| method provides access to an XML document containing the
  11419. current application configuration. The object is populated in |main()|.
  11420. @<Application Implementation@>=
  11421. QDomDocument* Application::configuration()
  11422. {
  11423. return &conf;
  11424. }
  11425. @ The |database()| method provides access to a database connection for use by
  11426. database aware widgets.
  11427. @<Application Implementation@>=
  11428. QSqlDatabase Application::database()
  11429. {
  11430. QString connectionName;
  11431. QSqlDatabase connection =
  11432. QSqlDatabase::database(QLatin1String(QSqlDatabase::defaultConnection), false);
  11433. do
  11434. {
  11435. connectionName = QUuid::createUuid().toString();
  11436. } while (QSqlDatabase::connectionNames().contains(connectionName));
  11437. return QSqlDatabase::cloneDatabase(connection, QString(connectionName));
  11438. }
  11439. @ Starting with version 1.8 there are methods for determining if a connection
  11440. to the database was successfully established when Typica was opened.
  11441. @<Application Implementation@>=
  11442. void Application::setDatabaseConnected(bool status)
  11443. {
  11444. connectionStatus = status;
  11445. }
  11446. bool Application::databaseConnected()
  11447. {
  11448. return connectionStatus;
  11449. }
  11450. @ Database notifications allow various parts of Typica to be aware when data in
  11451. the database may have been changed by another instance of Typica running on a
  11452. different computer or by another program that uses the same database. To pass
  11453. notifications to the various places that may be interested in these and not
  11454. bother notification aware controls that are uninterested in unrelated
  11455. notifications, a notification object is created for each notification.
  11456. Note that the notification channel is an identifier and unquoted identifiers
  11457. will be converted to lowercase while \pn{} will attempt to match subscribed to
  11458. notifications exactly. This means that it is generally a good idea to subscribe
  11459. with the channel specified in lowercase.
  11460. @<Application Implementation@>=
  11461. DatabaseNotification* Application::subscribe(const QString &notification)
  11462. {
  11463. DatabaseNotification *retval;
  11464. if(notifiers.contains(notification))
  11465. {
  11466. retval = notifiers.value(notification);
  11467. }
  11468. else
  11469. {
  11470. if(notifiers.size() == 0)
  11471. {
  11472. notificationDriver = QSqlDatabase::database().driver();
  11473. connect(notificationDriver, SIGNAL(notification(QString)), this, SLOT(notify(QString)));
  11474. }
  11475. retval = new DatabaseNotification;
  11476. connect(this, SIGNAL(aboutToQuit()), retval, SLOT(deleteLater()));
  11477. if(notifiers.size() !=
  11478. notificationDriver->subscribedToNotifications().size())
  11479. {
  11480. for(int i = 0; i < notifiers.size(); i++)
  11481. {
  11482. notificationDriver->subscribeToNotification(notifiers.keys().at(i));
  11483. }
  11484. }
  11485. notifiers.insert(notification, retval);
  11486. notificationDriver->subscribeToNotification(notification);
  11487. }
  11488. return retval;
  11489. }
  11490. @ As the various parts of \pn{} operate mostly indepent of each other and
  11491. notifications from the current instance may not be immediately returned, it is
  11492. generally a good idea for operations that would generate a notification to also
  11493. signal that notification within the application.
  11494. @<Application Implementation@>=
  11495. void Application::notify(const QString &notification)
  11496. {
  11497. if(notifiers.contains(notification))
  11498. {
  11499. DatabaseNotification *notifier = notifiers.value(notification);
  11500. notifier->forwardNotification(notification);
  11501. }
  11502. }
  11503. @ A function is provided to allow subscribing to notifications from scripts.
  11504. @<Function prototypes for scripting@>=
  11505. QScriptValue Application_subscribe(QScriptContext *context,
  11506. QScriptEngine *engine);
  11507. @ The implementation is trivial.
  11508. @<Functions for scripting@>=
  11509. QScriptValue Application_subscribe(QScriptContext *context,
  11510. QScriptEngine *engine)
  11511. {
  11512. return engine->newQObject(
  11513. AppInstance->subscribe(argument<QString>(0, context)));
  11514. }
  11515. @ The DatabaseNotification object just needs a signal that interested objects
  11516. can connect to.
  11517. @<Class declarations@>=
  11518. class DatabaseNotification : public QObject
  11519. {
  11520. Q_OBJECT
  11521. public:
  11522. DatabaseNotification();
  11523. public slots:
  11524. void forwardNotification(const QString &notification);
  11525. signals:
  11526. void notify(const QString &notification);
  11527. };
  11528. @ The implementation is trivial.
  11529. @<Class declarations@>=
  11530. DatabaseNotification::DatabaseNotification() : QObject(NULL)
  11531. {
  11532. /* Nothing needs to be done here. */
  11533. }
  11534. void DatabaseNotification::forwardNotification(const QString &notification)
  11535. {
  11536. emit notify(notification);
  11537. }
  11538. @** Table editor for ordered arrays with SQL relations.
  11539. \noindent A database in use at Wilson's Coffee \char'046~Tea stores information
  11540. for a roasting log and uses entered information to adjust inventory tracking
  11541. tables. This roasting log connects the use of unroasted coffee with the creation
  11542. of roasted coffee. In order to support roasting coffee from more than one lot at
  11543. the same time, the columns that specify the types of coffee used and the amount
  11544. of each coffee are entered as ordered arrays in which the first entry in the
  11545. array specifying an unroasted coffee is associated with the first entry in the
  11546. array specifying the amount of coffee used. While most batches will involve only
  11547. a single unroasted coffee, the database has no limitation on the number of
  11548. coffees that may be roasted in a single batch. An additional characteristic of
  11549. this table is that the database requires an identification number for unroasted
  11550. coffee items, but it would be better to provide a list of acceptable items with
  11551. human readable names.
  11552. A scrollable area containing a table view which can provide the necessary input
  11553. delegates (such as a combo box for SQL relations) and validators which ensures
  11554. that there is always at least one empty row available for input with convenience
  11555. functions for extracting the arrays needed for database insertion would be ideal
  11556. for this.
  11557. To get this, we need a simple table model based on |QStandardItemModel|
  11558. or |QAbstractItemModel|. The model should ensure that there is always at least
  11559. one empty row available for editing. It should also provide a function for
  11560. obtaining a string that presents all values from a specified column with a given
  11561. role as an array literal suitable for binding to an SQL query.
  11562. A class based on |QComboBox| providing options selected from an SQL query will
  11563. be needed. This can be used as a standalone widget elsewhere, but here it is
  11564. also needed as an editor class for a column delegate. Another delegate class
  11565. allows input in another column to be constrained by a |QValidator| (in this case
  11566. a |QDoubleValidator|).
  11567. A class based on |QTableView| brings all of these classes together and presents
  11568. them to the user.
  11569. @* A table model for producing SQL array literals.
  11570. \noindent This is a simple table model which provides two somewhat unusual
  11571. features. First, it always provides at least one empty row at the end of the
  11572. data. Second, it provides SQL array literals for columns in the model.
  11573. \danger At some point I would like to replace this model and |MeasurementModel|
  11574. with an improved table model suitable to replace both. Some preliminary design
  11575. work suggests that this improvement simplifies \pn{} considerably both
  11576. internally and in the data flow configuration. This has not yet been done due to
  11577. development time constraints.\endanger
  11578. @<Class declarations@>=
  11579. class SaltModel : public QAbstractItemModel@/
  11580. {
  11581. Q_OBJECT@t\2\2@>@/
  11582. QList<QList<QMap<int, QVariant> > > modelData;
  11583. QStringList hData;
  11584. int colcount;@t\1\1@>@/
  11585. public:@/
  11586. SaltModel(int columns);
  11587. ~SaltModel();
  11588. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  11589. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  11590. bool setHeaderData(int section, Qt::Orientation@, orientation,
  11591. const QVariant &value, int role = Qt::DisplayRole);
  11592. QVariant data(const QModelIndex &index, int role) const;
  11593. bool setData(const QModelIndex &index, const QVariant &value,
  11594. int role = Qt::EditRole);
  11595. Qt::ItemFlags@, flags(const QModelIndex &index) const;
  11596. QVariant headerData(int section, Qt::Orientation@, orientation,
  11597. int role = Qt::DisplayRole) const;
  11598. QModelIndex index(int row, int column,
  11599. const QModelIndex &parent = QModelIndex()) const;
  11600. QModelIndex parent(const QModelIndex &index) const;
  11601. QString arrayLiteral(int column, int role) const;
  11602. QString quotedArrayLiteral(int column, int role) const;
  11603. void clear();
  11604. bool removeRows(int row, int count,
  11605. const QModelIndex &parent = QModelIndex());
  11606. int findData(const QVariant &value, int column, int role = Qt::UserRole);
  11607. };
  11608. @ The only unique methods in this class are the |arrayLiteral| and
  11609. |quotedArrayLiteral| methods. These take a column number and a data role and
  11610. produce a SQL array literal for every entry in that column with the specified
  11611. role. The string will take the form of
  11612. {\tt{'\LB row 1, row 2, }}$\dots$ {\tt{row N\RB '}}.
  11613. This is done simply by starting with a string identifying the start of an array
  11614. literal, looping over the rows in the model while appending any data found along
  11615. with the commas to separate values. If any data is found, the extra comma and
  11616. space are removed from the constructed string. Finally, text marking the end of
  11617. the array literal is added.
  11618. The |arrayLiteral| method is appropriate where the expected values are numeric.
  11619. The |quotedArrayLiteral| method is appropriate where the expected values are
  11620. text. The values in the array will have quotation marks around them for the
  11621. |quotedArrayLiteral|. Note that when binding these values to placeholders in a
  11622. SQL query the leading and trailing single quote characters should be removed.
  11623. \danger The way this method is currently used is quite harmless. Data from one
  11624. column is integer data obtained as a result of a previous database query and
  11625. data from the other column is restricted by the view to numeric data. Please
  11626. note, however, that it would be extremely stupid to use code such as this when
  11627. user input cannot be controlled so tightly. Were this model used with a view
  11628. that allows general text input, it would be trivial to construct an SQL
  11629. injection attack.
  11630. \medskip
  11631. \centerline{\includegraphics[width=6in]{exploits_of_a_mom}}
  11632. \smallskip
  11633. \centerline{Figure \secno: An Example of an SQL injection attack.\nfnote{%
  11634. Comic copyright Randall Munroe. Original can be found at:~%
  11635. \pdfURL{%
  11636. http://xkcd.com/327/}%
  11637. {http://xkcd.com/327/}}}
  11638. \medskip
  11639. \endanger
  11640. @<SaltModel Implementation@>=
  11641. QString SaltModel::arrayLiteral(int column, int role) const
  11642. {
  11643. QString literal = "'{";
  11644. for(int i = 0; i < rowCount(); i++)
  11645. {
  11646. QString datum = data(index(i, column), role).toString();
  11647. if(!datum.isEmpty())
  11648. {
  11649. literal.append(datum);
  11650. literal.append(", ");
  11651. }
  11652. }
  11653. if(literal.size() > 2)
  11654. {
  11655. literal.chop(2);
  11656. }
  11657. literal.append("}'");
  11658. return literal;
  11659. }
  11660. QString SaltModel::quotedArrayLiteral(int column, int role) const
  11661. {
  11662. QString literal = "'{";
  11663. for(int i = 0; i < rowCount(); i++)
  11664. {
  11665. QString datum = data(index(i, column), role).toString();
  11666. if(!datum.isEmpty())
  11667. {
  11668. literal.append("\"");
  11669. literal.append(datum);
  11670. literal.append("\", ");
  11671. }
  11672. }
  11673. if(literal.size() > 2)
  11674. {
  11675. literal.chop(2);
  11676. }
  11677. literal.append("}'");
  11678. return literal;
  11679. }
  11680. @ No entries in this model have children.
  11681. @<SaltModel Implementation@>=
  11682. QModelIndex SaltModel::parent(const QModelIndex &) const
  11683. {
  11684. return QModelIndex();
  11685. }
  11686. @ The |setData()| method is called by delegates on views when the user enters
  11687. new data. This method must check to determine if the data is being entered in
  11688. the last row to increase the size of the table.
  11689. The end of this function may seem a little strange. Why not simply look up the
  11690. map and insert information directly into the model data? Well, as of this
  11691. writing, that doesn'@q'@>t work. There are two ways around that problem. One is to
  11692. have the lists store references and dereference the real data. The other option
  11693. is to obtain a copy of the row, then a copy of the cell, update the cell, then
  11694. replace the old value of the cell in the copy of the row, then replace the old
  11695. values of the row in the real data. The other option would probably be more
  11696. efficient, but this does work.
  11697. @<SaltModel Implementation@>=
  11698. bool SaltModel::setData(const QModelIndex &index, const QVariant &value,
  11699. int role)@t\2\2@>@/
  11700. {@t\1@>@/
  11701. @<Check that the SaltModel index is valid@>@;
  11702. if(!valid)@/
  11703. {@t\1@>@/
  11704. return false;@t\2@>@/
  11705. }
  11706. if(index.row() == modelData.size() - 1)@/
  11707. {
  11708. beginInsertRows(QModelIndex(), modelData.size(), modelData.size());
  11709. @<Expand the SaltModel@>@;
  11710. endInsertRows();
  11711. }
  11712. QList<QMap<int, QVariant> > row = modelData.at(index.row());
  11713. QMap<int, QVariant> cell = row.at(index.column());
  11714. cell.insert(role, value);
  11715. if(role == Qt::EditRole)@/
  11716. {
  11717. cell.insert(Qt::DisplayRole, value);
  11718. }
  11719. row.replace(index.column(), cell);
  11720. modelData.replace(index.row(), row);
  11721. emit dataChanged(index, index);@/
  11722. return true;@t\2@>@/
  11723. }
  11724. @ Some model operations require checking that a model index is valid. This
  11725. chunk is used in these cases.
  11726. @<Check that the SaltModel index is valid@>=
  11727. bool valid = false;@/
  11728. if(index.isValid())@/
  11729. {@t\1@>@/
  11730. if(index.row() < modelData.size())@/
  11731. {@t\1@>@/
  11732. if(index.column() < colcount)@/
  11733. {@t\1@>@/
  11734. valid = true;@t\2@>@/
  11735. }@t\2@>@/
  11736. }@t\2@>@/
  11737. }
  11738. @ When data is modified in the last row of the table, the model must be expanded
  11739. to allow for additional data.
  11740. @<Expand the SaltModel@>=
  11741. QList<QMap<int, QVariant> > newRow;
  11742. QMap<int, QVariant> defaults;
  11743. for(int i = 0; i < colcount; i++)
  11744. {
  11745. newRow.append(defaults);
  11746. }
  11747. modelData.append(newRow);
  11748. @ The number of columns in the table is specified in the model constructor.
  11749. @<SaltModel Implementation@>=
  11750. SaltModel::SaltModel(int columns) : QAbstractItemModel(), colcount(columns)
  11751. {
  11752. for(int i = 0; i < columns; i++)
  11753. {
  11754. hData << "";
  11755. }
  11756. @<Expand the SaltModel@>@;
  11757. }
  11758. @ The destructor doesn'@q'@>t need to do anything.
  11759. @<SaltModel Implementation@>=
  11760. SaltModel::~SaltModel()
  11761. {
  11762. /* Nothing needs to be done here. */
  11763. }
  11764. @ A pair of methods provide the number of rows and columns in the model. No
  11765. entries in the model have children, so the parent should always be the invisible
  11766. root object.
  11767. @<SaltModel Implementation@>=
  11768. int SaltModel::rowCount(const QModelIndex &parent) const
  11769. {
  11770. return (parent == QModelIndex() ? modelData.size() : 0);
  11771. }
  11772. int SaltModel::columnCount(const QModelIndex &parent) const
  11773. {
  11774. return (parent == QModelIndex() ? colcount : 0);
  11775. }
  11776. @ The model maintains header data for labeling the model columns.
  11777. @<SaltModel Implementation@>=
  11778. bool SaltModel::setHeaderData(int section, Qt::Orientation@, orientation,@|
  11779. const QVariant &value, int)@t\2\2@>@/
  11780. {@t\1@>@/
  11781. if(orientation == Qt::Horizontal && section < colcount)@/
  11782. {@t\1@>@/
  11783. hData.replace(section, value.toString());@/
  11784. emit headerDataChanged(orientation, section, section);@/
  11785. return true;@t\2@>@/
  11786. }@/
  11787. return false;@t\2@>@/
  11788. }
  11789. @ Views need to be able to retrieve model and header data.
  11790. @<SaltModel Implementation@>=
  11791. QVariant SaltModel::data(const QModelIndex &index, int role) const
  11792. {
  11793. @<Check that the SaltModel index is valid@>@;
  11794. if(!valid)
  11795. {
  11796. return QVariant();
  11797. }
  11798. QList<QMap<int,QVariant> > row = modelData.at(index.row());
  11799. QMap<int,QVariant> cell = row.at(index.column());
  11800. return cell.value(role, QVariant());
  11801. }
  11802. QVariant SaltModel::headerData(int section, Qt::Orientation@, orientation,
  11803. int role) const
  11804. {
  11805. if(orientation == Qt::Horizontal && role == Qt::DisplayRole &&
  11806. section < colcount)
  11807. {
  11808. return QVariant(hData.at(section));
  11809. }
  11810. return QVariant();
  11811. }
  11812. @ Views need to know certain details such as if an item in the view can be
  11813. altered by the view. For this model, all valid indices can be edited.
  11814. @<SaltModel Implementation@>=
  11815. Qt::ItemFlags SaltModel::flags(const QModelIndex &index) const
  11816. {
  11817. @<Check that the SaltModel index is valid@>@;
  11818. if(valid)
  11819. {
  11820. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled;
  11821. }
  11822. return 0;
  11823. }
  11824. @ So far, many of the methods use model indices. The model is responsible for
  11825. creating these.
  11826. @<SaltModel Implementation@>=
  11827. QModelIndex SaltModel::index(int row, int column,
  11828. const QModelIndex &parent) const
  11829. {
  11830. if(parent == QModelIndex())
  11831. {
  11832. if(row < modelData.size() && column < colcount)
  11833. {
  11834. return createIndex(row, column);
  11835. }
  11836. }
  11837. return QModelIndex();
  11838. }
  11839. @ There are some times when it is useful to clear the model data. Note that
  11840. column header data is retained and the table will contain a single empty row
  11841. after this method is called.
  11842. @<SaltModel Implementation@>=
  11843. void SaltModel::clear()
  11844. {
  11845. beginResetModel();
  11846. modelData.clear();
  11847. @<Expand the SaltModel@>@;
  11848. endResetModel();
  11849. }
  11850. @ Another commonly useful operation is the ability to remove rows from the
  11851. model. The new batch window uses this feature to eliminate rows in which the
  11852. coffee is set to NULL. Note that if all rows of the model are removed, a new
  11853. empty row will be created.
  11854. @<SaltModel Implementation@>=
  11855. bool SaltModel::removeRows(int row, int count,
  11856. const QModelIndex &parent)
  11857. {
  11858. if(parent == QModelIndex())
  11859. {
  11860. if(row >= 0 && count > 0 && (row + count - 1) < modelData.size())
  11861. {
  11862. beginRemoveRows(parent, row, row + count - 1);
  11863. for(int i = 0; i < count; i++)
  11864. {
  11865. modelData.removeAt(row);
  11866. }
  11867. endRemoveRows();
  11868. if(modelData.size() == 0)
  11869. {
  11870. beginInsertRows(parent, 0, 0);
  11871. @<Expand the SaltModel@>@;
  11872. endInsertRows();
  11873. }
  11874. return @[true@];
  11875. }
  11876. }
  11877. return @[false@];
  11878. }
  11879. @ To find the row number for removal operations it is useful to search for
  11880. special values on a given role. The |findData()| method returns the first row
  11881. in which the given value matches for a particular column and a particular role
  11882. or |-1| if no such match exists.
  11883. @<SaltModel Implementation@>=
  11884. int SaltModel::findData(const QVariant &value, int column, int role)
  11885. {
  11886. for(int i = 0; i < modelData.size(); i++)
  11887. {
  11888. if(modelData.at(i).size() > column)
  11889. {
  11890. if(modelData.at(i).at(column).contains(role))
  11891. {
  11892. if(modelData.at(i).at(column).value(role) == value)
  11893. {
  11894. return i;
  11895. }
  11896. }
  11897. }
  11898. }
  11899. return -1;
  11900. }
  11901. @* A Delegate for SQL Relations.
  11902. \noindent The first column of the table view being described is responsible for
  11903. providing item numbers to the database. Requiring that these numbers be entered
  11904. directly is prone to not particularly user friendly and almost encourages input
  11905. errors. These item numbers, however, refer to the items table in the database
  11906. which includes, among other details, a human readable text string naming the
  11907. item. This delegate provides the user with a drop down menu from which such a
  11908. string may be selected with this information provided by the database itself.
  11909. When the user selects an item, it informs the model not only of the text string
  11910. in the display role, but also of the id number in a user data role which can
  11911. later be queried in order to properly craft the appropriate query.
  11912. This is implemented with two classes. The first is a |QComboBox| which queries
  11913. the database and maintains a mapping of id to text. This is made its own widget
  11914. as it is useful without being turned into a delegate. The second class provides
  11915. this widget as a delegate and handles communications between it and the model.
  11916. @<Class declarations@>=
  11917. class SqlComboBox : public QComboBox@/
  11918. {@t\1@>@/
  11919. Q_OBJECT@;
  11920. int dataColumn;
  11921. int displayColumn;
  11922. bool dataColumnShown;
  11923. QString specialNullText;
  11924. QVariant specialNullData;
  11925. public:@/
  11926. SqlComboBox();
  11927. ~SqlComboBox();
  11928. SqlComboBox* clone(QWidget *parent);@/
  11929. @t\4@>public slots@t\kern-3pt@>:@/
  11930. void addNullOption();
  11931. void addSqlOptions(QString query);
  11932. void setDataColumn(int column);
  11933. void setDisplayColumn(int column);
  11934. void showData(bool show);
  11935. void setNullText(QString nullText);
  11936. void setNullData(QVariant nullData);@t\2@>@/
  11937. }@t\kern-3pt@>;
  11938. @ In order to make this class work a little more nicely as an item delegate,
  11939. the |clone()| method has been provided to create a new object with the same
  11940. options as a prototype.
  11941. @<SqlComboBox Implementation@>=
  11942. SqlComboBox* SqlComboBox::clone(QWidget *parent)
  11943. {
  11944. SqlComboBox *widget = new SqlComboBox();
  11945. widget->setParent(parent);
  11946. for(int i = 0; i < count(); i++)
  11947. {
  11948. widget->addItem(itemText(i), itemData(i));
  11949. }
  11950. return widget;
  11951. }
  11952. @ When using this class, we must first decide if the data column is shown. If
  11953. this is desired, the entries displayed will contain both the value from the
  11954. display column followed by the value from the data column. This can be useful in
  11955. cases where the same text is used for two different items.
  11956. @<SqlComboBox Implementation@>=
  11957. void SqlComboBox::showData(bool show)
  11958. {
  11959. dataColumnShown = show;
  11960. }
  11961. @ Next, there is a need to know if the NULL value may legally be selected. Where
  11962. this is the case, we generally want this to be inserted first. As the
  11963. |QComboBox| supports storing both display and user data, much of the code is a
  11964. thin wrapper around calls to the base class. The text and data for the NULL
  11965. value can be set arbitrarily, which can be useful in certain cases. Note that
  11966. any customization of the NULL text or data must be set before a call to
  11967. |addNullOption()|.
  11968. @<SqlComboBox Implementation@>=
  11969. void SqlComboBox::addNullOption()
  11970. {
  11971. addItem(specialNullText, specialNullData);
  11972. }
  11973. void SqlComboBox::setNullText(QString nullText)
  11974. {
  11975. specialNullText = nullText;
  11976. }
  11977. void SqlComboBox::setNullData(QVariant nullData)
  11978. {
  11979. specialNullData = nullData;
  11980. }
  11981. @ Typically, the SQL query used to populate this widget will request two columns
  11982. of data. One column is used as the display data, the other as user data. This is
  11983. done to present a human readable string where a database query needs an
  11984. identification number. By default, column |0| is used in both roles. If this
  11985. is not desired, the methods to change that must be called before specifying the
  11986. query.
  11987. @<SqlComboBox Implementation@>=
  11988. void SqlComboBox::setDataColumn(int column)
  11989. {
  11990. dataColumn = column;
  11991. }
  11992. void SqlComboBox::setDisplayColumn(int column)
  11993. {
  11994. displayColumn = column;
  11995. }
  11996. @ Once the widget is properly configured, we can run the SQL query and populate
  11997. the combo box with the results.
  11998. @<SqlComboBox Implementation@>=
  11999. void SqlComboBox::addSqlOptions(QString query)
  12000. {
  12001. SqlQueryConnection h;
  12002. QSqlQuery *dbquery = h.operator->();
  12003. if(!dbquery->exec(query))
  12004. {
  12005. QSqlError error = dbquery->lastError();
  12006. qDebug() << error.databaseText();
  12007. qDebug() << error.driverText();
  12008. qDebug() << error.text();
  12009. qDebug() << dbquery->lastQuery();
  12010. /* Throw an error here, please. */
  12011. }
  12012. while(dbquery->next())
  12013. {
  12014. QString displayValue(dbquery->value(displayColumn).toString());
  12015. QString dataValue(dbquery->value(dataColumn).toString());
  12016. if(dataColumnShown)
  12017. {
  12018. displayValue.append(QString(" (%1)").arg(dataValue));
  12019. }
  12020. addItem(displayValue, dataValue);
  12021. }
  12022. }
  12023. @ The constructor initializes some private member data. A size policy is also
  12024. set on the pop up. This allows the pop up to appear wider than the combo box to
  12025. allow more data to appear. On Linux this appears to also change the text elide
  12026. mode to something that is conveniently more appropriate for the use cases in
  12027. Typica. Note that this was not enough of a change to force the pop up to be
  12028. wide enough to contain all of the text for especially long items, but if the
  12029. combo box is wide enough the pop up will match that width.
  12030. The destructor is trivial.
  12031. @<SqlComboBox Implementation@>=
  12032. SqlComboBox::SqlComboBox() :
  12033. dataColumn(0), displayColumn(0), dataColumnShown(false),
  12034. specialNullText(tr("Unknown")), specialNullData(QVariant::String)
  12035. {
  12036. view()->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
  12037. }
  12038. SqlComboBox::~SqlComboBox()
  12039. {
  12040. /* Nothing needs to be done here. */
  12041. }
  12042. @ To use this class as an editor delegate in a model we wrap the class in a
  12043. |QItemDelegate|.
  12044. @<Class declarations@>=
  12045. class SqlComboBoxDelegate : public QItemDelegate@/
  12046. {
  12047. Q_OBJECT@;
  12048. SqlComboBox *delegate;
  12049. public:@/
  12050. SqlComboBoxDelegate(QObject *parent = NULL);
  12051. QWidget *createEditor(QWidget *parent,
  12052. const QStyleOptionViewItem &option,@|
  12053. const QModelIndex &index) const;
  12054. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  12055. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  12056. const QModelIndex &index) const;
  12057. void setWidget(SqlComboBox *widget);
  12058. virtual QSize sizeHint() const;
  12059. void updateEditorGeometry(QWidget *editor,
  12060. const QStyleOptionViewItem &option,@|
  12061. const QModelIndex &index) const;
  12062. };
  12063. @ Rather than set the values for the combo box through the delegate class, we
  12064. create the editor and pass it in to the delegate.
  12065. @<SqlComboBoxDelegate Implementation@>=
  12066. void SqlComboBoxDelegate::setWidget(SqlComboBox *widget)
  12067. {
  12068. delegate = widget;
  12069. }
  12070. @ When a view requests this delegate, we simply return the widget that was
  12071. previously passed in.
  12072. @<SqlComboBoxDelegate Implementation@>=
  12073. QWidget* SqlComboBoxDelegate::createEditor(QWidget *parent,@|
  12074. const QStyleOptionViewItem &,
  12075. const QModelIndex &) const
  12076. {
  12077. return delegate->clone(parent);
  12078. }
  12079. @ To set the appropriate editor data, we check the value in the model and
  12080. attempt to set the value to match that.
  12081. @<SqlComboBoxDelegate Implementation@>=
  12082. void SqlComboBoxDelegate::setEditorData(QWidget *editor,
  12083. const QModelIndex &index) const
  12084. {
  12085. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  12086. self->setCurrentIndex(self->findData(
  12087. index.model()->data(index,
  12088. Qt::UserRole).toString()));
  12089. }
  12090. @ When setting the model data, we need to specify both the display role and the
  12091. user data role.
  12092. @<SqlComboBoxDelegate Implementation@>=
  12093. void SqlComboBoxDelegate::setModelData(QWidget *editor,@|
  12094. QAbstractItemModel *model,
  12095. const QModelIndex &index) const
  12096. {
  12097. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  12098. model->setData(index, self->itemData(self->currentIndex(), Qt::UserRole),
  12099. Qt::UserRole);
  12100. model->setData(index, self->currentText(), Qt::DisplayRole);
  12101. }
  12102. @ This is needed to play nicely with the model view architecture.
  12103. @<SqlComboBoxDelegate Implementation@>=
  12104. void SqlComboBoxDelegate::updateEditorGeometry(QWidget *editor,
  12105. const QStyleOptionViewItem &option,
  12106. const QModelIndex &) const
  12107. {
  12108. editor->setGeometry(option.rect);
  12109. }
  12110. @ When this delegate is used in a table view, we want to be able to provide a
  12111. size hint that can be used to resize the column in order to fit the delegate.
  12112. @<SqlComboBoxDelegate Implementation@>=
  12113. QSize SqlComboBoxDelegate::sizeHint() const
  12114. {
  12115. return delegate->sizeHint();
  12116. }
  12117. @ Finally, we need a constructor.
  12118. @<SqlComboBoxDelegate Implementation@>=
  12119. SqlComboBoxDelegate::SqlComboBoxDelegate(QObject *parent)
  12120. : QItemDelegate(parent)@/
  12121. {
  12122. /* Nothing needs to be done here. */
  12123. }
  12124. @** The main program.
  12125. The |main()| function is where program execution starts. Most of the work
  12126. required here is taken care of for us by the |Application| object.
  12127. The odd handling of argc is required to prevent segmentation faults in the Linux
  12128. build.
  12129. @<The main program@>=
  12130. int main(int argc, char **argv)@/
  12131. {@/
  12132. int *c = &argc;
  12133. Application app(*c, argv);
  12134. QSettings settings;
  12135. @<Set up logging@>@;
  12136. @<Set up icons@>@;
  12137. @<Set up fonts@>@;
  12138. @<Register device configuration widgets@>@;
  12139. @<Prepare the database connection@>@;
  12140. @<Load the application configuration@>@;
  12141. @<Set up the scripting engine@>@;
  12142. app.engine = engine;
  12143. @<Find and evaluate starting script@>@;
  12144. int retval = app.exec();
  12145. delete engine;
  12146. return retval;@/
  12147. }
  12148. @ \pn{} 1.6.3 introduces optional logging of diagnostic messages to a file. By
  12149. default this feature is not enabled. A sensible future refinement to this would
  12150. allow specification of where this file should be created.
  12151. @<Set up logging@>=
  12152. if(settings.value("settings/advanced/logging", false).toBool())
  12153. {
  12154. qInstallMsgHandler(messageFileOutput);
  12155. }
  12156. @ This requires that we have our messageFileOutput function.
  12157. @<Logging function prototype@>=
  12158. void messageFileOutput(QtMsgType type, const char *msg);
  12159. @ The current implementation is straightforward.
  12160. @<Logging function implementation@>=
  12161. void messageFileOutput(QtMsgType, const char *msg)
  12162. {
  12163. QFile output("Typica-"+QDate::currentDate().toString("yyyy-MM-dd")+".log");
  12164. output.open(QIODevice::WriteOnly | QIODevice::Append);
  12165. QTextStream outstream(&output);
  12166. outstream << msg << "\r\n";
  12167. }
  12168. @ \pn{} 1.4 introduces the ability to use icons in certain interface elements.
  12169. Some commonly desired public domain graphics are provided by the Tango Desktop
  12170. Project. We also set an application level default window icon.
  12171. @<Set up icons@>=
  12172. QStringList themeSearchPath = QIcon::themeSearchPaths();
  12173. themeSearchPath.append(":/resources/icons/tango");
  12174. QIcon::setThemeSearchPaths(themeSearchPath);
  12175. QIcon::setThemeName(":/resources/icons/tango");
  12176. app.setWindowIcon(QIcon(":/resources/icons/appicons/logo.svg"));
  12177. @ Similarly some elements make use of a special font which is loaded from
  12178. resource data.
  12179. There has been a report of a bug which I have not been able to reproduce and
  12180. which the original reporter has not yet gotten back to me with the results of
  12181. a test, so I have opted for an alternate approach which does not preclude the
  12182. use of the earlier plan but which may solve the matter. This brings in the
  12183. TeX Gyre Pagella font and sets this as the default standard font for all web
  12184. views.
  12185. @s QFontDatabase int
  12186. @s QWebSettings int
  12187. @<Set up fonts@>=
  12188. QFile entypo(":/resources/fonts/entypo.ttf");
  12189. entypo.open(QIODevice::ReadOnly);
  12190. QFontDatabase::addApplicationFontFromData(entypo.readAll());
  12191. entypo.close();
  12192. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-regular.otf");
  12193. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-bold.otf");
  12194. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-bolditalic.otf");
  12195. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-italic.otf");
  12196. QWebSettings::globalSettings()->setFontFamily(QWebSettings::StandardFont, "Tex Gyre Pagella");
  12197. @ Some widgets provided by \pn{} require access to a database in order to work.
  12198. To simplify using these widgets, the application will request information
  12199. needed to connect to a database. The use of two distinct |if| blocks rather than
  12200. an |if|$\dots$|else| construction is used because the data from settings can be
  12201. changed if an attempt to connect to the database fails.
  12202. @<Prepare the database connection@>=
  12203. if(settings.value("database/exists", "false").toString() == "true")
  12204. {
  12205. @<Try connecting to the database@>@;
  12206. }
  12207. if(settings.value("database/exists", "false").toString() == "false")
  12208. {
  12209. @<Prompt for database connection information@>@;
  12210. }
  12211. @ In order to connect to the database, we need five pieces of information: the
  12212. name of a database driver (PostgreSQL is recommended for now), the host name of
  12213. the computer running the database, the name of the database, the name of the
  12214. user connecting to the database, and that user'@q'@>s password. This information will
  12215. be stored in the user settings for the application so that the database
  12216. connection can be established without prompting the user next time. A class is
  12217. provided to gather this information.
  12218. @<Class declarations@>=
  12219. class SqlConnectionSetup : public QDialog@/
  12220. {@t\1@>@/
  12221. Q_OBJECT@;
  12222. public:@/
  12223. SqlConnectionSetup();
  12224. ~SqlConnectionSetup();@/
  12225. @t\4@>public slots@t\kern-3pt@>:@/
  12226. void testConnection();
  12227. private:@/
  12228. QFormLayout *formLayout;
  12229. QComboBox *driver;
  12230. QLineEdit *hostname;
  12231. QLineEdit *portnumber;
  12232. QLineEdit *dbname;
  12233. QLineEdit *user;
  12234. QLineEdit *password;
  12235. QVBoxLayout *layout;
  12236. QHBoxLayout *buttons;
  12237. QPushButton *cancelButton;
  12238. QPushButton *connectButton;@t\2@>@/
  12239. }@t\kern-3pt@>;
  12240. @ The constructor sets up this widget. The destructor does nothing.
  12241. @<SqlConnectionSetup implementation@>=
  12242. SqlConnectionSetup::SqlConnectionSetup() :
  12243. formLayout(new QFormLayout), driver(new QComboBox), hostname(new QLineEdit),
  12244. portnumber(new QLineEdit),
  12245. dbname(new QLineEdit), user(new QLineEdit), password(new QLineEdit),
  12246. layout(new QVBoxLayout), buttons(new QHBoxLayout),
  12247. cancelButton(new QPushButton(tr("Cancel"))),
  12248. connectButton(new QPushButton(tr("Connect")))@/
  12249. {
  12250. QSettings settings;
  12251. driver->addItem("PostgreSQL", "QPSQL");
  12252. formLayout->addRow(tr("Database driver:"), driver);
  12253. formLayout->addRow(tr("Host name:"), hostname);
  12254. hostname->setText(settings.value("database/hostname").toString());
  12255. formLayout->addRow(tr("Port number:"), portnumber);
  12256. portnumber->setText(settings.value("database/portnumber", "5432").toString());
  12257. formLayout->addRow(tr("Database name:"), dbname);
  12258. dbname->setText(settings.value("database/dbname").toString());
  12259. formLayout->addRow(tr("User name:"), user);
  12260. user->setText(settings.value("database/user").toString());
  12261. password->setEchoMode(QLineEdit::Password);
  12262. formLayout->addRow(tr("Password:"), password);
  12263. password->setText(settings.value("database/password").toString());
  12264. layout->addLayout(formLayout);
  12265. buttons->addStretch(1);
  12266. buttons->addWidget(cancelButton);
  12267. connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(reject()));
  12268. buttons->addWidget(connectButton);
  12269. layout->addLayout(buttons);
  12270. connect(connectButton, SIGNAL(clicked(bool)), this, SLOT(testConnection()));
  12271. connectButton->setDefault(true);
  12272. setLayout(layout);
  12273. setModal(true);
  12274. }
  12275. SqlConnectionSetup::~SqlConnectionSetup()
  12276. {
  12277. /* Nothing needs to be done here. */
  12278. }
  12279. @ The |testConnection()| method checks if the information provided can be used
  12280. to open a new database connection.
  12281. @<SqlConnectionSetup implementation@>=
  12282. void SqlConnectionSetup::testConnection()
  12283. {
  12284. QSqlDatabase database =
  12285. QSqlDatabase::addDatabase(driver->itemData(driver->currentIndex()).
  12286. toString());
  12287. database.setConnectOptions("application_name=Typica");
  12288. database.setHostName(hostname->text());
  12289. database.setPort(portnumber->text().toInt());
  12290. database.setDatabaseName(dbname->text());
  12291. database.setUserName(user->text());
  12292. database.setPassword(password->text());
  12293. if(database.open())
  12294. {
  12295. QSettings settings;
  12296. settings.setValue("database/exists", "true");
  12297. settings.setValue("database/driver",
  12298. driver->itemData(driver->currentIndex()).toString());
  12299. settings.setValue("database/hostname", hostname->text());
  12300. settings.setValue("database/portnumber", portnumber->text());
  12301. settings.setValue("database/dbname", dbname->text());
  12302. settings.setValue("database/user", user->text());
  12303. settings.setValue("database/password", password->text());
  12304. AppInstance->setDatabaseConnected(true);
  12305. accept();
  12306. }
  12307. else
  12308. {
  12309. QMessageBox::information(this, tr("Database connection failed"),
  12310. tr("Failed to connect to database."));
  12311. }
  12312. }
  12313. @ In order to prompt for connection information, we simply create a
  12314. |SqlConnectionSetup| object and call |exec()|. When control returns, the
  12315. settings will either contain appropriate connection information or we have to
  12316. give up on getting that information from the user for now.
  12317. @<Prompt for database connection information@>=
  12318. SqlConnectionSetup dialog;
  12319. dialog.exec();
  12320. @ If we have connected to a database in the previous running of the application,
  12321. we try to connect to the same database automatically rather than prompt the
  12322. user. If the connection attempt fails, we can fall back on asking the user for
  12323. help.
  12324. @<Try connecting to the database@>=
  12325. QSqlDatabase database =
  12326. QSqlDatabase::addDatabase(settings.value("database/driver").toString());
  12327. database.setConnectOptions("application_name=Typica");
  12328. database.setHostName(settings.value("database/hostname").toString());
  12329. database.setPort(settings.value("database/portnumber", 5432).toInt());
  12330. database.setDatabaseName(settings.value("database/dbname").toString());
  12331. database.setUserName(settings.value("database/user").toString());
  12332. database.setPassword(settings.value("database/password").toString());
  12333. if(!database.open())
  12334. {
  12335. settings.setValue("database/exists", "false");
  12336. }
  12337. else
  12338. {
  12339. AppInstance->setDatabaseConnected(true);
  12340. }
  12341. @** Viewing a record of batches.
  12342. \noindent It is frequently useful to present a table view with the results of a
  12343. SQL query and have a way of interacting with that view to obtain more details
  12344. related to a given record in that table. For this purpose, \pn{} provides a
  12345. widget based on |QTableView| which presents information from a
  12346. |QSqlQueryModel|. The table emits signals when an entry in the table is double
  12347. clicked. One of these contains the data from the first column of that row and
  12348. is suitable for use when a primary key is presented in that column and this is
  12349. sufficient for the desired drill down. The other signal provides the row number
  12350. which can be used along with a reference to the table to obtain the data in any
  12351. column.
  12352. This class also automatically persists column widths when these are changed.
  12353. @<Class declarations@>=
  12354. class SqlQueryView : public QTableView@/
  12355. {@/
  12356. @[Q_OBJECT@]@;
  12357. public:@/
  12358. SqlQueryView(QWidget *parent = NULL);
  12359. void setQuery(const QString &query);
  12360. bool setHeaderData(int section, Qt::Orientation@, orientation,
  12361. const QVariant &value, int role);
  12362. @[Q_INVOKABLE@,@, QVariant@]@, data(int row, int column,
  12363. int role = Qt::DisplayRole);@t\2\2@>@/
  12364. signals:@/
  12365. void openEntry(QString key);
  12366. void openEntryRow(int row);@/
  12367. protected:@/
  12368. virtual void showEvent(QShowEvent *event);@/
  12369. @[private slots@]:@/
  12370. void openRow(const QModelIndex &index);
  12371. void persistColumnResize(int column, int oldsize, int newsize);@/
  12372. };
  12373. @ The constructor sets up the communication between the model and the view and
  12374. also provides the connection needed to notice when columns change size to
  12375. persist that preference.
  12376. @<SqlQueryView implementation@>=
  12377. SqlQueryView::SqlQueryView(QWidget *parent) : QTableView(parent)
  12378. {
  12379. setModel(new QSqlQueryModel);
  12380. connect(this, SIGNAL(doubleClicked(QModelIndex)),
  12381. this, SLOT(openRow(QModelIndex)));
  12382. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  12383. this, SLOT(persistColumnResize(int, int, int)));
  12384. }
  12385. @ Column width persistance requires two methods. First we have a slot
  12386. method which is called when a column width is changed. This is saved with
  12387. |QSettings| under a key utilizing the name of the window, the name of the
  12388. table, and the column number.
  12389. @<SqlQueryView implementation@>=
  12390. void SqlQueryView::persistColumnResize(int column, int, int newsize)
  12391. {
  12392. @<Save updated column size@>@;
  12393. }
  12394. @ The body of this function has been split out so that it can be shared with
  12395. other table views without the need to introduce a new common base class.
  12396. @<Save updated column size@>=
  12397. QSettings settings;
  12398. @<Obtain top level widget@>@;
  12399. settings.setValue(QString("columnWidths/%1/%2/%3").
  12400. arg(topLevelWidget->objectName()).
  12401. arg(objectName()).arg(column),
  12402. QVariant(newsize));
  12403. @ To determine which window a given table is in, we just follow
  12404. |parentWidget()| until there isn'@q'@>t one. It is possible that the table view
  12405. will also be the window, however this is not advised as it is easier for the
  12406. settings key to be non-unique in such a case.
  12407. @<Obtain top level widget@>=
  12408. QWidget *topLevelWidget = this;
  12409. while(topLevelWidget->parentWidget())
  12410. {
  12411. topLevelWidget = topLevelWidget->parentWidget();
  12412. }
  12413. @ We restore column widths in response to a show event. One of these should be
  12414. received just before the widget is shown so the widget should appear correctly.
  12415. @<SqlQueryView implementation@>=
  12416. void SqlQueryView::showEvent(QShowEvent *event)
  12417. {
  12418. @<Restore table column widths@>@;
  12419. event->accept();
  12420. }
  12421. @ Similarly, most of the body of this method has also been split into a chunk
  12422. so that it might be shared with other classes.
  12423. @<Restore table column widths@>=
  12424. QSettings settings;
  12425. @<Obtain top level widget@>
  12426. QString baseKey =
  12427. QString("columnWidths/%1/%2").arg(topLevelWidget->objectName()).
  12428. arg(objectName());
  12429. for(int i = 0; i < model()->columnCount(); i++)
  12430. {
  12431. QString key = QString("%1/%2").arg(baseKey).arg(i);
  12432. if(settings.contains(key))
  12433. {
  12434. setColumnWidth(i, settings.value(key).toInt());
  12435. }
  12436. }
  12437. @ A slot is required for obtaining the information to send out in our signals.
  12438. @<SqlQueryView implementation@>=
  12439. void SqlQueryView::openRow(const QModelIndex &index)
  12440. {
  12441. emit openEntry(((QSqlQueryModel *)model())->record(index.row()).value(0).toString());
  12442. emit openEntryRow(index.row());
  12443. }
  12444. @ The other functions are wrappers around model methods.
  12445. @<SqlQueryView implementation@>=
  12446. void SqlQueryView::setQuery(const QString &query)
  12447. {
  12448. QSqlDatabase database = AppInstance->database();
  12449. database.open();
  12450. QSqlQuery q(query, database);
  12451. ((QSqlQueryModel*)model())->setQuery(q);
  12452. database.close();
  12453. }
  12454. bool SqlQueryView::setHeaderData(int section, Qt::Orientation@, orientation,
  12455. const QVariant &value, int role)
  12456. {
  12457. return model()->setHeaderData(section, orientation, value, role);
  12458. }
  12459. @ A method is also provided to allow scripts to access the data.
  12460. @<SqlQueryView implementation@>=
  12461. QVariant SqlQueryView::data(int row, int column, int role)
  12462. {
  12463. return model()->data(model()->index(row, column), role);
  12464. }
  12465. @ To use this class, it is useful to expose it to the host environment.
  12466. @<Function prototypes for scripting@>=
  12467. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine);
  12468. QScriptValue constructSqlQueryView(QScriptContext *context,
  12469. QScriptEngine *engine);
  12470. QScriptValue SqlQueryView_setQuery(QScriptContext *context,
  12471. QScriptEngine *engine);
  12472. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  12473. QScriptEngine *engine);
  12474. @ The script constructor is passed to the host environment.
  12475. @<Set up the scripting engine@>=
  12476. constructor = engine->newFunction(constructSqlQueryView);
  12477. value = engine->newQMetaObject(&SqlQueryView::staticMetaObject, constructor);
  12478. engine->globalObject().setProperty("SqlQueryView", value);
  12479. @ Next we construct the view, add properties to access its methods from the host
  12480. environment, and pass that back.
  12481. @<Functions for scripting@>=
  12482. QScriptValue constructSqlQueryView(QScriptContext *, QScriptEngine *engine)
  12483. {
  12484. QScriptValue object = engine->newQObject(new SqlQueryView);
  12485. setSqlQueryViewProperties(object, engine);
  12486. return object;
  12487. }
  12488. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine)
  12489. {
  12490. setQTableViewProperties(value, engine);
  12491. value.setProperty("setHeaderData",
  12492. engine->newFunction(SqlQueryView_setHeaderData));
  12493. value.setProperty("setQuery", engine->newFunction(SqlQueryView_setQuery));
  12494. }
  12495. @ The properties added are simplified wrappers around the class methods.
  12496. @<Functions for scripting@>=
  12497. QScriptValue SqlQueryView_setQuery(QScriptContext *context, QScriptEngine *)
  12498. {
  12499. SqlQueryView *self = getself<SqlQueryView *>(context);
  12500. QString query = argument<QString>(0, context);
  12501. self->setQuery(query);
  12502. self->reset();
  12503. return QScriptValue();
  12504. }
  12505. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  12506. QScriptEngine *)
  12507. {
  12508. SqlQueryView *self = getself<SqlQueryView *>(context);
  12509. int section = argument<int>(0, context);
  12510. QString data = argument<QString>(1, context);
  12511. self->setHeaderData(section, Qt::Horizontal, data, Qt::DisplayRole);
  12512. return QScriptValue();
  12513. }
  12514. @** Reporting.
  12515. \noindent \pn{} version 1.4 added a new type of menu which is designed to
  12516. handle reports. This makes extensive use of the previously existing reporting
  12517. system at present which makes modifying existing reports to work with the new
  12518. system very simple. Further changes may be introduced in the future that
  12519. substantially depart from this in order to simplify report files.
  12520. Previously to add a new report to a configuration, you needed to create the
  12521. report, add an {\tt <include>} tag in the main configuration file to bring that
  12522. report into the application configuration, then in any window with a Reports
  12523. menu you would need to add the report to that menu in its configuration file
  12524. and write a small bit of JavaScript to obtain a reference to that new menu
  12525. item and create the report when that menu item is triggered. This is highly
  12526. repetetive, error prone, and with the new approach it is not needed at all.
  12527. To add a new report to a configuration using the new approach one need only
  12528. save the new report file in the appropriate directory and \pn{} will detect
  12529. this, add it to any Reports menus that may exist, and handle all of the details
  12530. of generating these reports on demand.
  12531. The Reports menu is created in a configuration as a {\tt <menu>} element with
  12532. three attributes. The {\tt name} attribute as usual is the name of the menu
  12533. item. The {\tt type} attribute will have a value of {\tt "reports"} and the
  12534. {\tt src} attribute will indicate the directory to search for reports to
  12535. populate that menu. This allows for multiple Reports menus with different
  12536. reports in each menu if desired.
  12537. Reports are added to the menu in the order of the file names in the reports
  12538. directory.
  12539. \danger While it should not be an issue with the limited number of reports
  12540. presently distributed with Typica, the approach taken to implementing this menu
  12541. type is highly inefficient. There are many optimizations available if this
  12542. becomes problematic.\endanger
  12543. When a report menu is generated, the directory used for this is added as a
  12544. search path for the |"reports"| prefix. This is used by the |createReport()|
  12545. script method and is intended to allow access to reports from outside of the
  12546. Report menu.
  12547. @<Populate reports menu@>=
  12548. QSettings settings;
  12549. QString reportDirectory = QString("%1/%2").arg(settings.value("config").
  12550. toString()).
  12551. arg(element.attribute("src"));
  12552. QDir::addSearchPath("reports", reportDirectory);
  12553. QDir directory(reportDirectory);
  12554. directory.setFilter(QDir::Files);
  12555. directory.setSorting(QDir::Name);
  12556. QStringList nameFilter;
  12557. nameFilter << "*.xml";
  12558. directory.setNameFilters(nameFilter);
  12559. QFileInfoList reportFiles = directory.entryInfoList();
  12560. for(int i = 0; i < reportFiles.size(); i++)
  12561. {
  12562. QFileInfo reportFile = reportFiles.at(i);
  12563. @<Add report to reports menu@>@;
  12564. }
  12565. @ The menu items themselves are a subclass of |QAction| which holds all of the
  12566. information needed to respond to its activation by generating the appropriate
  12567. report.
  12568. @<Class declarations@>=
  12569. class ReportAction : public QAction@/
  12570. {@/
  12571. @[Q_OBJECT@]@;
  12572. public:@/
  12573. ReportAction(const QString &fileName, const QString &reportName,
  12574. QObject *parent = NULL);@/
  12575. @[private slots@]:@/
  12576. void createReport();@/
  12577. private:@/
  12578. QString reportFile;@/
  12579. };
  12580. @ The constructor receives the name of the report file which is used to
  12581. generate the report when needed and the name of the report which is used as the
  12582. name presented in the menu.
  12583. @<ReportAction implementation@>=
  12584. ReportAction::ReportAction(const QString &fileName, const QString &reportName,
  12585. QObject *parent) :
  12586. QAction(reportName, parent), reportFile(fileName)
  12587. {
  12588. connect(this, SIGNAL(triggered()), this, SLOT(createReport()));
  12589. }
  12590. @ The slot method is responsible for creating the new report. This is very
  12591. similar to the old approach and reuses much of the same code. Of particular
  12592. note is the |targetID| variable. This is set to facilitate window geometry
  12593. management, though this should probably be set from the {\tt id} attribute
  12594. of the {\tt <window>} element in the file to preserve window geometry
  12595. settings if the configuration is moved to another location in the file
  12596. system.
  12597. @<ReportAction implementation@>=
  12598. void ReportAction::createReport()
  12599. {
  12600. QFile file(reportFile);
  12601. QDomDocument document;
  12602. if(file.open(QIODevice::ReadOnly))
  12603. {
  12604. document.setContent(&file, true);
  12605. QDomElement element = document.documentElement();
  12606. QScriptEngine *engine = AppInstance->engine;
  12607. QScriptContext *context = engine->pushContext();
  12608. QScriptValue object;
  12609. QString targetID = reportFile;
  12610. @<Display the window@>@;
  12611. file.close();
  12612. engine->popContext();
  12613. }
  12614. }
  12615. @ With the |ReportAction| available, we are now ready to add reports to the
  12616. Reports menu. To do this we check each file in the given directory to determine
  12617. if it is a report file, obtain the report title and location within the menu
  12618. hierarchy from the file data, create the actions, and add them to the menu.
  12619. @<Add report to reports menu@>=
  12620. QString path = reportFile.absoluteFilePath();
  12621. QFile file(path);
  12622. if(file.open(QIODevice::ReadOnly))
  12623. {
  12624. QDomDocument document;
  12625. document.setContent(&file, true);
  12626. QDomElement root = document.documentElement();
  12627. QString translationContext = root.attribute("id");
  12628. QDomNode titleNode = root.elementsByTagName("reporttitle").at(0);
  12629. if(!titleNode.isNull())
  12630. {
  12631. QDomElement titleElement = titleNode.toElement();
  12632. QString title = QCoreApplication::translate("configuration",
  12633. titleElement.text().toUtf8().data());
  12634. if(!title.isEmpty())
  12635. {
  12636. QStringList hierarchy = title.split(":->");
  12637. QMenu *insertionPoint = menu;
  12638. @<Traverse report menu hierarchy@>
  12639. ReportAction *action = new ReportAction(path, hierarchy.last());
  12640. insertionPoint->addAction(action);
  12641. }
  12642. }
  12643. }
  12644. @ \pn{} allows the Reports menu to contain arbitrarily deep menu hierarchies.
  12645. It is advised to keep these hierarchies shallow.
  12646. @<Traverse report menu hierarchy@>=
  12647. for(int j = 0; j < hierarchy.size() - 1; j++)
  12648. {
  12649. QObjectList menuList = insertionPoint->children();
  12650. bool menuFound = @[false@];
  12651. for(int k = 0; k < menuList.size(); k++)
  12652. {
  12653. QMenu *currentItem = qobject_cast<QMenu*>(menuList.at(k));
  12654. if(currentItem)
  12655. {
  12656. if(currentItem->title() == hierarchy.at(j))
  12657. {
  12658. menuFound = @[true@];
  12659. insertionPoint = currentItem;
  12660. break;
  12661. }
  12662. }
  12663. }
  12664. if(!menuFound)
  12665. {
  12666. insertionPoint = insertionPoint->addMenu(hierarchy.at(j));
  12667. }
  12668. }
  12669. @ \noindent The reporting functionality in \pn{} is based on the Scribe framework
  12670. in Qt. This brings several benefits, including making it easy to print reports
  12671. or save reports as plain text or HTML.
  12672. Reports are specified in the \pn{}'@q'@>s configuration document and can include both
  12673. static elements and elements that are populated by external data such as the
  12674. result of a SQL query.
  12675. @<Function prototypes for scripting@>=
  12676. void addReportToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  12677. QStack<QLayout *> *layoutStack);
  12678. @ When adding a report to a layout, we must not only add the widget to the
  12679. layout, but also construct the document.
  12680. @<Functions for scripting@>=
  12681. void addReportToLayout(QDomElement element, QStack<QWidget *> *,@|
  12682. QStack<QLayout *> *layoutStack)
  12683. {
  12684. QTextEdit *widget = new QTextEdit;
  12685. if(element.hasAttribute("id"))
  12686. {
  12687. widget->setObjectName(element.attribute("id"));
  12688. }
  12689. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  12690. layout->addWidget(widget);
  12691. QTextDocument *document = new QTextDocument;
  12692. QFont defaultFont;
  12693. defaultFont.setPointSize(11);
  12694. document->setDefaultFont(defaultFont);
  12695. QTextCursor cursor(document);
  12696. @<Construct report document@>@;
  12697. widget->setDocument(document);
  12698. }
  12699. @ Several child elements are allowed under the {\tt <report>} element. These
  12700. should be processed in order to produce the final report document.
  12701. @<Construct report document@>=
  12702. QDomNodeList children = element.childNodes();
  12703. for(int i = 0; i < children.count(); i++)
  12704. {
  12705. QDomNode current;
  12706. QDomElement currentElement;
  12707. current = children.at(i);
  12708. if(current.isElement())
  12709. {
  12710. currentElement = current.toElement();
  12711. @<Process report document elements@>@;
  12712. }
  12713. }
  12714. @ If any custom styling for HTML content is required, a {\tt <style>} element
  12715. should be placed in the report description before any such content.
  12716. @<Process report document elements@>=
  12717. if(currentElement.tagName() == "style")
  12718. {
  12719. document->setDefaultStyleSheet(currentElement.text());
  12720. }
  12721. @ One common need is the ability to insert static text, such as the title of the
  12722. report. In order to simplify formatting, the text can be interpreted as HTML.
  12723. Note that to avoid having HTML tags eaten by the parser, the text of this
  12724. element should be a CDATA section.
  12725. @<Process report document elements@>=
  12726. if(currentElement.tagName() == "html")
  12727. {
  12728. cursor.insertHtml(currentElement.text());
  12729. }
  12730. @ If no special formatting is needed, a plain text element can be used. This
  12731. might be extended in the future to allow attributes for specifying the character
  12732. formatting to be used with the text.
  12733. @<Process report document elements@>=
  12734. if(currentElement.tagName() == "text")
  12735. {
  12736. cursor.insertText(currentElement.text());
  12737. }
  12738. @ One of the more interesting elements of a report is the {\tt <table>} element.
  12739. This is an element which can change its contents in response to changes in user
  12740. controls.
  12741. @<Process report document elements@>=
  12742. if(currentElement.tagName() == "table")
  12743. {
  12744. QTextFrame *frame = cursor.insertFrame(QTextFrameFormat());
  12745. ReportTable *table = new ReportTable(frame, currentElement);
  12746. table->setParent(widget);
  12747. if(currentElement.hasAttribute("id"))
  12748. {
  12749. table->setObjectName(currentElement.attribute("id"));
  12750. }
  12751. }
  12752. @ The |ReportTable| class is responsible for parsing {\tt <table>} child
  12753. elements and inserting the table into the document at the correct location.
  12754. @<Class declarations@>=
  12755. class ReportTable : public QObject@/
  12756. {@t\1@>@/
  12757. Q_OBJECT@;
  12758. QTextFrame *area;
  12759. QDomElement configuration;
  12760. QMap<QString, QVariant> bindings;
  12761. public:@/
  12762. ReportTable(QTextFrame *frame, QDomElement description);
  12763. ~ReportTable();
  12764. @[Q_INVOKABLE@,@, void@]@, bind(QString placeholder, QVariant value);@t\2\2@>@/
  12765. @t\4@>public slots@t\kern-3pt@>:@/
  12766. void refresh();@t\2@>@/
  12767. }@t\kern-3pt@>;
  12768. @ The |ReportTable| class takes a |QTextFrame| and |QDomElement| pointer in
  12769. its constructor. The former is used to establish the bounds of the table within
  12770. a document and the latter is used for generating the table contents.
  12771. @<ReportTable implementation@>=
  12772. ReportTable::ReportTable(QTextFrame *frame, QDomElement description) :
  12773. area(frame), configuration(description)
  12774. {
  12775. refresh();
  12776. }
  12777. ReportTable::~ReportTable()
  12778. {
  12779. }
  12780. @ In order to change the table contents based on user controls, the |bind()|
  12781. method allows a placeholder to be replaced with a value when evaluating a SQL
  12782. query.
  12783. @<ReportTable implementation@>=
  12784. void ReportTable::bind(QString placeholder, QVariant value)
  12785. {
  12786. bindings.insert(placeholder, value);
  12787. }
  12788. @ All of the interesting work is done in the |refresh()| slot. This method
  12789. deletes the current content of the frame and creates a table based on the
  12790. description of the table in the configuration document.
  12791. @<ReportTable implementation@>=
  12792. void ReportTable::refresh()
  12793. {
  12794. @<Delete current report table content@>@;
  12795. int rows = 1;
  12796. int columns = 1;
  12797. int currentRow = 0;
  12798. QTextTable *table = cursor.insertTable(rows, columns);
  12799. @<Set table formatting@>@;
  12800. @<Reconstruct report table content@>@;
  12801. if(rows > 1)
  12802. {
  12803. table->removeRows(0, 1);
  12804. }
  12805. }
  12806. @ Deleting the current content of the table involves using a cursor to select
  12807. everything in the frame and then removing that selection. There are more optimal
  12808. ways to do this but if there are performance problems with this, you may want to
  12809. reconsider what you are trying to do.
  12810. @<Delete current report table content@>=
  12811. QTextCursor cursor = area->firstCursorPosition();
  12812. while(cursor < area->lastCursorPosition())
  12813. {
  12814. cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
  12815. }
  12816. cursor.removeSelectedText();
  12817. @ When creating a new table, we may need to alter the formatting of that table.
  12818. To do this, we get the current format, modify that based on attributes of the
  12819. {\tt <table>} element, and apply the modified copy to the newly constructed
  12820. table.
  12821. @<Set table formatting@>=
  12822. QTextTableFormat format = table->format();
  12823. format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
  12824. if(configuration.hasAttribute("align"))
  12825. {
  12826. if(configuration.attribute("align") == "center")
  12827. {
  12828. format.setAlignment(Qt::AlignHCenter);
  12829. }
  12830. }
  12831. table->setFormat(format);
  12832. @ To reconstruct the table, we need to parse the description of the table.
  12833. @<Reconstruct report table content@>=
  12834. QDomNodeList children = configuration.childNodes();
  12835. for(int i = 0; i < children.count(); i++)
  12836. {
  12837. QDomNode current;
  12838. QDomElement currentElement;
  12839. current = children.at(i);
  12840. if(current.isElement())
  12841. {
  12842. currentElement = current.toElement();
  12843. if(currentElement.tagName() == "query")
  12844. {
  12845. @<Add SQL query results to report table@>@;
  12846. }
  12847. else if(currentElement.tagName() == "row")
  12848. {
  12849. @<Add new row to report table@>@;
  12850. }
  12851. }
  12852. }
  12853. @ The text of a {\tt <query>} element will be the query desired in the table.
  12854. This might include placeholders that must be bound to values before the query is
  12855. executed. If query execution results in an error (as it will if it contains
  12856. placeholders that have not yet had values bound to them), there will be no
  12857. change to the table and the next child element, if any, will be processed.
  12858. @<Add SQL query results to report table@>=
  12859. SqlQueryConnection h;
  12860. QSqlQuery *query = h.operator->();
  12861. query->prepare(currentElement.text());
  12862. foreach(QString key, bindings.uniqueKeys())
  12863. {
  12864. if(currentElement.text().contains(key))
  12865. {
  12866. query->bindValue(key, bindings.value(key));
  12867. }
  12868. }
  12869. query->exec();
  12870. if(!query->next())
  12871. {
  12872. continue;
  12873. }
  12874. if(query->record().count() > columns)
  12875. {
  12876. table->appendColumns(query->record().count() - columns);
  12877. }
  12878. do
  12879. {
  12880. table->appendRows(1);
  12881. rows++;
  12882. currentRow++;
  12883. for(int j = 0; j < query->record().count(); j++)
  12884. {
  12885. QTextTableCell cell = table->cellAt(currentRow, j);
  12886. cursor = cell.firstCursorPosition();
  12887. cursor.insertText(query->value(j).toString());
  12888. }
  12889. } while(query->next());
  12890. @ It is sometimes desirable to add fixed data such as column headers to a table.
  12891. This is done with the {\tt <row>} element.
  12892. Technically, this isn'@q'@>t needed. The same results can be produced by using a
  12893. {\tt <query>} element to select constant data, but this approach saves a trip to
  12894. the database.
  12895. @<Add new row to report table@>=
  12896. table->appendRows(1);
  12897. currentRow++;
  12898. rows++;
  12899. QDomNodeList rowChildren = currentElement.childNodes();
  12900. int currentColumn = 0;
  12901. for(int j = 0; j < rowChildren.count(); j++)
  12902. {
  12903. QDomNode node;
  12904. QDomElement nodeElement;
  12905. node = rowChildren.at(j);
  12906. if(node.isElement())
  12907. {
  12908. nodeElement = node.toElement();
  12909. if(nodeElement.tagName() == "cell")
  12910. {
  12911. if(currentColumn == columns)
  12912. {
  12913. table->appendColumns(1);
  12914. columns++;
  12915. }
  12916. QTextTableCell cell = table->cellAt(currentRow, currentColumn);
  12917. cursor = cell.firstCursorPosition();
  12918. cursor.insertText(nodeElement.text());
  12919. currentColumn++;
  12920. }
  12921. }
  12922. }
  12923. @ In order to expose report printing capabilities, we provide a property on
  12924. |QTextEdit| objects to handle this.
  12925. @<Function prototypes for scripting@>=
  12926. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine);
  12927. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *engine);
  12928. @ This function is a trivial adaptation from the Qt documentation.
  12929. @<Functions for scripting@>=
  12930. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *)
  12931. {
  12932. QTextEdit *self = getself<QTextEdit *>(context);
  12933. QTextDocument *document = self->document();
  12934. QPrinter printer;
  12935. QPrintDialog printwindow(&printer, self);
  12936. if(printwindow.exec() != QDialog::Accepted)
  12937. {
  12938. return QScriptValue();
  12939. }
  12940. document->print(&printer);
  12941. return QScriptValue();
  12942. }
  12943. @ The host environment must be informed of this function.
  12944. @<Functions for scripting@>=
  12945. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine)
  12946. {
  12947. setQAbstractScrollAreaProperties(value, engine);
  12948. value.setProperty("print", engine->newFunction(QTextEdit_print));
  12949. }
  12950. @i plugins.w
  12951. @i daterangeselector.w
  12952. @** An area for repeated user interface elements.
  12953. \noindent There are multiple use cases in which it is useful to specify a
  12954. complex aggregation of user interface elements to be repeated arbitrarily many
  12955. times. For example, placing multiple copies of a cupping form in a single area
  12956. for conveniently entering observations for all coffees in a particular session
  12957. or providing any number of copies of the form for entering coffee purchase
  12958. information. The |FormArray| widget provides this capability, allowing the
  12959. XML portion of the configuration document to specify the form once and allowing
  12960. the host environment to access the copies.
  12961. Slots and the |Q_INVOKABLE| macro are used to simplify the use of this class
  12962. from the host environment.
  12963. @<Class declarations@>=
  12964. class FormArray : public QScrollArea@/
  12965. {@t\1@>@/
  12966. Q_OBJECT@;
  12967. QDomElement configuration;
  12968. QWidget itemContainer;
  12969. QVBoxLayout itemLayout;
  12970. int maxwidth;
  12971. int maxheight;
  12972. public:@/
  12973. FormArray(QDomElement description);
  12974. @[Q_INVOKABLE@,@, QWidget*@] elementAt(int index);@t\2\2@>@/
  12975. @[Q_INVOKABLE@,@, int@] elements();@t\2\2@>@/
  12976. @t\4@>public slots@t\kern-3pt@>:@/
  12977. void addElements(int copies = 1);
  12978. void removeAllElements();
  12979. void setMaximumElementWidth(int width);
  12980. void setMaximumElementHeight(int height);@t\2@>@/
  12981. }@t\kern-3pt@>;
  12982. @ The |FormArray| is just a |QScrollArea| providing a view onto a |QWidget|
  12983. containing a layout which has arbitrarily many copies of a |QWidget| with
  12984. contents determined by the configuration document used to create the
  12985. |FormArray|.
  12986. @<FormArray implementation@>=
  12987. FormArray::FormArray(QDomElement description) : configuration(description),
  12988. maxwidth(-1), maxheight(-1)@/
  12989. {
  12990. setWidget(&itemContainer);
  12991. itemContainer.setLayout(&itemLayout);
  12992. }
  12993. @ The |FormArray| was initially created by an XML element. A copy of this is
  12994. stored in the private variable |configuration|. This can have the same child
  12995. elements as {\tt <widget>}, allowing us to reuse the function for creating
  12996. populating the widget. When adding a new element, we must resize the
  12997. |itemContainer|, otherwise Qt will attempt to cram all widgets in the layout
  12998. into the same vertical space as was previously required. The result is not
  12999. attractive. We also set a minimum width just in case the newly created widget is
  13000. the first one added to the area.
  13001. @<FormArray implementation@>=
  13002. void FormArray::addElements(int copies)
  13003. {
  13004. QStack<QWidget *> *widgetStack = new QStack<QWidget *>;
  13005. QStack<QLayout *> *layoutStack = new QStack<QLayout *>;
  13006. QWidget *widget;
  13007. for(int i = 0; i < copies; i++)
  13008. {
  13009. widget = new QWidget;
  13010. if(maxwidth > -1)
  13011. {
  13012. widget->setMaximumWidth(maxwidth);
  13013. }
  13014. if(maxheight > -1)
  13015. {
  13016. widget->setMaximumHeight(maxheight);
  13017. }
  13018. if(configuration.hasChildNodes())
  13019. {
  13020. widgetStack->push(widget);
  13021. populateWidget(configuration, widgetStack, layoutStack);
  13022. widgetStack->pop();
  13023. widget->setMinimumHeight(widget->sizeHint().height());
  13024. itemLayout.addWidget(widget);
  13025. if(widget->sizeHint().height() > maxheight && maxheight > -1)
  13026. {
  13027. itemContainer.setMinimumHeight(maxheight * elements() + 50);
  13028. }
  13029. else
  13030. {
  13031. itemContainer.setMinimumHeight(itemContainer.sizeHint().height()
  13032. + widget->sizeHint().height());
  13033. }
  13034. if(maxwidth > -1)
  13035. {
  13036. itemContainer.setMinimumWidth(maxwidth + 50);
  13037. }
  13038. else
  13039. {
  13040. itemContainer.setMinimumWidth(widget->sizeHint().width() + 50);
  13041. }
  13042. }
  13043. }
  13044. }
  13045. @ In order to retrieve a widget from the area, we use the |elementAt()| method.
  13046. The pointer returned by this function can be used as the first argument to
  13047. |findChildObject()| in the host environment in order to find any widget in the
  13048. form.
  13049. @<FormArray implementation@>=
  13050. QWidget* FormArray::elementAt(int index)
  13051. {
  13052. if(index < itemLayout.count())
  13053. {
  13054. QLayoutItem *item = itemLayout.itemAt(index);
  13055. return item->widget();
  13056. }
  13057. else
  13058. {
  13059. return NULL;
  13060. }
  13061. }
  13062. @ Removing all elements is trivial, however we must be sure to reset the size of
  13063. |itemContainer|.
  13064. @<FormArray implementation@>=
  13065. void FormArray::removeAllElements()
  13066. {
  13067. while(itemLayout.count() > 0)
  13068. {
  13069. QLayoutItem *item;
  13070. item = itemLayout.itemAt(0);
  13071. item->widget()->hide();
  13072. itemLayout.removeWidget(item->widget());
  13073. }
  13074. itemContainer.setMinimumHeight(0);
  13075. }
  13076. @ This just leaves a method for determining the number of elements already in
  13077. the view. This is equal to the number of items in the layout.
  13078. @<FormArray implementation@>=
  13079. int FormArray::elements()
  13080. {
  13081. return itemLayout.count();
  13082. }
  13083. @ Some widgets do not behave well in a |FormArray| setting and will try to use
  13084. an excess of screen space. In these cases, constraining the size of the elements
  13085. can be beneficial. These just set private member variables which are used when
  13086. adding new elements.
  13087. @<FormArray implementation@>=
  13088. void FormArray::setMaximumElementWidth(int width)
  13089. {
  13090. maxwidth = width;
  13091. }
  13092. void FormArray::setMaximumElementHeight(int height)
  13093. {
  13094. maxheight = height;
  13095. }
  13096. @ In order to create an instance of this class from the configuration document,
  13097. a {\tt <formarray>} element is used. This can be added to any layout.
  13098. @<Function prototypes for scripting@>=
  13099. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  13100. QStack<QLayout *> *layoutStack);
  13101. @ Processing child elements is deferred until a call to
  13102. |FormArray::addElements()| has been made.
  13103. @<Functions for scripting@>=
  13104. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *,@|
  13105. QStack<QLayout *> *layoutStack)
  13106. {
  13107. FormArray *widget = new FormArray(element);
  13108. if(element.hasAttribute("id"))
  13109. {
  13110. widget->setObjectName(element.attribute("id"));
  13111. }
  13112. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13113. layout->addWidget(widget);
  13114. }
  13115. @** Scale widgets.
  13116. \noindent One of the most commonly used methods of documenting the properties of
  13117. a coffee is through a cupping form. Several such forms exist to meet different
  13118. needs, however most involve several scales which can be marked to determine some
  13119. aspect of a particular attribute. Some of these scales are scored values which,
  13120. when considered with other scored values produce a numerical representation of
  13121. the quality of a given coffee. Others are unscored values which serve to provide
  13122. additional documentation of a property. For example, when the SCAA cupping form
  13123. expanded to the current form of ten scored properties with defects subtracted
  13124. from the total, a second scale was added for the acidity property. The scored
  13125. scale is used for marking the quality of the acidity while another unscored
  13126. scale is used for marking the intensity of that acidity.
  13127. Previously, in order to enter cupping information in \pn{}, numeric entry fields
  13128. were used. While this was very efficient for transcribing paper cupping forms
  13129. (and this was, in fact, the principal use case for our prototype cupping form
  13130. database software), it is not a form that lends itself to convenient use at the
  13131. cupping table.
  13132. Two new widgets are therefore introduced which allows a cupper to simply click
  13133. at some point on the scale to record that impression. Unfortunately, this is
  13134. still something of a tradeoff. It is not quite so efficient as using a paper
  13135. form in my experience, however it is faster than transcribing a stack of cupping
  13136. forms, particularly when working with cuppers with ambiguous handwriting. By
  13137. moving data acquisition to the point of data generation, a more useful record
  13138. can be produced for use in aggregate analysis.
  13139. @* The Horizontal Scale.
  13140. \noindent Several cupping forms make use of 10 point scales for the quality of
  13141. various attributes. The |ScaleControl| widget provides such a scale. It
  13142. consists of a bar with major ticks at 0, 5, and 10 and minor ticks at integer
  13143. values within this range. The first click sets both the initial and final value
  13144. of the scale while subsequent clicks adjust only the final value. A pair of
  13145. controls at each end of the scale allows the user to adjust either of these
  13146. values to compensate for imprecision at the point of the click. The two values,
  13147. an initial unscored value and a final scored value, provide some limited
  13148. temporal documentation. That is, it documents how the perception of a coffee
  13149. changes as it cools.
  13150. The widget is implemented as a |QGraphicsView| subclass. Please note that the
  13151. scale widgets are not particularly robust. In order to support a broader range
  13152. of cupping forms, there are plans to extend this class to allow user defined
  13153. range and tick patterns and user defined colors for the indicators.
  13154. @<Class declarations@>=
  13155. class ScaleControl : public QGraphicsView@/
  13156. {@t\1@>@/
  13157. Q_OBJECT@/
  13158. Q_PROPERTY(double initialValue READ initialValue WRITE setInitialValue)@/
  13159. Q_PROPERTY(double finalValue READ finalValue WRITE setFinalValue)@/
  13160. @<ScaleControl private members@>@t\2\2@>@/
  13161. public:@/
  13162. ScaleControl();
  13163. double initialValue(void);
  13164. double finalValue(void);
  13165. virtual QSize sizeHint() const;@/
  13166. @[public slots@]:@/
  13167. void setInitialValue(double value);
  13168. void setFinalValue(double value);@/
  13169. signals:@/
  13170. void initialChanged(double);
  13171. void finalChanged(double);@/
  13172. protected:@/
  13173. virtual void mousePressEvent(QMouseEvent *event);
  13174. virtual void mouseReleaseEvent(QMouseEvent *event);@t\2@>@/
  13175. }@t\kern-4pt@>;
  13176. @ The private variables available to instances of this class are used for
  13177. managing various aspects of the widget.
  13178. @<ScaleControl private members@>=
  13179. QGraphicsScene scene;
  13180. QGraphicsPolygonItem initialDecrement;
  13181. QGraphicsPolygonItem initialIncrement;
  13182. QGraphicsPolygonItem finalDecrement;
  13183. QGraphicsPolygonItem finalIncrement;
  13184. QGraphicsPolygonItem initialIndicator;
  13185. QGraphicsPolygonItem finalIndicator;
  13186. QGraphicsPathItem scaleLine;
  13187. QPolygonF left;
  13188. QPolygonF right;
  13189. QPolygonF down;
  13190. QPolygonF up;
  13191. QPainterPath scalePath;
  13192. QBrush initialBrush;
  13193. QBrush finalBrush;
  13194. double nonScoredValue;
  13195. double scoredValue;
  13196. bool initialSet;
  13197. bool finalSet;
  13198. bool scaleDown;
  13199. @ The constructor sets up the scene displayed by this widget. There is
  13200. considerable room for improvement here.
  13201. @<ScaleControl implementation@>=
  13202. ScaleControl::ScaleControl() : QGraphicsView(NULL, NULL), nonScoredValue(-1),
  13203. scoredValue(-1), initialSet(false), finalSet(false), scaleDown(false)
  13204. {
  13205. left << QPointF(0, 5) << QPointF(10, 0) << QPointF(10, 10) <<
  13206. QPointF(0, 5);
  13207. right << QPointF(10, 5) << QPointF(0, 0) << QPointF(0, 10) <<
  13208. QPointF(10, 5);
  13209. down << QPointF(0, 0) << QPointF(-5, -10) << QPointF(5, -10) <<
  13210. QPointF(0, 0);
  13211. up << QPointF(0, 0) << QPointF(-5, 10) << QPointF(4, 10) << QPointF(0, 0);
  13212. initialBrush.setColor(QColor(170, 170, 255));
  13213. initialBrush.setStyle(Qt::SolidPattern);
  13214. finalBrush.setColor(Qt::blue);
  13215. finalBrush.setStyle(Qt::SolidPattern);
  13216. initialDecrement.setPolygon(left);
  13217. initialDecrement.setBrush(initialBrush);
  13218. initialDecrement.setPos(0, 0);
  13219. scene.addItem(&initialDecrement);
  13220. initialIncrement.setPolygon(right);
  13221. initialIncrement.setBrush(initialBrush);
  13222. initialIncrement.setPos(122, 0);
  13223. scene.addItem(&initialIncrement);
  13224. finalDecrement.setPolygon(left);
  13225. finalDecrement.setBrush(finalBrush);
  13226. finalDecrement.setPos(0, 12);
  13227. scene.addItem(&finalDecrement);
  13228. finalIncrement.setPolygon(right);
  13229. finalIncrement.setBrush(finalBrush);
  13230. finalIncrement.setPos(122, 12);
  13231. scene.addItem(&finalIncrement);
  13232. scalePath.moveTo(0, 10);
  13233. scalePath.lineTo(100, 10);
  13234. scalePath.moveTo(0, 0);
  13235. scalePath.lineTo(0, 20);
  13236. scalePath.moveTo(10, 5);
  13237. scalePath.lineTo(10, 15);
  13238. scalePath.moveTo(20, 5);
  13239. scalePath.lineTo(20, 15);
  13240. scalePath.moveTo(30, 5);
  13241. scalePath.lineTo(30, 15);
  13242. scalePath.moveTo(40, 5);
  13243. scalePath.lineTo(40, 15);
  13244. scalePath.moveTo(50, 0);
  13245. scalePath.lineTo(50, 20);
  13246. scalePath.moveTo(60, 5);
  13247. scalePath.lineTo(60, 15);
  13248. scalePath.moveTo(70, 5);
  13249. scalePath.lineTo(70, 15);
  13250. scalePath.moveTo(80, 5);
  13251. scalePath.lineTo(80, 15);
  13252. scalePath.moveTo(90, 5);
  13253. scalePath.lineTo(90, 15);
  13254. scalePath.moveTo(100, 0);
  13255. scalePath.lineTo(100, 20);
  13256. scaleLine.setPath(scalePath);
  13257. scaleLine.setPos(16, 1);
  13258. scene.addItem(&scaleLine);
  13259. setScene(&scene);
  13260. initialIndicator.setPolygon(down);
  13261. initialIndicator.setBrush(initialBrush);
  13262. finalIndicator.setPolygon(up);
  13263. finalIndicator.setBrush(finalBrush);
  13264. setMinimumSize(sizeHint());
  13265. setMaximumSize(sizeHint());
  13266. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13267. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13268. setMinimumSize(sizeHint());
  13269. }
  13270. @ The size hint forces a smaller representation of the widget, making it easier
  13271. to arrange with other widgets.
  13272. @<ScaleControl implementation@>=
  13273. QSize ScaleControl::sizeHint() const
  13274. {
  13275. return QSize(140, 30);
  13276. }
  13277. @ The methods for setting the values represented on the scale must ensure that
  13278. the appropriate indicator is drawn and position it appropriately.
  13279. @<ScaleControl implementation@>=
  13280. void ScaleControl::setInitialValue(double value)@t\2\2@>@/
  13281. {@t\1@>@/
  13282. if(value >= 0 && value <= 10)@/
  13283. {@t\1@>@/
  13284. nonScoredValue = value;
  13285. if(!initialSet)
  13286. {
  13287. scene.addItem(&initialIndicator);
  13288. }
  13289. initialSet = true;
  13290. initialIndicator.setPos(value * 10 + 16, 10);
  13291. emit initialChanged(value);
  13292. if(!finalSet)
  13293. {
  13294. setFinalValue(value);
  13295. }@t\2@>@/
  13296. }@t\2@>@/
  13297. }@/@/
  13298. void ScaleControl::setFinalValue(double value)@t\2\2@>@/
  13299. {@t\1@>@/
  13300. if(value >= 0 && value <= 10)@/
  13301. {@t\1@>@/
  13302. scoredValue = value;
  13303. if(!finalSet)@/
  13304. {
  13305. scene.addItem(&finalIndicator);
  13306. }
  13307. finalSet = true;
  13308. finalIndicator.setPos(value * 10 + 16, 11);
  13309. emit finalChanged(value);@t\2@>@/
  13310. }@t\2@>@/
  13311. }
  13312. @ These values can, of course, be retrieved programmatically.
  13313. @<ScaleControl implementation@>=
  13314. double ScaleControl::initialValue(void)
  13315. {
  13316. return nonScoredValue;
  13317. }
  13318. double ScaleControl::finalValue(void)
  13319. {
  13320. return scoredValue;
  13321. }
  13322. @ This only leaves the matter of handling interaction with the widget. A future
  13323. version of this class might split the various interface elements in the scene
  13324. into distinct classes capable of using the event propagation capabilities
  13325. provided by the graphics view framework, however with the current design, we
  13326. must do a little more work.
  13327. There are two events which must be accepted in order to register a click on a
  13328. given portion of the scale. One event is generated when the mouse button is
  13329. pressed.
  13330. @<ScaleControl implementation@>=
  13331. void ScaleControl::mousePressEvent(QMouseEvent *event)
  13332. {
  13333. @<Check that the left button was pressed@>@;
  13334. scaleDown = @[true@];
  13335. event->accept();
  13336. }
  13337. @ The primary action button on the mouse is the left button. While there might
  13338. be sensible interactions to provide in response to other buttons, these are not
  13339. presently supported.
  13340. @<Check that the left button was pressed@>=
  13341. if(event->button() != Qt::LeftButton)
  13342. {
  13343. event->ignore();
  13344. return;
  13345. }
  13346. @ Most of the click event handling is done in response to releasing the mouse
  13347. button. In this event handler we must determine if the click occurred in a
  13348. clickable portion of the scale and take the appropriate action in response.
  13349. @<ScaleControl implementation@>=
  13350. void ScaleControl::mouseReleaseEvent(QMouseEvent *event)@t\2\2@>@/
  13351. {@t\1@>@/
  13352. @<Check that the left button was pressed@>@;
  13353. if(!scaleDown)
  13354. {
  13355. event->ignore();
  13356. return;
  13357. }
  13358. scaleDown = false;
  13359. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  13360. @<Handle clicks in the decrement controls@>@;
  13361. @<Handle clicks in the increment controls@>@;
  13362. @<Handle clicks in the scale area@>@;
  13363. event->ignore();
  13364. return;@t\2@>@/
  13365. }
  13366. @ As currently implemented, each horizontal pixel position represents a value
  13367. evenly divisible by $0.1$. It is, however, quite common to see vaues with a
  13368. $.25$ or $.75$ after the whole number on cupping forms. In order to make it
  13369. possible to select such values without vastly increasing the length of the
  13370. scale, the increment and decrement controls adjust the represented value by
  13371. $0.05$.
  13372. @<Handle clicks in the decrement controls@>=
  13373. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 10)
  13374. {
  13375. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13376. {
  13377. if(initialSet)
  13378. {
  13379. setInitialValue(nonScoredValue - 0.05);
  13380. }
  13381. event->accept();
  13382. return;
  13383. }
  13384. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  13385. {
  13386. if(finalSet)
  13387. {
  13388. setFinalValue(scoredValue - 0.05);
  13389. event->accept();
  13390. return;
  13391. }
  13392. }
  13393. }
  13394. @ Incrementing represented values is done in the same manner as decrementing
  13395. them.
  13396. @<Handle clicks in the increment controls@>=
  13397. else if(sceneCoordinate.x() >= 122 && sceneCoordinate.x() <= 132)
  13398. {
  13399. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13400. {
  13401. if(initialSet)
  13402. {
  13403. setInitialValue(nonScoredValue + 0.05);
  13404. event->accept();
  13405. return;
  13406. }
  13407. }
  13408. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  13409. {
  13410. if(finalSet)
  13411. {
  13412. setFinalValue(scoredValue + 0.05);
  13413. event->accept();
  13414. return;
  13415. }
  13416. }
  13417. }
  13418. @ When handling clicks in the scale area, there is a difference between the
  13419. first click and any subsequent click.
  13420. @<Handle clicks in the scale area@>=
  13421. double relativeX = sceneCoordinate.x() - 16;
  13422. if(initialSet)
  13423. {
  13424. if(relativeX >= 0 && relativeX <= 100)
  13425. {
  13426. setFinalValue(relativeX / 10.0);
  13427. event->accept();
  13428. return;
  13429. }
  13430. }
  13431. else
  13432. {
  13433. if(relativeX >= 0 && relativeX <= 100)
  13434. {
  13435. setInitialValue(relativeX / 10.0);
  13436. event->accept();
  13437. return;
  13438. }
  13439. }
  13440. @* The Vertical Scale.
  13441. \noindent In addition to the horizontal scale, there is also a vertical scale.
  13442. The implementation of this class is in some ways a bit simpler as only one value
  13443. must be retained. While there is no prohibition on using this scale for scored
  13444. values (and this might enable a rather compact representation which might be
  13445. useful in some applications), its intent is for unscored values which are less
  13446. likely to change over time. If the dry aroma of a coffee changes significantly
  13447. during a cupping session, you are most likely waiting far too long to pour the
  13448. water.
  13449. @<Class declarations@>=
  13450. class IntensityControl : public QGraphicsView@/
  13451. {@/
  13452. @[Q_OBJECT@]@;
  13453. @[Q_PROPERTY(double value READ value WRITE setValue)@]@;
  13454. QGraphicsScene scene;
  13455. QGraphicsPolygonItem decrement;
  13456. QGraphicsPolygonItem increment;
  13457. QGraphicsPolygonItem indicator;
  13458. QGraphicsPathItem scaleLine;
  13459. QPolygonF left;
  13460. QPolygonF up;
  13461. QPolygonF down;
  13462. QPainterPath scalePath;
  13463. QBrush theBrush;
  13464. double theValue;
  13465. bool valueSet;
  13466. bool scaleDown;
  13467. public:@/
  13468. IntensityControl();
  13469. double value();
  13470. virtual QSize sizeHint() const;@/
  13471. @[public slots@]:@/
  13472. void setValue(double val);@/
  13473. signals:@/
  13474. void valueChanged(double);@/
  13475. protected:@/
  13476. virtual void mousePressEvent(QMouseEvent *event);
  13477. virtual void mouseReleaseEvent(QMouseEvent *event);@/
  13478. };
  13479. @ Note the similarity between this constructor and the the |ScaleControl|
  13480. constructor.
  13481. @<IntensityControl implementation@>=
  13482. IntensityControl::IntensityControl() : QGraphicsView(NULL, NULL), theValue(-1),
  13483. valueSet(false), scaleDown(false)
  13484. {
  13485. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13486. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13487. left << QPointF(0, 0) << QPointF(10, -5) << QPointF(10, 5) << QPointF(0, 0);
  13488. down << QPointF(0, 0) << QPointF(10, 0) << QPointF(5, 10) << QPointF(0, 0);
  13489. up << QPointF(0, 10) << QPointF(10, 10) << QPointF(5, 0) << QPointF(0, 10);
  13490. theBrush.setColor(Qt::blue);
  13491. theBrush.setStyle(Qt::SolidPattern);
  13492. increment.setPolygon(up);
  13493. increment.setBrush(theBrush);
  13494. increment.setPos(0, 0);
  13495. scene.addItem(&increment);
  13496. decrement.setPolygon(down);
  13497. decrement.setBrush(theBrush);
  13498. decrement.setPos(0, 122);
  13499. scene.addItem(&decrement);
  13500. scalePath.moveTo(5, 0);
  13501. scalePath.lineTo(5, 100);
  13502. scalePath.moveTo(0, 0);
  13503. scalePath.lineTo(10, 0);
  13504. scalePath.moveTo(0, 10);
  13505. scalePath.lineTo(10, 10);
  13506. scalePath.moveTo(0, 20);
  13507. scalePath.lineTo(10, 20);
  13508. scalePath.moveTo(0, 30);
  13509. scalePath.lineTo(10, 30);
  13510. scalePath.moveTo(0, 40);
  13511. scalePath.lineTo(10, 40);
  13512. scalePath.moveTo(0, 50);
  13513. scalePath.lineTo(10, 50);
  13514. scalePath.moveTo(0, 60);
  13515. scalePath.lineTo(10, 60);
  13516. scalePath.moveTo(0, 70);
  13517. scalePath.lineTo(10, 70);
  13518. scalePath.moveTo(0, 80);
  13519. scalePath.lineTo(10, 80);
  13520. scalePath.moveTo(0, 90);
  13521. scalePath.lineTo(10, 90);
  13522. scalePath.moveTo(0, 100);
  13523. scalePath.lineTo(10, 100);
  13524. scaleLine.setPath(scalePath);
  13525. scaleLine.setPos(0, 16);
  13526. scene.addItem(&scaleLine);
  13527. setScene(&scene);
  13528. indicator.setPolygon(left);
  13529. indicator.setBrush(theBrush);
  13530. setMinimumSize(sizeHint());
  13531. setMaximumSize(sizeHint());
  13532. }
  13533. @ Once again, the size hint reduces the default size of the widget.
  13534. @<IntensityControl implementation@>=
  13535. QSize IntensityControl::sizeHint() const
  13536. {
  13537. return QSize(25, 160);
  13538. }
  13539. @ To support a more intuitive numerical representation, higher values should map
  13540. to higher positions on the scale. This is contrary to the coordinate system
  13541. provided by Qt, so the code setting the position of the indicator on the scale
  13542. must account for this.
  13543. During testing of this class, I found that it was impossible to select the
  13544. values 0 or 10 either through a click or with the increment or decrement
  13545. controls. Adding two additional execution branches corrects this issue.
  13546. @<IntensityControl implementation@>=
  13547. void IntensityControl::setValue(double val)
  13548. {
  13549. if(val >= 0 && val <= 10)
  13550. {
  13551. theValue = val;
  13552. if(!valueSet)
  13553. {
  13554. scene.addItem(&indicator);
  13555. }
  13556. valueSet = @[true@];
  13557. indicator.setPos(6, (100 - (val * 10)) + 16);
  13558. emit(valueChanged(val));
  13559. }
  13560. else if(val < 1)
  13561. {
  13562. setValue(0);
  13563. }
  13564. else
  13565. {
  13566. setValue(10);
  13567. }
  13568. }
  13569. double IntensityControl::value()
  13570. {
  13571. return theValue;
  13572. }
  13573. @ Mouse event handling is similar as well. The mouse press event simply notes
  13574. that the button has been pressed.
  13575. @<IntensityControl implementation@>=
  13576. void IntensityControl::mousePressEvent(QMouseEvent *event)
  13577. {
  13578. @<Check that the left button was pressed@>@;
  13579. scaleDown = @[true@];
  13580. event->accept();
  13581. }
  13582. @ Since there are fewer clickable areas there are fewer regions to check while
  13583. handling the mouse release event. Just as the |setValue()| method must
  13584. compensate for a mismatch between the scale and the underlying coordinate
  13585. system, so must click handling in the scale area take this into consideration
  13586. when determining which value the click intends.
  13587. @<IntensityControl implementation@>=
  13588. void IntensityControl::mouseReleaseEvent(QMouseEvent *event)
  13589. {
  13590. @<Check that the left button was pressed@>@;
  13591. if(!scaleDown)
  13592. {
  13593. event->ignore();
  13594. return;
  13595. }
  13596. scaleDown = @[false@];
  13597. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  13598. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 16)
  13599. {
  13600. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13601. {
  13602. if(valueSet)
  13603. {
  13604. setValue(theValue + 0.05);
  13605. }
  13606. event->accept();
  13607. return;
  13608. }
  13609. else if(sceneCoordinate.y() >= 122 && sceneCoordinate.y() <= 132)
  13610. {
  13611. if(valueSet)
  13612. {
  13613. setValue(theValue - 0.05);
  13614. }
  13615. event->accept();
  13616. return;
  13617. }
  13618. else if(sceneCoordinate.y() >= 16 && sceneCoordinate.y() <= 116)
  13619. {
  13620. setValue(10 - ((sceneCoordinate.y() - 16) / 10.0));
  13621. event->accept();
  13622. return;
  13623. }
  13624. }
  13625. }
  13626. @* Scripting the Scale Widgets.
  13627. \noindent Scale widgets can be added through the configuration system with
  13628. {\tt <hscale>} and {\tt <vscale>} elements. These can be added to layouts.
  13629. @<Function prototypes for scripting@>=
  13630. void addScaleControlToLayout(QDomElement element,
  13631. QStack<QWidget *> *widgetStack,
  13632. QStack<QLayout *> *layoutStack);
  13633. void addIntensityControlToLayout(QDomElement element,
  13634. QStack<QWidget *> *widgetStack,
  13635. QStack<QLayout *> *layoutStack);
  13636. @ Adding these widgets is done in the same way as adding other widgets.
  13637. @<Functions for scripting@>=
  13638. void addScaleControlToLayout(QDomElement element, QStack<QWidget *> *,
  13639. QStack<QLayout *> *layoutStack)
  13640. {
  13641. ScaleControl *scale = new ScaleControl;
  13642. if(element.hasAttribute("id"))
  13643. {
  13644. scale->setObjectName(element.attribute("id"));
  13645. }
  13646. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13647. layout->addWidget(scale);
  13648. }
  13649. void addIntensityControlToLayout(QDomElement element, QStack<QWidget *> *,
  13650. QStack<QLayout *> *layoutStack)
  13651. {
  13652. IntensityControl *scale = new IntensityControl;
  13653. if(element.hasAttribute("id"))
  13654. {
  13655. scale->setObjectName(element.attribute("id"));
  13656. }
  13657. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13658. layout->addWidget(scale);
  13659. }
  13660. @** Device Configuration.
  13661. \noindent Starting in \pn{} 1.4, all supported measurement hardware is
  13662. available from the same build and it is possible to use multiple devices from
  13663. differernt vendors at the same time. In previous versions, there were very few
  13664. available hardware configurations and a small number of example configuration
  13665. documents covered the needs of most people using the software. As more hardware
  13666. is supported and more people with distinct needs start using \pn{}, that
  13667. approach becomes unsustainable and the need for in-program configuration
  13668. becomes increasingly pronounced.
  13669. Device configuration is coupled to configuration of the logging window and
  13670. it is possible to configure multiple different roasters with different hardware
  13671. and other customizations of the logging window specific to a particular
  13672. machine.
  13673. The core of this is the use of an XML document saved with |QSettings| under
  13674. the |"DeviceConfiguration"| key. Within the root {\tt <DeviceConfiguration>}
  13675. element there are two grouping elements: {\tt <devices>} and
  13676. {\tt <references>}. The terminology was developed at a time when it was
  13677. thought that hardware configuration and logging view configuration would be
  13678. decoupled from each other, however the benefits of combining these far
  13679. outweighed the minor loss of flexibility with this approach.
  13680. Within the {\tt <devices>} tag there are arbitrarily many {\tt <node>} tags
  13681. which themselves may contain {\tt <node>} tags nested to any depth. Each of
  13682. these has two attributes, a {\tt name} attribute which specifies the display
  13683. text used to represent that node and a {\tt reference} attribute with a
  13684. unique value. Typica will generate a UUID for each node to use as the unique
  13685. value but this is not strictly required. The {\tt name} attribute does not
  13686. need to be unique and will generally be supplied by the person using the
  13687. software. The top level {\tt node} elements represent a coffee roaster and
  13688. the sub-elements can represent hardware, annotation controls, and possibly
  13689. other configurable features.
  13690. Within the {\tt <references>} tag there are as many {\tt <reference>} tags as
  13691. there are {\tt <node>} tags. Each of these has an {\tt id} attribute which
  13692. matches the {\tt reference} attribute in a {\tt <node>} tag and a {\tt driver}
  13693. attribute which is used to determine which class should be used to interact
  13694. with these settings. In the case of device configuration, this allows a
  13695. determination of which class should be used to generate an editor for settings
  13696. related to that node. Within each {\tt <reference>} tag is an arbitrary number
  13697. of {\tt <attribute>} tags with {\tt name} and {\tt value} attributes. Code for
  13698. providing the settings widgets and device interfaces can use these for any
  13699. desired purpose, but it is common to have one {\tt <attribute>} tag per setting
  13700. appropriate for a given node and possibly more to identify the concept a
  13701. particular node represents.
  13702. The global |Application| object is extended to maintain a |QDomDocument|
  13703. representation of this XML document.
  13704. @<Application private data members@>=
  13705. QDomDocument deviceConfigurationDocument;
  13706. @ Two methods are also provided for interacting with this document. The
  13707. |deviceConfiguration()| method returns a pointer to the private data member,
  13708. loading the XML from |QSettings| if required and creating a new document with
  13709. no {\tt <node>} tags if the document does not exist in settings. The
  13710. |saveDeviceConfiguration()| method serializes the |QDomDocument| to settings.
  13711. @<Device configuration members@>=
  13712. QDomDocument deviceConfiguration();
  13713. @ The method for saving should be a slot so a model representing this data
  13714. can persist changes through the signals and slots mechanism rather than
  13715. requiring the calls to be explicitn.
  13716. @<Extended Application slots@>=
  13717. void saveDeviceConfiguration();
  13718. @ Serializing the current configuration is trivial.
  13719. @<Application Implementation@>=
  13720. void Application::saveDeviceConfiguration()
  13721. {
  13722. QSettings settings;
  13723. settings.setValue("DeviceConfiguration",
  13724. QVariant(deviceConfigurationDocument.toByteArray()));
  13725. }
  13726. @ Producing a pointer to a loaded configuration only slightly more complicated.
  13727. If the configuration has been previously loaded we just return the pointer.
  13728. Otherwise, we attempt to load the document.
  13729. @<Application Implementation@>=
  13730. QDomDocument Application::deviceConfiguration()
  13731. {
  13732. if(deviceConfigurationDocument.isNull())
  13733. {
  13734. @<Load device configuration document from settings@>@;
  13735. }
  13736. return deviceConfigurationDocument;
  13737. }
  13738. @ In most cases a document will already exist in settings, but we must verify
  13739. this and create a new document if it does not exist. We also clear device
  13740. configuration settings if the configuration document is invalid.
  13741. @<Load device configuration document from settings@>=
  13742. QSettings settings;
  13743. QByteArray document = settings.value("DeviceConfiguration").toByteArray();
  13744. QString etext;
  13745. int eline;
  13746. int ecol;
  13747. if(document.length() == 0)
  13748. {
  13749. qDebug() << "Loaded settings length is 0. Creating new configuration.";
  13750. @<Create device configuration document@>@;
  13751. }
  13752. else
  13753. {
  13754. if(!deviceConfigurationDocument.setContent(document, false,
  13755. &etext, &eline, &ecol))
  13756. {
  13757. @<Report configuration loading error@>@;
  13758. @<Create device configuration document@>@;
  13759. }
  13760. }
  13761. @ Rather than generate the empty device configuration programmatically, we keep
  13762. an empty device configuration document as a resource.
  13763. @<Create device configuration document@>=
  13764. QFile emptyDocument(":/resources/xml/EmptyDeviceConfiguration.xml");
  13765. emptyDocument.open(QIODevice::ReadOnly);
  13766. if(!deviceConfigurationDocument.setContent(&emptyDocument, false,
  13767. &etext, &eline, &ecol))
  13768. {
  13769. @<Report configuration loading error@>@;
  13770. }
  13771. else
  13772. {
  13773. saveDeviceConfiguration();
  13774. }
  13775. @ There isn'@q'@>t really anything that can be done if the device configuration data
  13776. is corrupt, but an error message can be produced if the program happens to have
  13777. access to a debugging console.
  13778. @<Report configuration loading error@>=
  13779. qDebug() << QString(tr("An error occurred loading device configuration."));
  13780. qDebug() << QString(tr("Line %1, Column %2")).arg(eline).arg(ecol);
  13781. qDebug() << etext;
  13782. @* Model and view for device configuration hierarchy.
  13783. \noindent When manipulating device configuration data, it can be useful to
  13784. present the device hierarchy in a tree view. To do this, we use two classes to
  13785. produce a tree model. This is slightly extended and modified from an example
  13786. in the Qt documentation.\nfnote{Simple DOM Model Example:\par\indent\pdfURL{%
  13787. http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}
  13788. {http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}}
  13789. Our model uses the |DeviceTreeModelNode| class to cache the |QDomNode|
  13790. instances with the data we want.
  13791. @<Class declarations@>=
  13792. class DeviceTreeModelNode
  13793. {
  13794. public:
  13795. DeviceTreeModelNode(QDomNode &node, int row,
  13796. DeviceTreeModelNode *parent = NULL);
  13797. ~DeviceTreeModelNode();
  13798. DeviceTreeModelNode *child(int index);
  13799. DeviceTreeModelNode *parent();
  13800. QDomNode node() const;
  13801. int row();
  13802. private:
  13803. QDomNode domNode;
  13804. QHash<int, DeviceTreeModelNode*> children;
  13805. int rowNumber;
  13806. DeviceTreeModelNode *parentItem;
  13807. };
  13808. @ Implementation of this helper class is trivial.
  13809. @<DeviceTreeModelNode implementation@>=
  13810. DeviceTreeModelNode::DeviceTreeModelNode(QDomNode &node, int row,
  13811. DeviceTreeModelNode *parent)
  13812. : domNode(node), rowNumber(row), parentItem(parent)
  13813. {
  13814. /* Nothing needs to be done here. */
  13815. }
  13816. DeviceTreeModelNode::~DeviceTreeModelNode()
  13817. {
  13818. QHash<int, DeviceTreeModelNode *>::iterator@, i;
  13819. for(i = children.begin(); i != children.end(); i++)
  13820. {
  13821. delete i.value();
  13822. }
  13823. }
  13824. DeviceTreeModelNode *DeviceTreeModelNode::parent()
  13825. {
  13826. return parentItem;
  13827. }
  13828. int DeviceTreeModelNode::row()
  13829. {
  13830. return rowNumber;
  13831. }
  13832. QDomNode DeviceTreeModelNode::node() const
  13833. {
  13834. return domNode;
  13835. }
  13836. DeviceTreeModelNode *DeviceTreeModelNode::child(int index)
  13837. {
  13838. if(children.contains(index))
  13839. {
  13840. return children[index];
  13841. }
  13842. if(index >= 0 && index < domNode.childNodes().count())
  13843. {
  13844. QDomNode childNode = domNode.childNodes().item(index);
  13845. DeviceTreeModelNode *childItem = new DeviceTreeModelNode(childNode,
  13846. index, this);
  13847. children[index] = childItem;
  13848. return childItem;
  13849. }
  13850. return NULL;
  13851. }
  13852. @ The model class provides a single column representation of the {\tt devices}
  13853. section of the device configuration document. It provides methods for editing
  13854. the name of any node, for adding new nodes to the model, for deleting any node
  13855. in the model, and for obtaining the {\tt reference} element corresponding to
  13856. a given node.
  13857. @<Class declarations@>=
  13858. class DeviceTreeModel : public QAbstractItemModel@/
  13859. {@/
  13860. @[Q_OBJECT@]@;
  13861. public:@/
  13862. DeviceTreeModel(QObject *parent = NULL);
  13863. ~DeviceTreeModel();
  13864. QVariant data(const QModelIndex &index, int role) const;
  13865. Qt::ItemFlags flags(const QModelIndex &index) const;
  13866. QVariant headerData(int section, Qt::Orientation orientation,
  13867. int role = Qt::DisplayRole) const;
  13868. QModelIndex index(int row, int column,
  13869. const QModelIndex &parent = QModelIndex()) const;
  13870. QModelIndex parent(const QModelIndex &child) const;
  13871. Q_INVOKABLE int rowCount(const QModelIndex &parent = QModelIndex()) const;
  13872. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  13873. bool setData(const QModelIndex &index, const QVariant &value,
  13874. int role);
  13875. bool removeRows(int row, int count, const QModelIndex &parent);
  13876. QDomElement referenceElement(const QString &id);
  13877. @[public slots@]:@/
  13878. void newNode(const QString &name, const QString &driver,
  13879. const QModelIndex &parent);
  13880. private:@/
  13881. QDomDocument document;
  13882. DeviceTreeModelNode *root;
  13883. QDomNode referenceSection;
  13884. QDomNode treeRoot;
  13885. };
  13886. @ In the constructor we locate the {\tt devices} and {\tt references} sections
  13887. of the passed in document. Our tree of cached |QDomNode| elements starts with
  13888. the former and is expanded as needed.
  13889. @<DeviceTreeModel implementation@>=
  13890. DeviceTreeModel::DeviceTreeModel(QObject *parent)
  13891. : QAbstractItemModel(parent)
  13892. {
  13893. document = AppInstance->deviceConfiguration();
  13894. QDomNodeList elements = document.elementsByTagName("devices");
  13895. if(elements.size() != 1)
  13896. {
  13897. qDebug() << "Unexpected result when loading device map.";
  13898. }
  13899. treeRoot = elements.at(0);
  13900. root = new DeviceTreeModelNode(treeRoot, 0);
  13901. elements = document.elementsByTagName("references");
  13902. if(elements.size() != 1)
  13903. {
  13904. qDebug() << "No references section. Creating.";
  13905. referenceSection = document.createElement("references");
  13906. document.appendChild(referenceSection);
  13907. }
  13908. else
  13909. {
  13910. referenceSection = elements.at(0);
  13911. }
  13912. connect(this, SIGNAL(dataChanged(QModelIndex, QModelIndex)),
  13913. AppInstance, SLOT(saveDeviceConfiguration()));
  13914. connect(this, SIGNAL(modelReset()),
  13915. AppInstance, SLOT(saveDeviceConfiguration()));
  13916. connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)),
  13917. AppInstance, SLOT(saveDeviceConfiguration()));
  13918. }
  13919. @ We only provide a single column for our model, so |columnCount()| can simply
  13920. return a constant. The |rowCount()| method can return a variety of values
  13921. depending on the parent node.
  13922. @<DeviceTreeModel implementation@>=
  13923. int DeviceTreeModel::columnCount(const QModelIndex &) const
  13924. {
  13925. return 1;
  13926. }
  13927. int DeviceTreeModel::rowCount(const QModelIndex &parent) const
  13928. {
  13929. if(parent.column() > 0)
  13930. {
  13931. return 0;
  13932. }
  13933. @<Get parent item from index@>@;
  13934. return parentItem->node().childNodes().count();
  13935. }
  13936. @ If an invalid index is passed as the parent index, we assume the parent to
  13937. be the root element.
  13938. @<Get parent item from index@>=
  13939. DeviceTreeModelNode *parentItem;
  13940. if(!parent.isValid())
  13941. {
  13942. parentItem = root;
  13943. }
  13944. else
  13945. {
  13946. parentItem = static_cast<DeviceTreeModelNode *>(parent.internalPointer());
  13947. }
  13948. @ As seen in |rowCount()|, we keep a pointer to the cached node in our model
  13949. indices.
  13950. @<DeviceTreeModel implementation@>=
  13951. QModelIndex DeviceTreeModel::index(int row, int column,
  13952. const QModelIndex &parent) const
  13953. {
  13954. if(!hasIndex(row, column, parent))
  13955. {
  13956. return QModelIndex();
  13957. }
  13958. @<Get parent item from index@>@;
  13959. DeviceTreeModelNode *childItem = parentItem->child(row);
  13960. if(childItem)
  13961. {
  13962. return createIndex(row, column, childItem);
  13963. }
  13964. return QModelIndex();
  13965. }
  13966. @ We can also request an index for the parent of a given index.
  13967. @<DeviceTreeModel implementation@>=
  13968. QModelIndex DeviceTreeModel::parent(const QModelIndex &child) const
  13969. {
  13970. if(!child.isValid())
  13971. {
  13972. return QModelIndex();
  13973. }
  13974. DeviceTreeModelNode *childItem =
  13975. static_cast<DeviceTreeModelNode *>(child.internalPointer());
  13976. DeviceTreeModelNode *parentItem = childItem->parent();
  13977. if(!parentItem || parentItem == root)
  13978. {
  13979. return QModelIndex();
  13980. }
  13981. return createIndex(parentItem->row(), 0, parentItem);
  13982. }
  13983. @ All items should be enabled, selectable, and editable.
  13984. @<DeviceTreeModel implementation@>=
  13985. Qt::ItemFlags DeviceTreeModel::flags(const QModelIndex &index) const
  13986. {
  13987. if(!index.isValid())
  13988. {
  13989. return 0;
  13990. }
  13991. return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
  13992. }
  13993. @ Each node in the model maintains two pieces of information. One is the
  13994. display value for the node which is held in the {\tt name} attribute of the
  13995. corresponding XML element. The other is a reference ID held in the
  13996. {\tt reference} attribute.
  13997. @<DeviceTreeModel implementation@>=
  13998. QVariant DeviceTreeModel::data(const QModelIndex &index, int role) const
  13999. {
  14000. if(!index.isValid())
  14001. {
  14002. return QVariant();
  14003. }
  14004. if(role != Qt::DisplayRole && role != Qt::UserRole && role != Qt::EditRole)
  14005. {
  14006. return QVariant();
  14007. }
  14008. DeviceTreeModelNode *item =
  14009. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  14010. QDomNode node = item->node();
  14011. QDomElement element = node.toElement();
  14012. switch(role)
  14013. {
  14014. case Qt::DisplayRole:@/
  14015. case Qt::EditRole:@/
  14016. return QVariant(element.attribute("name"));
  14017. case Qt::UserRole:@/
  14018. return QVariant(element.attribute("reference"));
  14019. default:@/
  14020. return QVariant();
  14021. }
  14022. return QVariant();
  14023. }
  14024. @ The reference value is managed by the model and should never be changed. The
  14025. display value for a node is, however, editable. These changes must propagate
  14026. back to the XML document underlying the model.
  14027. @<DeviceTreeModel implementation@>=
  14028. bool DeviceTreeModel::setData(const QModelIndex &index,
  14029. const QVariant &value, int)@;@/
  14030. {@t\1@>@/
  14031. if(!index.isValid())@/
  14032. {@t\1@>@/
  14033. return false;@t\2@>@/
  14034. }@/
  14035. DeviceTreeModelNode *item =
  14036. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  14037. QDomNode node = item->node();
  14038. QDomElement element = node.toElement();
  14039. element.setAttribute("name", value.toString());
  14040. emit dataChanged(index, index);@;
  14041. return true;@t\2@>@/
  14042. }
  14043. @ A custom method is provided for adding new nodes to the model. This generates
  14044. the two XML elements needed for the node. The |name| parameter is the display
  14045. name of the new node, the |driver| parameter is used as the value for the
  14046. {\tt driver} attribute in the {\tt reference} element which will be used to
  14047. determine what classes are used to work with that data.
  14048. @<DeviceTreeModel implementation@>=
  14049. void DeviceTreeModel::newNode(const QString &name, const QString &driver,
  14050. const QModelIndex &parent)
  14051. {
  14052. QString referenceID = QUuid::createUuid().toString();
  14053. @<Get parent item from index@>@;
  14054. QDomNode parentNode = parentItem->node();
  14055. int newRowNumber = rowCount(parent);
  14056. beginInsertRows(parent, newRowNumber, newRowNumber);
  14057. QDomElement deviceElement = document.createElement("node");
  14058. deviceElement.setAttribute("name", name);
  14059. deviceElement.setAttribute("reference", referenceID);
  14060. parentNode.appendChild(deviceElement);
  14061. QDomElement referenceElement = document.createElement("reference");
  14062. referenceElement.setAttribute("id", referenceID);
  14063. referenceElement.setAttribute("driver", driver);
  14064. referenceSection.appendChild(referenceElement);
  14065. endInsertRows();
  14066. }
  14067. @ We can also delete nodes. When deleting a node, both XML elements are
  14068. removed and our node cache is invalidated.
  14069. @<DeviceTreeModel implementation@>=
  14070. bool DeviceTreeModel::removeRows(int row, int count, const QModelIndex &parent)@t\2\2@>@/
  14071. {@t\1@>@/
  14072. @<Get parent item from index@>@;
  14073. QDomNode parentNode = parentItem->node();
  14074. QDomNodeList childNodes = parentNode.childNodes();@;
  14075. if(childNodes.size() < row + count)@/
  14076. {@t\1@>@/
  14077. return false;@t\2@>@/
  14078. }@/
  14079. beginRemoveRows(parent, row, row + count - 1);
  14080. QList<QDomElement> removalList;
  14081. for(int i = row; i < row + count; i++)
  14082. {
  14083. removalList.append(childNodes.at(i).toElement());
  14084. }
  14085. QDomElement element;
  14086. QDomElement reference;
  14087. for(int i = 0; i < count; i++)
  14088. {
  14089. element = removalList.at(i);
  14090. if(element.hasAttribute("reference"))
  14091. {
  14092. reference = referenceElement(element.attribute("reference"));
  14093. if(!reference.isNull())
  14094. {
  14095. referenceSection.removeChild(reference);
  14096. }
  14097. }
  14098. parentNode.removeChild(element);
  14099. }
  14100. endRemoveRows();
  14101. beginResetModel();
  14102. delete root;
  14103. root = new DeviceTreeModelNode(treeRoot, 0);
  14104. endResetModel();@;
  14105. return true;@t\2@>@/
  14106. }
  14107. @ Another custom method obtains the {\tt reference} element for a given
  14108. reference ID.
  14109. @<DeviceTreeModel implementation@>=
  14110. QDomElement DeviceTreeModel::referenceElement(const QString &id)
  14111. {
  14112. QDomNodeList childNodes = referenceSection.childNodes();
  14113. QDomElement element;
  14114. for(int i = 0; i < childNodes.size(); i++)
  14115. {
  14116. element = childNodes.at(i).toElement();
  14117. if(element.hasAttribute("id"))
  14118. {
  14119. if(element.attribute("id") == id)
  14120. {
  14121. return element;
  14122. }
  14123. }
  14124. }
  14125. return QDomElement();
  14126. }
  14127. @ We don'@q'@>t want any headers, so |headerData()| is very simple.
  14128. @<DeviceTreeModel implementation@>=
  14129. QVariant DeviceTreeModel::headerData(int, Qt::Orientation, int) const
  14130. {
  14131. return QVariant();
  14132. }
  14133. @ The destructor destroys the node cache. The destructor for the top level node
  14134. will recursively destroy all child nodes.
  14135. @<DeviceTreeModel implementation@>=
  14136. DeviceTreeModel::~DeviceTreeModel()
  14137. {
  14138. delete root;
  14139. }
  14140. @ Exposing this class to the host environment allows a number of interesting
  14141. possibilities. Setting the model to a combo box, for example, allows the
  14142. selection of top level nodes representing a particular coffee roaster. It is
  14143. also useful to have the ability to traverse a specified sub-tree of the model
  14144. to set up a logging view that matches the configuration for such a selected
  14145. roaster.
  14146. @<Function prototypes for scripting@>=
  14147. QScriptValue constructDeviceTreeModel(QScriptContext *context,
  14148. QScriptEngine *engine);
  14149. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine);
  14150. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine);
  14151. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  14152. QScriptEngine *engine);
  14153. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine);
  14154. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine);
  14155. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context, QScriptEngine *engine);
  14156. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context, QScriptEngine *engine);
  14157. @ The constructor is trivial.
  14158. @<Functions for scripting@>=
  14159. QScriptValue constructDeviceTreeModel(QScriptContext *, QScriptEngine *engine)
  14160. {
  14161. QScriptValue object = engine->newQObject(new DeviceTreeModel);
  14162. setDeviceTreeModelProperties(object, engine);
  14163. return object;
  14164. }
  14165. @ As usual the host environment is informed of this constructor.
  14166. @<Set up the scripting engine@>=
  14167. constructor = engine->newFunction(constructDeviceTreeModel);
  14168. value = engine->newQMetaObject(&DeviceTreeModel::staticMetaObject,
  14169. constructor);
  14170. engine->globalObject().setProperty("DeviceTreeModel", value);
  14171. @ A number of properties are set to allow script code to traverse the model.
  14172. Most of these properties are properly members of |QAbstractItemModel| and
  14173. the code is written to allow any models that may be exposed to the host
  14174. environment in the future to make use of these as well. Note that this is not
  14175. a full set of functionality but only what I needed to implement a particular
  14176. feature set.
  14177. @<Functions for scripting@>=
  14178. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine)
  14179. {
  14180. setQAbstractItemModelProperties(value, engine);
  14181. value.setProperty("referenceElement",
  14182. engine->newFunction(DeviceTreeModel_referenceElement));
  14183. }
  14184. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine)
  14185. {
  14186. setQObjectProperties(value, engine);
  14187. value.setProperty("data", engine->newFunction(QAbstractItemModel_data));
  14188. value.setProperty("index", engine->newFunction(QAbstractItemModel_index));
  14189. value.setProperty("rowCount", engine->newFunction(QAbstractItemModel_rowCount));
  14190. value.setProperty("hasChildren", engine->newFunction(QAbstractItemModel_hasChildren));
  14191. }
  14192. @ The wrapped call to |referenceElement| does a little more than might be
  14193. expected. Rather than returning a |QDomElement| and leaving it up to script
  14194. code to traverse the sub-tree, we create a |QVariantMap| which in script code
  14195. is translated as an object with the keys as properties of the object containing
  14196. the values of those keys. This is populated by first specifying a {\tt driver}
  14197. key with its value from the {\tt driver} attribute of the {\tt reference} node.
  14198. We then examine the {\tt <attribute>} sub-elements and use the {\tt name}
  14199. attribute as keys and the {\tt value} attribute as values to fill out the rest
  14200. of the map.
  14201. @<Functions for scripting@>=
  14202. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  14203. QScriptEngine *engine)
  14204. {
  14205. DeviceTreeModel *model = getself<DeviceTreeModel *>(context);
  14206. QDomElement referenceElement = model->referenceElement(argument<QString>(0, context));
  14207. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14208. QDomElement node;
  14209. QVariantMap retval;
  14210. retval.insert("driver", referenceElement.attribute("driver"));
  14211. for(int i = 0; i < configData.size(); i++)
  14212. {
  14213. node = configData.at(i).toElement();
  14214. retval.insert(node.attribute("name"), node.attribute("value"));
  14215. }
  14216. return engine->toScriptValue(retval);
  14217. }
  14218. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine)
  14219. {
  14220. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14221. QModelIndex index = argument<QModelIndex>(0, context);
  14222. int role = argument<int>(1, context);
  14223. return engine->toScriptValue(model->data(index, role));
  14224. }
  14225. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine)
  14226. {
  14227. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14228. int row = 0;
  14229. int column = 0;
  14230. QModelIndex index;
  14231. if(context->argumentCount() > 1)
  14232. {
  14233. row = argument<int>(0, context);
  14234. column = argument<int>(1, context);
  14235. }
  14236. if(context->argumentCount() > 2)
  14237. {
  14238. index = argument<QModelIndex>(2, context);
  14239. }
  14240. QModelIndex retval = model->index(row, column, index);
  14241. return engine->toScriptValue(retval);
  14242. }
  14243. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context,
  14244. QScriptEngine *)
  14245. {
  14246. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14247. QModelIndex index;
  14248. if(context->argumentCount() == 1)
  14249. {
  14250. index = argument<QModelIndex>(0, context);
  14251. }
  14252. return QScriptValue(model->rowCount(index));
  14253. }
  14254. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context,
  14255. QScriptEngine *engine)
  14256. {
  14257. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14258. QModelIndex index;
  14259. if(context->argumentCount() == 1)
  14260. {
  14261. index = argument<QModelIndex>(0, context);
  14262. }
  14263. return QScriptValue(engine, model->hasChildren(index));
  14264. }
  14265. @ Some additional work is needed to handle |QModelIndex| appropriately. First
  14266. we declare that as a metatype.
  14267. @<Class declarations@>=
  14268. Q_DECLARE_METATYPE(QModelIndex)
  14269. @ Next we need a pair of functions to convert |QModelIndex| to and from script
  14270. values.
  14271. @<Function prototypes for scripting@>=
  14272. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index);
  14273. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index);
  14274. @ These are implemented thusly.
  14275. @<Functions for scripting@>=
  14276. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index)
  14277. {
  14278. QVariant var;
  14279. var.setValue(index);
  14280. QScriptValue object = engine->newVariant(var);
  14281. return object;
  14282. }
  14283. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index)
  14284. {
  14285. index = value.toVariant().value<QModelIndex>();
  14286. }
  14287. @ Finally we register this with the engine.
  14288. @<Set up the scripting engine@>=
  14289. qScriptRegisterMetaType(engine, QModelIndex_toScriptValue, QModelIndex_fromScriptValue);
  14290. @* Device Configuration Widgets.
  14291. \noindent Each node in the {\tt devices} section of the |DeviceTreeModel| is
  14292. associated with a {\tt reference} element that provides a driver string which
  14293. can be used to identify the classes used to interact with the device
  14294. configuration data. An example of this is selecting which widget to use when
  14295. selecting a node in a configuration window. These widgets must be registered
  14296. to the appropriate driver string in advance. This is currently handled through
  14297. the |Application| instance, though it would probably be better to split this
  14298. into its own class at some point in the future.
  14299. @<Application private data members@>=
  14300. QHash<QString, QMetaObject> deviceConfigurationWidgets;
  14301. @ Two methods register widgets and retrieve an instance of the appropriate
  14302. widget for a given node in the device configuration model.
  14303. @<Device configuration members@>=
  14304. void registerDeviceConfigurationWidget(QString driver, QMetaObject widget);
  14305. QWidget* deviceConfigurationWidget(DeviceTreeModel *model,
  14306. const QModelIndex &index);
  14307. @ Registration is a simple wrapper around the underlying |QHash|.
  14308. @<Application Implementation@>=
  14309. void Application::registerDeviceConfigurationWidget(QString driver,
  14310. QMetaObject widget)
  14311. {
  14312. deviceConfigurationWidgets.insert(driver, widget);
  14313. }
  14314. @ Obtaining the configuration widget for a given node involves looking up the
  14315. reference element, extracting the driver string, looking up the associated
  14316. meta-object, and returning a new instance of that object.
  14317. As there is no concept of an invalid |QMetaObject| we default to the static
  14318. meta-object for a |QWidget| if a widget for the specified driver string is not
  14319. registered and check for this prior to creating a new instance of the
  14320. configuration widget.
  14321. @<Application Implementation@>=
  14322. QWidget* Application::deviceConfigurationWidget(DeviceTreeModel *model,
  14323. const QModelIndex &index)
  14324. {
  14325. QVariant nodeReference = index.data(Qt::UserRole);
  14326. QDomElement referenceElement = model->referenceElement(
  14327. model->data(index, Qt::UserRole).toString());
  14328. QMetaObject metaObject =
  14329. deviceConfigurationWidgets.value(referenceElement.attribute("driver"),
  14330. QWidget::staticMetaObject);
  14331. QWidget *editor;
  14332. if(metaObject.className() == QWidget::staticMetaObject.className())
  14333. {
  14334. editor = NULL;
  14335. }
  14336. else
  14337. {
  14338. editor = qobject_cast<QWidget *>(
  14339. metaObject.newInstance(Q_ARG(DeviceTreeModel *, model),
  14340. Q_ARG(QModelIndex, index)));
  14341. }
  14342. return editor;
  14343. }
  14344. @ Every node type should have an associated editor and the editors for nodes
  14345. which can have child nodes should be able to handle creating these child nodes.
  14346. This leaves the problem of creating the top level nodes. For this we must have
  14347. a way to register three key pieces of information: the text which should appear
  14348. for selecting a new top level node to add to the configuration, the default
  14349. name for a node of that type, and the registered driver string associated with
  14350. that node type. The most likely use for this information is in constructing a
  14351. menu. |QAction| seems like a good fit, but this cannot pass all of the
  14352. required information. Part of the chosen solution is a |QAction| subclass
  14353. which takes all three pieces of information and provides a new signal to
  14354. supply the information needed to add a new top level node.
  14355. @<Class declarations@>=
  14356. class NodeInserter : public QAction@/
  14357. {@/
  14358. @[Q_OBJECT@]@;
  14359. public:@/
  14360. NodeInserter(const QString &title, const QString &name,
  14361. const QString &driver, QObject *parent = NULL);
  14362. signals:@/
  14363. void triggered(QString name, QString driver);
  14364. @[private slots@]:@/
  14365. void onTriggered();
  14366. private:@/
  14367. QString defaultNodeName;
  14368. QString driverString;
  14369. };
  14370. @ The constructor saves the information that will later be emitted and connects
  14371. the |triggered()| signal from |QAction| to a private slot which emits our new
  14372. |triggered()| signal.
  14373. @<NodeInserter implementation@>=
  14374. NodeInserter::NodeInserter(const QString &title, const QString &name,
  14375. const QString &driver, QObject *parent) :
  14376. QAction(title, parent), defaultNodeName(name), driverString(driver)
  14377. {
  14378. connect(this, SIGNAL(triggered()), this, SLOT(onTriggered()));
  14379. }
  14380. void NodeInserter::onTriggered()
  14381. {
  14382. emit triggered(defaultNodeName, driverString);
  14383. }
  14384. @ An interface for adding top level nodes to the device configuration needs to
  14385. be able to access a list of these actions so we make this available through the
  14386. |Application| instance. Once again, it would be better to split device
  14387. configuration registration data to a separate class and there should be
  14388. accessors around this.
  14389. Note that this terminology was introduced when it was assumed that device
  14390. configuration and logging view configuration would be separate. It is likely
  14391. that a future code cleanup will remove this in favor of handling the top level
  14392. of the device configuration hierarchy (under roaster specification) in the same
  14393. way that sub-nodes are handled.
  14394. @<Device configuration members@>=
  14395. QList<NodeInserter *> topLevelNodeInserters;
  14396. @ With this done, we can now produce a window which allows someone to easily
  14397. edit the device configuration.
  14398. As of version 1.6 this class is no longer a window but just a |QWidget| which
  14399. is inserted into another more general settings window. The name of the class
  14400. should be changed in a future version to reflect this change.
  14401. @<Class declarations@>=
  14402. class DeviceConfigurationWindow : public QWidget
  14403. {
  14404. @[Q_OBJECT@]@;
  14405. public:@/
  14406. DeviceConfigurationWindow();
  14407. @[public slots@]:@/
  14408. void addDevice();
  14409. void removeNode();
  14410. void newSelection(const QModelIndex &index);
  14411. @[private slots@]:@/
  14412. void resizeColumn();
  14413. private:@/
  14414. QDomDocument document;
  14415. DeviceTreeModel *model;
  14416. QTreeView *view;
  14417. QScrollArea *configArea;
  14418. };
  14419. @ This window consists of two main panels separated by a splitter. The left
  14420. panel presents a tree view of the current device configuration and a set of
  14421. controls that allows someone to either add a new top level node to the
  14422. configuration or delete any node in the configuration along with all of its
  14423. child nodes.
  14424. The right panel provides a |QScrollArea|. When a node is selected from the tree
  14425. view, the appropriate configuration widget will be inserted into that area.
  14426. When a configuration widget adds a new node to the device model, the parent
  14427. node (which should be the currently selected node but the code does not assume
  14428. this) is expanded to show the new child node if it has not already been
  14429. expanded.
  14430. @<DeviceConfigurationWindow implementation@>=
  14431. DeviceConfigurationWindow::DeviceConfigurationWindow() : QWidget(NULL),
  14432. view(new QTreeView), configArea(new QScrollArea)
  14433. {
  14434. QSplitter *splitter = new QSplitter;
  14435. QWidget *leftWidget = new QWidget;
  14436. leftWidget->setMinimumWidth(200);
  14437. QVBoxLayout *left = new QVBoxLayout;
  14438. view->setAnimated(true);
  14439. view->setSelectionMode(QAbstractItemView::SingleSelection);
  14440. document = AppInstance->deviceConfiguration();
  14441. model = new DeviceTreeModel;
  14442. view->setModel(model);
  14443. view->setTextElideMode(Qt::ElideNone);
  14444. view->expandAll();
  14445. view->resizeColumnToContents(0);
  14446. connect(model, SIGNAL(modelReset()), view, SLOT(expandAll()));
  14447. QHBoxLayout *treeButtons = new QHBoxLayout;
  14448. QToolButton *addDeviceButton = new QToolButton;
  14449. addDeviceButton->setIcon(QIcon::fromTheme("list-add"));
  14450. addDeviceButton->setToolTip(tr("New Roaster"));
  14451. connect(addDeviceButton, SIGNAL(clicked()),
  14452. this, SLOT(addDevice()));
  14453. QToolButton *removeNodeButton = new QToolButton;
  14454. removeNodeButton->setIcon(QIcon::fromTheme("list-remove"));
  14455. removeNodeButton->setToolTip(tr("Delete Selection"));
  14456. connect(removeNodeButton, SIGNAL(clicked()), this, SLOT(removeNode()));
  14457. treeButtons->addWidget(addDeviceButton);
  14458. treeButtons->addWidget(removeNodeButton);
  14459. left->addWidget(view);
  14460. left->addLayout(treeButtons);
  14461. leftWidget->setLayout(left);
  14462. splitter->addWidget(leftWidget);
  14463. configArea->setMinimumWidth(580);
  14464. configArea->setMinimumHeight(460);
  14465. configArea->setWidgetResizable(true);
  14466. splitter->addWidget(configArea);
  14467. QVBoxLayout *centralLayout = new QVBoxLayout;
  14468. centralLayout->addWidget(splitter);
  14469. setLayout(centralLayout);
  14470. connect(view, SIGNAL(activated(QModelIndex)),
  14471. this, SLOT(newSelection(QModelIndex)));
  14472. connect(view, SIGNAL(clicked(QModelIndex)),
  14473. this, SLOT(newSelection(QModelIndex)));
  14474. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  14475. view, SLOT(expand(QModelIndex)));
  14476. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  14477. this, SLOT(resizeColumn()));
  14478. connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
  14479. this, SLOT(resizeColumn()));
  14480. }
  14481. @ Adding a new top level node to the model is just a matter of extracting the
  14482. required information from the signal requesting that addition.
  14483. @<DeviceConfigurationWindow implementation@>=
  14484. void DeviceConfigurationWindow::addDevice()
  14485. {
  14486. model->newNode(tr("New Roaster"), "roaster", QModelIndex());
  14487. }
  14488. @ Removing the currently selected node is also simple.
  14489. @<DeviceConfigurationWindow implementation@>=
  14490. void DeviceConfigurationWindow::removeNode()
  14491. {
  14492. QModelIndex index = view->currentIndex();
  14493. if(index.isValid())
  14494. {
  14495. int row = index.row();
  14496. QModelIndex parent = index.parent();
  14497. model->removeRow(row, parent);
  14498. }
  14499. }
  14500. @ Due to most of the required logic being implemented in
  14501. |Application::deviceConfigurationWidget()|, inserting the proper editor in the
  14502. right area is also trivial.
  14503. @<DeviceConfigurationWindow implementation@>=
  14504. void DeviceConfigurationWindow::newSelection(const QModelIndex &index)
  14505. {
  14506. QWidget *editor = AppInstance->deviceConfigurationWidget(model, index);
  14507. if(editor)
  14508. {
  14509. configArea->setWidget(editor);
  14510. editor->show();
  14511. }
  14512. }
  14513. @ As nodes are added deeper in the device hierarchy or as nodes obtain longer
  14514. names, the nodes names may be elided by default rather than indicate that the
  14515. view can be scrolled horizontally. There has been feedback that this behavior
  14516. is not preferred so instead as the model data changes we expand the column
  14517. instead.
  14518. @<DeviceConfigurationWindow implementation@>=
  14519. void DeviceConfigurationWindow::resizeColumn()
  14520. {
  14521. view->resizeColumnToContents(0);
  14522. }
  14523. @ At least for the initial testing of this feature it will be useful if we can
  14524. instantiate this from the host environment. For this we at least require a
  14525. constructor.
  14526. Now that this widget is available through a more general settings window it may
  14527. be better to remove direct access to this class from the host environment.
  14528. @<Function prototypes for scripting@>=
  14529. QScriptValue constructDeviceConfigurationWindow(QScriptContext *context,
  14530. QScriptEngine *engine);
  14531. @ The constructor is trivial.
  14532. @<Functions for scripting@>=
  14533. QScriptValue constructDeviceConfigurationWindow(QScriptContext *,
  14534. QScriptEngine *engine)
  14535. {
  14536. QScriptValue object = engine->newQObject(new DeviceConfigurationWindow);
  14537. return object;
  14538. }
  14539. @ Finally we inform the host environment of this constructor.
  14540. @<Set up the scripting engine@>=
  14541. constructor = engine->newFunction(constructDeviceConfigurationWindow);
  14542. value = engine->newQMetaObject(&DeviceConfigurationWindow::staticMetaObject,
  14543. constructor);
  14544. engine->globalObject().setProperty("DeviceConfigurationWindow", value);
  14545. @* A Base Class for Device Configuration Widgets.
  14546. \noindent There are certain operations that are very commonly required
  14547. among device configuration widgets. These common elements have been implemented
  14548. in a base class.
  14549. @<Class declarations@>=
  14550. class BasicDeviceConfigurationWidget : public QWidget
  14551. {
  14552. @[Q_OBJECT@]@;
  14553. public:@/
  14554. BasicDeviceConfigurationWidget(DeviceTreeModel *model,
  14555. const QModelIndex &index);
  14556. @[public slots@]:@/
  14557. void insertChildNode(const QString &name, const QString &driver);
  14558. void updateAttribute(const QString &name, const QString &value);
  14559. protected:@/
  14560. DeviceTreeModel *deviceModel;
  14561. QModelIndex currentNode;
  14562. };
  14563. @ The constructor just passes its arguments to a pair of protected data
  14564. members. These are commonly required in subclasses but need not be exposed
  14565. outside of this branch of the object hierarchy.
  14566. @<BasicDeviceConfigurationWidget implementation@>=
  14567. BasicDeviceConfigurationWidget::BasicDeviceConfigurationWidget(
  14568. DeviceTreeModel *model, const QModelIndex &index)
  14569. : QWidget(NULL), deviceModel(model), currentNode(index)
  14570. {
  14571. /* Nothing needs to be done here. */
  14572. }
  14573. @ The |updateAttribute()| method sets the value property of an attribute
  14574. element of a given name that is a child of the current node, creating the
  14575. element if it does not exist.
  14576. @<BasicDeviceConfigurationWidget implementation@>=
  14577. void BasicDeviceConfigurationWidget::updateAttribute(const QString &name,
  14578. const QString &value)
  14579. {
  14580. QDomElement referenceElement = deviceModel->referenceElement(
  14581. deviceModel->data(currentNode, Qt::UserRole).toString());
  14582. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14583. QDomElement node;
  14584. bool found = @[false@];
  14585. for(int i = 0; i < configData.size(); i++)
  14586. {
  14587. node = configData.at(i).toElement();
  14588. if(node.attribute("name") == name)
  14589. {
  14590. node.setAttribute("value", value);
  14591. found = @[true@];
  14592. break;
  14593. }
  14594. }
  14595. if(!found)
  14596. {
  14597. node = AppInstance->deviceConfiguration().createElement("attribute");
  14598. node.setAttribute("name", name);
  14599. node.setAttribute("value", value);
  14600. referenceElement.appendChild(node);
  14601. }
  14602. AppInstance->saveDeviceConfiguration();
  14603. }
  14604. @ The |insertChildNode()| method constructs a new node with the specified name
  14605. and driver as a child of the current node. Node insertion is a generic
  14606. operation that does not require any knowledge of the configuration options that
  14607. will be presented in that node.
  14608. @<BasicDeviceConfigurationWidget implementation@>=
  14609. void BasicDeviceConfigurationWidget::insertChildNode(const QString &name,
  14610. const QString &driver)
  14611. {
  14612. deviceModel->newNode(name, driver, currentNode);
  14613. }
  14614. @** Configuration of Top Level Roaster Nodes.
  14615. \noindent The first configuration widget required is one for defining a coffee
  14616. roaster. This stores the identification number that will be used for machine
  14617. references in the database and also provides controls for adding all of the
  14618. required child nodes for hardware and configurable elements of the logging
  14619. window that may vary from one machine to the next.
  14620. All of the configuration widgets follow a similar pattern. One important detail
  14621. to note is that these configuration widgets are instantiated through Qt'@q'@>s
  14622. meta-object system. All of these constructors take a |DeviceTreeModel *| and a
  14623. |QModelIndex &| as arguments and they are marked as |Q_INVOKABLE|.
  14624. @<Class declarations@>=
  14625. class RoasterConfWidget : public BasicDeviceConfigurationWidget
  14626. {
  14627. @[Q_OBJECT@]@;
  14628. public:@/
  14629. @[Q_INVOKABLE@]@, RoasterConfWidget(DeviceTreeModel *model,
  14630. const QModelIndex &index);
  14631. @[private slots@]:@/
  14632. void updateRoasterId(int id);
  14633. void updateCapacityCheck(int value);
  14634. void updateCapacity(const QString &value);
  14635. void updateCapacityUnit(const QString &value);
  14636. };
  14637. @ Aside from the ID number used to identify the roaster in the database we also
  14638. need controls to add child nodes. In order to limit the number of options in
  14639. menus for adding child nodes, these are organized into groups that are
  14640. available through different controls.
  14641. @<RoasterConfWidget implementation@>=
  14642. RoasterConfWidget::RoasterConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14643. : BasicDeviceConfigurationWidget(model, index)
  14644. {
  14645. QVBoxLayout *layout = new QVBoxLayout;
  14646. QPushButton *addDeviceButton = new QPushButton(tr("Add Device"));
  14647. QMenu *deviceMenu = new QMenu;
  14648. NodeInserter *insertAction;
  14649. foreach(insertAction, AppInstance->topLevelNodeInserters)
  14650. {
  14651. connect(insertAction, SIGNAL(triggered(QString, QString)),
  14652. this, SLOT(insertChildNode(QString, QString)));
  14653. deviceMenu->addAction(insertAction);
  14654. }
  14655. addDeviceButton->setMenu(deviceMenu);
  14656. layout->addWidget(addDeviceButton);
  14657. QPushButton *addAnnotationControlButton = new QPushButton(tr("Add Annotation Control"));
  14658. QMenu *annotationMenu = new QMenu;
  14659. NodeInserter *basicButtonInserter = new NodeInserter(tr("Annotation Button"), tr("Annotation Button"), "annotationbutton");
  14660. NodeInserter *countingButtonInserter = new NodeInserter(tr("Counting Button"), tr("Counting Button"), "reconfigurablebutton");
  14661. NodeInserter *spinBoxInserter = new NodeInserter(tr("Numeric Entry"), tr("Numeric Entry"), "annotationspinbox");
  14662. NodeInserter *freeAnnotationInserter = new NodeInserter(tr("Free Text"),
  14663. tr("Free Text"),
  14664. "freeannotation");
  14665. annotationMenu->addAction(basicButtonInserter);
  14666. annotationMenu->addAction(countingButtonInserter);
  14667. annotationMenu->addAction(spinBoxInserter);
  14668. annotationMenu->addAction(freeAnnotationInserter);
  14669. connect(basicButtonInserter, SIGNAL(triggered(QString, QString)),
  14670. this, SLOT(insertChildNode(QString, QString)));
  14671. connect(countingButtonInserter, SIGNAL(triggered(QString, QString)),
  14672. this, SLOT(insertChildNode(QString, QString)));
  14673. connect(spinBoxInserter, SIGNAL(triggered(QString, QString)),
  14674. this, SLOT(insertChildNode(QString, QString)));
  14675. connect(freeAnnotationInserter, SIGNAL(triggered(QString, QString)),
  14676. this, SLOT(insertChildNode(QString, QString)));
  14677. @<Add annotation control node inserters@>@;
  14678. addAnnotationControlButton->setMenu(annotationMenu);
  14679. layout->addWidget(addAnnotationControlButton);
  14680. QPushButton *timersButton = new QPushButton(tr("Extra Timers"));
  14681. QMenu *timersMenu = new QMenu;
  14682. NodeInserter *coolingTimerInserter = new NodeInserter(tr("Cooling Timer"), tr("Cooling Timer"), "coolingtimer");
  14683. NodeInserter *rangeTimerInserter = new NodeInserter(tr("Range Timer"), tr("Range Timer"), "rangetimer");
  14684. NodeInserter *multirangeTimerInserter = new NodeInserter(tr("Multi-Range Timer"), tr("Multi-Range Timer"), "multirangetimer");
  14685. timersMenu->addAction(coolingTimerInserter);
  14686. timersMenu->addAction(rangeTimerInserter);
  14687. timersMenu->addAction(multirangeTimerInserter);
  14688. connect(coolingTimerInserter, SIGNAL(triggered(QString, QString)),
  14689. this, SLOT(insertChildNode(QString, QString)));
  14690. connect(rangeTimerInserter, SIGNAL(triggered(QString, QString)),
  14691. this, SLOT(insertChildNode(QString, QString)));
  14692. connect(multirangeTimerInserter, SIGNAL(triggered(QString, QString)),
  14693. this, SLOT(insertChildNode(QString, QString)));
  14694. timersButton->setMenu(timersMenu);
  14695. layout->addWidget(timersButton);
  14696. QPushButton *advancedButton = new QPushButton(tr("Advanced Features"));
  14697. QMenu *advancedMenu = new QMenu;
  14698. NodeInserter *linearsplineinserter = new NodeInserter(tr("Linear Spline Interpolated Series"), tr("Linear Spline Interpolated Series"), "linearspline");
  14699. advancedMenu->addAction(linearsplineinserter);
  14700. NodeInserter *translationinserter = new NodeInserter(tr("Profile Translation"), tr("Profile Translation"), "translation");
  14701. advancedMenu->addAction(translationinserter);
  14702. connect(linearsplineinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  14703. connect(translationinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  14704. @<Add node inserters to advanced features menu@>@;
  14705. advancedButton->setMenu(advancedMenu);
  14706. layout->addWidget(advancedButton);
  14707. QHBoxLayout *idLayout = new QHBoxLayout;
  14708. QLabel *idLabel = new QLabel(tr("Machine ID for database:"));
  14709. idLayout->addWidget(idLabel);
  14710. QSpinBox *id = new QSpinBox;
  14711. idLayout->addWidget(id);
  14712. idLayout->addStretch();
  14713. layout->addLayout(idLayout);
  14714. QHBoxLayout *capacityLayout = new QHBoxLayout;
  14715. QCheckBox *capacityCheckEnabled = new QCheckBox(tr("Maximum batch size:"));
  14716. QDoubleSpinBox *capacity = new QDoubleSpinBox;
  14717. capacity->setMinimum(0.0);
  14718. capacity->setDecimals(3);
  14719. capacity->setMaximum(999999.999);
  14720. QComboBox *capacityUnit = new QComboBox;
  14721. capacityUnit->addItem("g");
  14722. capacityUnit->addItem("Kg");
  14723. capacityUnit->addItem("oz");
  14724. capacityUnit->addItem("Lb");
  14725. capacityUnit->setCurrentIndex(3);
  14726. capacityLayout->addWidget(capacityCheckEnabled);
  14727. capacityLayout->addWidget(capacity);
  14728. capacityLayout->addWidget(capacityUnit);
  14729. capacityLayout->addStretch();
  14730. layout->addLayout(capacityLayout);
  14731. layout->addStretch();
  14732. @<Get device configuration data for current node@>@;
  14733. for(int i = 0; i < configData.size(); i++)
  14734. {
  14735. node = configData.at(i).toElement();
  14736. if(node.attribute("name") == "databaseid")
  14737. {
  14738. id->setValue(node.attribute("value").toInt());
  14739. }
  14740. else if(node.attribute("name") == "checkcapacity")
  14741. {
  14742. capacityCheckEnabled->setChecked(node.attribute("value") == "true");
  14743. }
  14744. else if(node.attribute("name") == "capacity")
  14745. {
  14746. capacity->setValue(node.attribute("value").toDouble());
  14747. }
  14748. else if(node.attribute("name") == "capacityunit")
  14749. {
  14750. capacityUnit->setCurrentIndex(capacityUnit->findText(node.attribute("value")));
  14751. }
  14752. }
  14753. updateRoasterId(id->value());
  14754. connect(id, SIGNAL(valueChanged(int)), this, SLOT(updateRoasterId(int)));
  14755. connect(capacityCheckEnabled, SIGNAL(stateChanged(int)), this, SLOT(updateCapacityCheck(int)));
  14756. connect(capacity, SIGNAL(valueChanged(QString)), this, SLOT(updateCapacity(QString)));
  14757. connect(capacityUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateCapacityUnit(QString)));
  14758. setLayout(layout);
  14759. }
  14760. @ Iterating over the configuration data associated with the current node is
  14761. required in nearly every configuration widget. The specifics of the loop
  14762. vary, but there is likely a better way to generalize that. Until then,
  14763. obtaining a |QDomNodeList| with the required data to iterate over has been
  14764. split off as its own chunk to reduce the risk of errors associated with typing
  14765. the same code many times.
  14766. @<Get device configuration data for current node@>=
  14767. QDomElement referenceElement =
  14768. model->referenceElement(model->data(index, Qt::UserRole).toString());
  14769. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14770. QDomElement node;
  14771. @ We need to propagate changes to the configuration fields to the device
  14772. configuration document. The |updateAttribute()| method in the base class
  14773. makes this trivial.
  14774. @<RoasterConfWidget implementation@>=
  14775. void RoasterConfWidget::updateRoasterId(int id)
  14776. {
  14777. updateAttribute("databaseid", QString("%1").arg(id));
  14778. }
  14779. void RoasterConfWidget::updateCapacityCheck(int value)
  14780. {
  14781. updateAttribute("checkcapacity", value == Qt::Checked ? "true" : "false");
  14782. }
  14783. void RoasterConfWidget::updateCapacity(const QString &value)
  14784. {
  14785. updateAttribute("capacity", value);
  14786. }
  14787. void RoasterConfWidget::updateCapacityUnit(const QString &value)
  14788. {
  14789. updateAttribute("capacityunit", value);
  14790. }
  14791. @ Finally we must register the configuration widget so that it can be
  14792. instantiated at the appropriate time.
  14793. @<Register device configuration widgets@>=
  14794. app.registerDeviceConfigurationWidget("roaster", RoasterConfWidget::staticMetaObject);
  14795. @** Configuration for NI-DAQmx Base devices.
  14796. \noindent The primary concern in supporting hardware that communicates through
  14797. NI-DAQmx Base is in configurations using a single NI USB 9211 (for NI-DAQmx
  14798. Base 2.x) or NI USB 9211A (for NI-DAQmx Base 3.x), but if it is reasonable to
  14799. do so I'@q'@>d like to later add support for multiple device configurations and
  14800. limited support for other devices including the ability to use devices with
  14801. voltage inputs for non-temperature measurement data. The top priority, however,
  14802. is in continuing to support hardware that people are already using with Typica.
  14803. In order to more easily implement these future plans, device configuration is
  14804. handled with three configuration tiers. The top level configuration node
  14805. indicates that we are using NI-DAQmx Base. Here we can add a child node
  14806. representing either a NI USB 9211 or NI USB 9211A. From a configuration
  14807. perspective these are identical with the default node name as the only
  14808. difference. From the device configuration we can specify the device identifier
  14809. and add channels to the device. In the channel nodes we specify the
  14810. thermocouple type.
  14811. @<Class declarations@>=
  14812. class NiDaqMxBaseDriverConfWidget : public BasicDeviceConfigurationWidget
  14813. {
  14814. @[Q_OBJECT@]@;
  14815. public:@/
  14816. @[Q_INVOKABLE@]@, NiDaqMxBaseDriverConfWidget(DeviceTreeModel *model,@|
  14817. const QModelIndex &index);
  14818. };
  14819. @ There is very little to configure here so there isn'@q'@>t much for the
  14820. constructor to do. We do need to keep a reference to the node we are
  14821. configuring so that child nodes can later be added. At present, no real
  14822. configuration data other than the existence of the node is required so
  14823. there is no need to read any configuration data here.
  14824. @<NiDaqMxBaseDriverConfWidget implementation@>=
  14825. NiDaqMxBaseDriverConfWidget::NiDaqMxBaseDriverConfWidget(
  14826. DeviceTreeModel *model, const QModelIndex &index) :
  14827. BasicDeviceConfigurationWidget(model, index)
  14828. {
  14829. QHBoxLayout *layout = new QHBoxLayout;
  14830. QToolButton *addDeviceButton = new QToolButton;
  14831. addDeviceButton->setText(tr("Add Device"));
  14832. NodeInserter *add9211 = new NodeInserter("NI USB 9211", "NI USB 9211",
  14833. "nidaqmxbase9211series");
  14834. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  14835. "nidaqmxbase9211series");
  14836. connect(add9211, SIGNAL(triggered(QString, QString)),
  14837. this, SLOT(insertChildNode(QString, QString)));
  14838. connect(add9211a, SIGNAL(triggered(QString, QString)),
  14839. this, SLOT(insertChildNode(QString, QString)));
  14840. QMenu *deviceMenu = new QMenu;
  14841. deviceMenu->addAction(add9211);
  14842. deviceMenu->addAction(add9211a);
  14843. addDeviceButton->setMenu(deviceMenu);
  14844. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  14845. layout->addWidget(addDeviceButton);
  14846. setLayout(layout);
  14847. }
  14848. @ Both the NI USB 9211 and NI USB 9211A are identical from a configuration
  14849. perspective. The only difference is the version of NI-DAQmx Base required for
  14850. use. As the API does not provide a way of determining which version is
  14851. installed, ensuring that the appropriate software is installed without
  14852. conflicts is left as an exercise for the person attempting to use \pn{}.
  14853. @<Class declarations@>=
  14854. class NiDaqMxBase9211ConfWidget : public BasicDeviceConfigurationWidget
  14855. {
  14856. Q_OBJECT
  14857. public:
  14858. Q_INVOKABLE NiDaqMxBase9211ConfWidget(DeviceTreeModel *device,
  14859. const QModelIndex &index);
  14860. private slots:
  14861. void addChannel();
  14862. void updateDeviceId(const QString &newId);
  14863. };
  14864. @ There are two controls required in a configuration widget for this device.
  14865. The first is the device identifier (for example, "Dev1"), the second is a
  14866. button for adding channels to the device. On a generic device we would also
  14867. need to set the clock rate, but with this hardware it is possible to determine
  14868. the maximum clock rate from the channels defined.
  14869. @<NiDaqMxBase9211ConfWidget implementation@>=
  14870. NiDaqMxBase9211ConfWidget::NiDaqMxBase9211ConfWidget(DeviceTreeModel *model,
  14871. const QModelIndex &index)
  14872. : BasicDeviceConfigurationWidget(model, index)
  14873. {
  14874. QVBoxLayout *layout = new QVBoxLayout;
  14875. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  14876. QLabel *label = new QLabel(tr("Device ID:"));
  14877. QLineEdit *deviceId = new QLineEdit;
  14878. deviceIdLayout->addWidget(label);
  14879. deviceIdLayout->addWidget(deviceId);
  14880. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  14881. layout->addLayout(deviceIdLayout);
  14882. layout->addWidget(addChannelButton);
  14883. @<Get device configuration data for current node@>@;
  14884. for(int i = 0; i < configData.size(); i++)
  14885. {
  14886. node = configData.at(i).toElement();
  14887. if(node.attribute("name") == "deviceID")
  14888. {
  14889. deviceId->setText(node.attribute("value", "Dev1"));
  14890. break;
  14891. }
  14892. }
  14893. updateDeviceId(deviceId->text());
  14894. connect(addChannelButton, SIGNAL(clicked()),
  14895. this, SLOT(addChannel()));
  14896. connect(deviceId, SIGNAL(textEdited(QString)),
  14897. this, SLOT(updateDeviceId(QString)));
  14898. setLayout(layout);
  14899. }
  14900. @ Updating the attribute tag under the reference element associated with the
  14901. current node is handled in the base class so we just need to pass in the
  14902. appropriate name value pair.
  14903. @<NiDaqMxBase9211ConfWidget implementation@>=
  14904. void NiDaqMxBase9211ConfWidget::updateDeviceId(const QString &newId)
  14905. {
  14906. updateAttribute("deviceID", newId);
  14907. }
  14908. @ Adding channels is just like adding any other sort of node.
  14909. @<NiDaqMxBase9211ConfWidget implementation@>=
  14910. void NiDaqMxBase9211ConfWidget::addChannel()
  14911. {
  14912. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  14913. }
  14914. @ Finally, we need a configuration widget to handle our thermocouple channels.
  14915. Ordinarily we would need three pieces of information for each channel. First
  14916. there is the thermocouple channel. Previously this was left implied by the
  14917. order of requests for a new channel, but more flexible configuration options
  14918. become possible with a more explicit specification. Since this widget is device
  14919. specific, all of the options can be easily enumerated to match markings on the
  14920. device. Next is the thermocouple type. Many options are supported, but I would
  14921. like to ensure that the most commonly used choices are listed first. The other
  14922. piece of information that DAQmx or DAQmx Base require is the measurement unit.
  14923. As all of Typica'@q'@>s internal operations are in Fahrenheit there is no need to
  14924. make this configurable so long as everything else that can display temperature
  14925. measurements can perform the appropriate conversions.
  14926. Note that as there are no configuration differences between the various
  14927. device combinations using an NI 9211 module with regard to thermocouple channel
  14928. configuration, we can use this widget with all device combinations that make
  14929. use of such a module.
  14930. @<Class declarations@>=
  14931. class Ni9211TcConfWidget : public BasicDeviceConfigurationWidget
  14932. {@/
  14933. @[Q_OBJECT@]@;
  14934. public:@/
  14935. Q_INVOKABLE@,@, Ni9211TcConfWidget(DeviceTreeModel *device,
  14936. const QModelIndex &index);
  14937. @[private slots@]:@/
  14938. void updateThermocoupleType(const QString &type);
  14939. void updateColumnName(const QString &name);
  14940. void updateHidden(bool hidden);
  14941. };
  14942. @ This follows the same pattern of previous device configuration widgets. The
  14943. constructor provides the required configuration controls and slot methods
  14944. catch configuration changes and update the underlying XML document
  14945. appropriately.
  14946. @<Ni9211TcConfWidget implementation@>=
  14947. Ni9211TcConfWidget::Ni9211TcConfWidget(DeviceTreeModel *model,
  14948. const QModelIndex &index) :
  14949. BasicDeviceConfigurationWidget(model, index)
  14950. {
  14951. QFormLayout *layout = new QFormLayout;
  14952. QLineEdit *columnName = new QLineEdit;
  14953. layout->addRow(tr("Column Name:"), columnName);
  14954. QComboBox *typeSelector = new QComboBox;
  14955. typeSelector->addItem("J");
  14956. typeSelector->addItem("K");
  14957. typeSelector->addItem("T");
  14958. typeSelector->addItem("B");
  14959. typeSelector->addItem("E");
  14960. typeSelector->addItem("N");
  14961. typeSelector->addItem("R");
  14962. typeSelector->addItem("S");
  14963. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  14964. QCheckBox *hideSeries = new QCheckBox("Hide this channel");
  14965. layout->addRow(hideSeries);
  14966. setLayout(layout);
  14967. @<Get device configuration data for current node@>@;
  14968. for(int i = 0; i < configData.size(); i++)
  14969. {
  14970. node = configData.at(i).toElement();
  14971. if(node.attribute("name") == "type")
  14972. {
  14973. typeSelector->setCurrentIndex(
  14974. typeSelector->findText(node.attribute("value")));
  14975. }
  14976. else if(node.attribute("name") == "columnname")
  14977. {
  14978. columnName->setText(node.attribute("value"));
  14979. }
  14980. else if(node.attribute("name") == "hidden")
  14981. {
  14982. hideSeries->setChecked(node.attribute("value") == "true");
  14983. }
  14984. }
  14985. updateThermocoupleType(typeSelector->currentText());
  14986. updateColumnName(columnName->text());
  14987. updateHidden(hideSeries->isChecked());
  14988. connect(typeSelector, SIGNAL(currentIndexChanged(QString)),
  14989. this, SLOT(updateThermocoupleType(QString)));
  14990. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  14991. connect(hideSeries, SIGNAL(toggled(bool)), this, SLOT(updateHidden(bool)));
  14992. }
  14993. @ Two slots are used to pass configuration changes back to the underlying XML
  14994. representation.
  14995. @<Ni9211TcConfWidget implementation@>=
  14996. void Ni9211TcConfWidget::updateThermocoupleType(const QString &type)
  14997. {
  14998. updateAttribute("type", type);
  14999. }
  15000. void Ni9211TcConfWidget::updateColumnName(const QString &name)
  15001. {
  15002. updateAttribute("columnname", name);
  15003. }
  15004. void Ni9211TcConfWidget::updateHidden(bool hidden)
  15005. {
  15006. updateAttribute("hidden", hidden ? "true" : "false");
  15007. }
  15008. @ These three widgets need to be registered so the configuration widget can
  15009. instantiate them when the nodes are selected.
  15010. @<Register device configuration widgets@>=
  15011. app.registerDeviceConfigurationWidget("nidaqmxbase",
  15012. NiDaqMxBaseDriverConfWidget::staticMetaObject);
  15013. app.registerDeviceConfigurationWidget("nidaqmxbase9211series",
  15014. NiDaqMxBase9211ConfWidget::staticMetaObject);
  15015. app.registerDeviceConfigurationWidget("ni9211seriestc",
  15016. Ni9211TcConfWidget::staticMetaObject);
  15017. @ Furthermore, we should create the NodeInserter objects for adding top level
  15018. nodes to the configuration. Preferably we would only allow top level nodes to
  15019. be inserted when all prerequisite software is available.
  15020. @<Register top level device configuration nodes@>=
  15021. NodeInserter *inserter = new NodeInserter(tr("NI DAQmx Base Device"),
  15022. tr("NI DAQmx Base"),
  15023. "nidaqmxbase", NULL);
  15024. topLevelNodeInserters.append(inserter);
  15025. @** Configuration of NI-DAQmx devices.
  15026. \noindent The other main class of hardware currently supported in Typica is a
  15027. small set of devices that require NI-DAQmx. This includes a few combinations of
  15028. the NI 9211 in different carriers and the NI USB TC01. Additional hardware may
  15029. be added to this set in the future.
  15030. The approach here is very similar to the approach used to configure NI-DAQmx
  15031. Base devices, starting with a widget for adding child device nodes.
  15032. @<Class declarations@>=
  15033. class NiDaqMxDriverConfWidget : public BasicDeviceConfigurationWidget
  15034. {
  15035. @[Q_OBJECT@]@;
  15036. public:
  15037. @[Q_INVOKABLE@]@, NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  15038. const QModelIndex &index);
  15039. };
  15040. @ Under our driver node we want to have the ability to insert device specific
  15041. child nodes.
  15042. @<NiDaqMxDriverConfWidget implementation@>=
  15043. NiDaqMxDriverConfWidget::NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  15044. const QModelIndex &index)
  15045. : BasicDeviceConfigurationWidget(model, index)
  15046. {
  15047. QHBoxLayout *layout = new QHBoxLayout;
  15048. QToolButton *addDeviceButton = new QToolButton;
  15049. addDeviceButton->setText(tr("Add Device"));
  15050. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  15051. "nidaqmx9211series");
  15052. NodeInserter *addtc01 = new NodeInserter("NI USB TC01", "NI USB TC01",
  15053. "nidaqmxtc01");
  15054. connect(add9211a, SIGNAL(triggered(QString, QString)),
  15055. this, SLOT(insertChildNode(QString, QString)));
  15056. connect(addtc01, SIGNAL(triggered(QString, QString)),
  15057. this, SLOT(insertChildNode(QString, QString)));
  15058. QMenu *deviceMenu = new QMenu;
  15059. deviceMenu->addAction(add9211a);
  15060. deviceMenu->addAction(addtc01);
  15061. addDeviceButton->setMenu(deviceMenu);
  15062. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  15063. layout->addWidget(addDeviceButton);
  15064. setLayout(layout);
  15065. }
  15066. @ Devices based on the 9211 module are essentially the same aside from device
  15067. naming convention. Configuring these is very similar to configuring similar
  15068. devices when using NI-DAQmx Base.
  15069. @<Class declarations@>=
  15070. class NiDaqMx9211ConfWidget : public BasicDeviceConfigurationWidget
  15071. {
  15072. @[Q_OBJECT@]@;
  15073. public:@/
  15074. @[Q_INVOKABLE@]@, NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  15075. const QModelIndex &index);
  15076. @[private slots@]:@/
  15077. void addChannel();
  15078. void updateDeviceId(const QString &newId);
  15079. };
  15080. @ Implementation is essentially identical to the NI-DAQmx Base class. It is
  15081. likely that there will be differences if this is ever extended to support
  15082. automatic detection of connected hardware. While NI-DAQmx Base does not
  15083. provide a way to query device identifiers, it uses a consistent naming scheme
  15084. by which device identifiers can be discovered. While NI-DAQmx lacks the same
  15085. consistency in device identifiers, it does provide a way to query that
  15086. information.
  15087. @<NiDaqMx9211ConfWidget implementation@>=
  15088. NiDaqMx9211ConfWidget::NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  15089. const QModelIndex &index)
  15090. : BasicDeviceConfigurationWidget(model, index)
  15091. {
  15092. QVBoxLayout *layout = new QVBoxLayout;
  15093. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  15094. QLabel *label = new QLabel(tr("Device ID:"));
  15095. QLineEdit *deviceId = new QLineEdit;
  15096. deviceIdLayout->addWidget(label);
  15097. deviceIdLayout->addWidget(deviceId);
  15098. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  15099. layout->addLayout(deviceIdLayout);
  15100. layout->addWidget(addChannelButton);
  15101. @<Get device configuration data for current node@>@;
  15102. for(int i = 0; i < configData.size(); i++)
  15103. {
  15104. node = configData.at(i).toElement();
  15105. if(node.attribute("name") == "deviceID")
  15106. {
  15107. deviceId->setText(node.attribute("value","Dev1"));
  15108. break;
  15109. }
  15110. }
  15111. updateDeviceId(deviceId->text());
  15112. connect(addChannelButton, SIGNAL(clicked()), this, SLOT(addChannel()));
  15113. connect(deviceId, SIGNAL(textEdited(QString)),
  15114. this, SLOT(updateDeviceId(QString)));
  15115. setLayout(layout);
  15116. }
  15117. void NiDaqMx9211ConfWidget::updateDeviceId(const QString &newId)
  15118. {
  15119. updateAttribute("deviceID", newId);
  15120. }
  15121. void NiDaqMx9211ConfWidget::addChannel()
  15122. {
  15123. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  15124. }
  15125. @ There is no need to create a configuration widget specific to the 9211 module
  15126. used in NI-DAQmx. The widget already used for NI-DAQmx Base can be used without
  15127. modification.
  15128. Configuring Typica for use with the NI USB-TC01 can be slightly simplified as
  15129. the device only has a single thermocouple channel. We can configure this without
  15130. requiring another node.
  15131. @<Class declarations@>=
  15132. class NiDaqMxTc01ConfWidget : public BasicDeviceConfigurationWidget
  15133. {
  15134. @[Q_OBJECT@]@;
  15135. public:@/
  15136. @[Q_INVOKABLE@]@, NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  15137. const QModelIndex &index);
  15138. @[private slots@]:@/
  15139. void updateDeviceId(const QString &newId);
  15140. void updateThermocoupleType(const QString &type);
  15141. void updateColumnName(const QString &name);
  15142. void updateHidden(bool hidden);
  15143. };
  15144. @ The implementation is similar to the other configuration widgets.
  15145. @<NiDaqMxTc01ConfWidget implementation@>=
  15146. NiDaqMxTc01ConfWidget::NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  15147. const QModelIndex &index)
  15148. : BasicDeviceConfigurationWidget(model, index)
  15149. {
  15150. QFormLayout *layout = new QFormLayout;
  15151. QLineEdit *deviceId = new QLineEdit;
  15152. layout->addRow(tr("Device ID:"), deviceId);
  15153. QLineEdit *columnName = new QLineEdit;
  15154. layout->addRow(tr("Column Name:"), columnName);
  15155. QComboBox *typeSelector = new QComboBox;
  15156. typeSelector->addItem("J");
  15157. typeSelector->addItem("K");
  15158. typeSelector->addItem("T");
  15159. typeSelector->addItem("B");
  15160. typeSelector->addItem("E");
  15161. typeSelector->addItem("N");
  15162. typeSelector->addItem("R");
  15163. typeSelector->addItem("S");
  15164. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  15165. QCheckBox *hideSeries = new QCheckBox(tr("Hide this channel"));
  15166. layout->addRow(hideSeries);
  15167. @<Get device configuration data for current node@>@;
  15168. for(int i = 0; i < configData.size(); i++)
  15169. {
  15170. node = configData.at(i).toElement();
  15171. if(node.attribute("name") == "deviceID")
  15172. {
  15173. deviceId->setText(node.attribute("value"));
  15174. }
  15175. else if(node.attribute("name") == "type")
  15176. {
  15177. typeSelector->setCurrentIndex(typeSelector->findText(node.attribute("value")));
  15178. }
  15179. else if(node.attribute("name") == "columnname")
  15180. {
  15181. columnName->setText(node.attribute("value"));
  15182. }
  15183. else if(node.attribute("name") == "hidden")
  15184. {
  15185. hideSeries->setChecked(node.attribute("value") == "true");
  15186. }
  15187. }
  15188. updateDeviceId(deviceId->text());
  15189. updateThermocoupleType(typeSelector->currentText());
  15190. updateColumnName(columnName->text());
  15191. updateHidden(hideSeries->isChecked());
  15192. connect(deviceId, SIGNAL(textEdited(QString)), this, SLOT(updateDeviceId(QString)));
  15193. connect(typeSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateThermocoupleType(QString)));
  15194. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  15195. setLayout(layout);
  15196. connect(hideSeries, SIGNAL(toggled(bool)), this, SLOT(updateHidden(bool)));
  15197. }
  15198. void NiDaqMxTc01ConfWidget::updateDeviceId(const QString &newId)
  15199. {
  15200. updateAttribute("deviceID", newId);
  15201. }
  15202. void NiDaqMxTc01ConfWidget::updateThermocoupleType(const QString &type)
  15203. {
  15204. updateAttribute("type", type);
  15205. }
  15206. void NiDaqMxTc01ConfWidget::updateColumnName(const QString &name)
  15207. {
  15208. updateAttribute("columnname", name);
  15209. }
  15210. void NiDaqMxTc01ConfWidget::updateHidden(bool hidden)
  15211. {
  15212. updateAttribute("hidden", hidden ? "true" : "false");
  15213. }
  15214. @ These configuration widgets need to be registered so they can be instantiated
  15215. in response to node selections.
  15216. @<Register device configuration widgets@>=
  15217. app.registerDeviceConfigurationWidget("nidaqmx", NiDaqMxDriverConfWidget::staticMetaObject);
  15218. app.registerDeviceConfigurationWidget("nidaqmx9211series", NiDaqMx9211ConfWidget::staticMetaObject);
  15219. app.registerDeviceConfigurationWidget("nidaqmxtc01", NiDaqMxTc01ConfWidget::staticMetaObject);
  15220. @ A |NodeInserter| for the driver configuration widget is also needed. Note that
  15221. at present NI DAQmx is only available on Windows so we do not bother to show
  15222. the option on other platforms. It would be generally preferable to replace this
  15223. with a check at runtime to determine if the required library exists. That could
  15224. be done with anything that requires third party installed code, leaving by
  15225. default only those options which have no external dependencies.
  15226. @<Register top level device configuration nodes@>=
  15227. #ifdef Q_OS_WIN32
  15228. inserter = new NodeInserter(tr("NI DAQmx Device"), tr("NI DAQmx"), "nidaqmx", NULL);
  15229. topLevelNodeInserters.append(inserter);
  15230. #endif
  15231. @** Configuration of Serial Port Devices.
  15232. \noindent It is possible to communicate with a number of devices through a
  15233. serial port. To do this, the appropriate settings for opening the port are
  15234. required and the communications protocol understood by the device must be
  15235. known. Serial port communications are provided by QextSerialPort. That
  15236. project was released under the MIT license.\nfnote{See the license text for
  15237. more information.} Additional headers are required.
  15238. @<Header files to include@>=
  15239. #include "qextserialport.h"
  15240. #include "qextserialenumerator.h"
  15241. @ Some custom widgets are provided which allow selecting the relevant
  15242. connection options from combo boxes. First there is a widget for selecting
  15243. the desired serial port. The drop down is pre-populated with any serial ports
  15244. that could be automatically detected, but the field can also be edited to
  15245. other values as may be required if the hardware is not connected during
  15246. configuration.
  15247. @<Class declarations@>=
  15248. class PortSelector : public QComboBox
  15249. {
  15250. Q_OBJECT
  15251. public:
  15252. PortSelector(QWidget *parent = NULL);
  15253. private slots:
  15254. void addDevice(QextPortInfo port);
  15255. private:
  15256. QextSerialEnumerator *lister;
  15257. };
  15258. @ The implementation is trivial.
  15259. @<PortSelector implementation@>=
  15260. PortSelector::PortSelector(QWidget *parent) : QComboBox(parent),
  15261. lister(new QextSerialEnumerator)
  15262. {
  15263. QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
  15264. QextPortInfo port;
  15265. foreach(port, ports)
  15266. {
  15267. #ifdef Q_OS_WIN32
  15268. addItem(port.portName);
  15269. #else
  15270. addItem(port.physName);
  15271. #endif
  15272. }
  15273. lister->setUpNotifications();
  15274. connect(lister, SIGNAL(deviceDiscovered(QextPortInfo)),
  15275. this, SLOT(addDevice(QextPortInfo)));
  15276. setEditable(true);
  15277. }
  15278. void PortSelector::addDevice(QextPortInfo port)
  15279. {
  15280. addItem(port.portName);
  15281. }
  15282. @ Next is a widget which allows selecting the baud rate. Only rates supported
  15283. by the current operating system are available to select.
  15284. A later version of QextSerialPort than is used by \pn{} provides a helper
  15285. class which can be used more conveniently to create this sort of control. As
  15286. this is not yet available to \pn{}, we instead copy the |enum| specifying
  15287. the appropriate values into the class and use Qt'@q'@>s meta-object system to
  15288. populate the combo box based on the values in that |enum|.
  15289. @<Class declarations@>=
  15290. class BaudSelector : public QComboBox
  15291. {
  15292. Q_OBJECT
  15293. Q_ENUMS(BaudRateType)
  15294. public:
  15295. BaudSelector(QWidget *parent = NULL);
  15296. enum BaudRateType
  15297. {
  15298. #if defined(Q_OS_UNIX) || defined(qdoc)
  15299. BAUD50 = 50, //POSIX ONLY
  15300. BAUD75 = 75, //POSIX ONLY
  15301. BAUD134 = 134, //POSIX ONLY
  15302. BAUD150 = 150, //POSIX ONLY
  15303. BAUD200 = 200, //POSIX ONLY
  15304. BAUD1800 = 1800, //POSIX ONLY
  15305. #if defined(B76800) || defined(qdoc)
  15306. BAUD76800 = 76800, //POSIX ONLY
  15307. #endif
  15308. #if (defined(B230400) && defined(B4000000)) || defined(qdoc)
  15309. BAUD230400 = 230400, //POSIX ONLY
  15310. BAUD460800 = 460800, //POSIX ONLY
  15311. BAUD500000 = 500000, //POSIX ONLY
  15312. BAUD576000 = 576000, //POSIX ONLY
  15313. BAUD921600 = 921600, //POSIX ONLY
  15314. BAUD1000000 = 1000000, //POSIX ONLY
  15315. BAUD1152000 = 1152000, //POSIX ONLY
  15316. BAUD1500000 = 1500000, //POSIX ONLY
  15317. BAUD2000000 = 2000000, //POSIX ONLY
  15318. BAUD2500000 = 2500000, //POSIX ONLY
  15319. BAUD3000000 = 3000000, //POSIX ONLY
  15320. BAUD3500000 = 3500000, //POSIX ONLY
  15321. BAUD4000000 = 4000000, //POSIX ONLY
  15322. #endif
  15323. #endif
  15324. #if defined(Q_OS_WIN) || defined(qdoc)
  15325. BAUD14400 = 14400, //WINDOWS ONLY
  15326. BAUD56000 = 56000, //WINDOWS ONLY
  15327. BAUD128000 = 128000, //WINDOWS ONLY
  15328. BAUD256000 = 256000, //WINDOWS ONLY
  15329. #endif
  15330. BAUD110 = 110,
  15331. BAUD300 = 300,
  15332. BAUD600 = 600,
  15333. BAUD1200 = 1200,
  15334. BAUD2400 = 2400,
  15335. BAUD4800 = 4800,
  15336. BAUD9600 = 9600,
  15337. BAUD19200 = 19200,
  15338. BAUD38400 = 38400,
  15339. BAUD57600 = 57600,
  15340. BAUD115200 = 115200
  15341. };
  15342. };
  15343. @ As the |enum| values are identical to the baud rates represented, we only
  15344. the numeric values, ignoring the names which are rather ugly.
  15345. @<BaudSelector implementation@>=
  15346. BaudSelector::BaudSelector(QWidget *parent) : QComboBox(parent)
  15347. {
  15348. QMetaObject meta = BaudSelector::staticMetaObject;
  15349. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("BaudRateType"));
  15350. for(int i = 0; i < type.keyCount(); i++)
  15351. {
  15352. addItem(QString("%1").arg(type.value(i)));
  15353. }
  15354. }
  15355. @ This same technique is used in a widget for selecting parity.
  15356. @<Class declarations@>=
  15357. class ParitySelector : public QComboBox
  15358. {
  15359. Q_OBJECT
  15360. Q_ENUMS(ParityType)
  15361. public:
  15362. ParitySelector(QWidget *parent = NULL);
  15363. enum ParityType
  15364. {
  15365. PAR_NONE,
  15366. PAR_ODD,
  15367. PAR_EVEN,
  15368. #if defined(Q_OS_WIN) || defined(qdoc)
  15369. PAR_MARK, //WINDOWS ONLY
  15370. #endif
  15371. PAR_SPACE
  15372. };
  15373. };
  15374. @ Implementation is similar to |BaudSelector| but as the values have no
  15375. apparent relation to what is represented we present the value names, placing
  15376. the corresponding value in the user data space associated with each entry.
  15377. The names here are ugly and not amenable to localization so this approach
  15378. should be reconsidered later.
  15379. @<ParitySelector implementation@>=
  15380. ParitySelector::ParitySelector(QWidget *parent) : QComboBox(parent)
  15381. {
  15382. QMetaObject meta = ParitySelector::staticMetaObject;
  15383. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("ParityType"));
  15384. for(int i = 0; i < type.keyCount(); i++)
  15385. {
  15386. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15387. }
  15388. }
  15389. @ Similarly, we have a widget for selecting a method for flow control.
  15390. @<Class declarations@>=
  15391. class FlowSelector : public QComboBox
  15392. {
  15393. @[Q_OBJECT@]@;
  15394. @[Q_ENUMS(FlowType)@]@;
  15395. public:@/
  15396. FlowSelector(QWidget *parent = NULL);
  15397. enum FlowType
  15398. {
  15399. FLOW_OFF,
  15400. FLOW_HARDWARE,
  15401. FLOW_XONXOFF
  15402. };
  15403. };
  15404. @ Implementation follows the same pattern as in |ParitySelector|.
  15405. @<FlowSelector implementation@>=
  15406. FlowSelector::FlowSelector(QWidget *parent) : QComboBox(parent)
  15407. {
  15408. QMetaObject meta = FlowSelector::staticMetaObject;
  15409. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("FlowType"));
  15410. for(int i = 0; i < type.keyCount(); i++)
  15411. {
  15412. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15413. }
  15414. }
  15415. @ We assume that the number of data bits will always be 8, though it may be
  15416. useful to later provide a control for selecting this for use with other devices
  15417. where this may not be assumed or for the sake of completion. This only leaves
  15418. specifying the number of stop bits.
  15419. @<Class declarations@>=
  15420. class StopSelector : public QComboBox
  15421. {
  15422. @[Q_OBJECT@]@;
  15423. @[Q_ENUMS(StopBitsType)@]@;
  15424. public:@/
  15425. StopSelector(QWidget *parent = NULL);
  15426. enum StopBitsType
  15427. {
  15428. STOP_1,
  15429. #if defined(Q_OS_WIN) || defined(qdoc)
  15430. STOP_1_5, //WINDOWS ONLY
  15431. #endif
  15432. STOP_2
  15433. };
  15434. };
  15435. @ Implementation should be familiar by now.
  15436. @<StopSelector implementation@>=
  15437. StopSelector::StopSelector(QWidget *parent) : QComboBox(parent)
  15438. {
  15439. QMetaObject meta = StopSelector::staticMetaObject;
  15440. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("StopBitsType"));
  15441. for(int i = 0; i < type.keyCount(); i++)
  15442. {
  15443. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15444. }
  15445. }
  15446. @** Configuration of Serial Devices Using Modbus RTU.
  15447. \noindent The following sections contain the details of older code related to
  15448. Modbus RTU support. While the various selector widgets are shared with the new
  15449. code, the configuration widgets and device interfaces are being replaced.
  15450. One protocol that is used across a broad class of devices is called
  15451. Modbus RTU. This protocol allows multiple devices to be chained together on a
  15452. two wire bus which can be connected to a single serial port. The communication
  15453. protocol involves a single message which is sent from a master device (in this
  15454. case the computer running Typica) to a slave device (the device we would like
  15455. to obtain information from) which is followed by a response message from the
  15456. slave to the master. After a brief wait the master can then send another
  15457. message to any slave on the bus and this process repeats. Every outgoing
  15458. message provides a station address to identify which slave on the bus should
  15459. respond, a function code to identify which of a broad class of operations has
  15460. been requested, the required data for the function specified, and a cyclic
  15461. redundancy check to validate the message.
  15462. @** A Spin Box with Hexadecimal Representation.
  15463. \noindent Common convention for communications documentation for devices that
  15464. use Modbus RTU is that relative addresses are specified in hexadecimal
  15465. representation. In order to simplify initial device configuration, it would be
  15466. best that input widgets both accept input in base 16 and display values as a
  15467. four digit hexadecimal value.
  15468. @<Class declarations@>=
  15469. class ShortHexSpinBox : public QSpinBox
  15470. {
  15471. @[Q_OBJECT@]@;
  15472. public:@/
  15473. ShortHexSpinBox(QWidget *parent = NULL);
  15474. virtual QValidator::State validate(QString &input, int &pos) const;@/
  15475. protected:@/
  15476. virtual int valueFromText(const QString &text) const;
  15477. virtual QString textFromValue(int value) const;@/
  15478. };
  15479. @ For this we can set some new defaults in the constructor and must override
  15480. three methods.
  15481. @<ShortHexSpinBox implementation@>=
  15482. ShortHexSpinBox::ShortHexSpinBox(QWidget *parent) : QSpinBox(parent)
  15483. {
  15484. setMinimum(0);
  15485. setMaximum(0xFFFF);
  15486. setPrefix("0x");
  15487. setMinimumWidth(65);
  15488. }
  15489. QValidator::State ShortHexSpinBox::validate(QString &input, int &) const
  15490. {
  15491. if(input.size() == 2)
  15492. {
  15493. return QValidator::Intermediate;
  15494. }
  15495. bool okay;
  15496. input.toInt(&okay, 16);
  15497. if(okay)
  15498. {
  15499. return QValidator::Acceptable;
  15500. }
  15501. return QValidator::Invalid;
  15502. }
  15503. int ShortHexSpinBox::valueFromText(const QString &text) const
  15504. {
  15505. return text.toInt(NULL, 16);
  15506. }
  15507. QString ShortHexSpinBox::textFromValue(int value) const
  15508. {
  15509. QString retval;
  15510. retval.setNum(value, 16);
  15511. while(retval.size() < 4)
  15512. {
  15513. retval.prepend("0");
  15514. }
  15515. return retval.toUpper();
  15516. }
  15517. @** Configuration Widgets for Modbus RTU Devices.
  15518. \noindent While the top level configuration widgets seen so far have not had
  15519. any configuration details beyond the ability to add devices under the driver,
  15520. in the case of a serial port with Modbus RTU devices it is reasonable to
  15521. provide the connection details which will be shared by all devices on the bus.
  15522. @<Class declarations@>=
  15523. class ModbusRtuPortConfWidget : public BasicDeviceConfigurationWidget
  15524. {
  15525. @[Q_OBJECT@]@;
  15526. public:
  15527. @[Q_INVOKABLE@]@, ModbusRtuPortConfWidget(DeviceTreeModel *model,
  15528. const QModelIndex &index);
  15529. @[private slots@]:@/
  15530. void updatePort(const QString &newPort);
  15531. void updateBaudRate(const QString &newRate);
  15532. void updateParity(const QString &newParity);
  15533. void updateFlowControl(const QString &newFlow);
  15534. void updateStopBits(const QString &newStopBits);
  15535. };
  15536. @ Aside from the extra information compared with other configuration widgets
  15537. previously described, there is nothing surprising about the implementation.
  15538. @<ModbusRtuPortConfWidget implementation@>=
  15539. ModbusRtuPortConfWidget::ModbusRtuPortConfWidget(DeviceTreeModel *model,
  15540. const QModelIndex &index)
  15541. : BasicDeviceConfigurationWidget(model, index)
  15542. {
  15543. QFormLayout *layout = new QFormLayout;
  15544. QToolButton *addDeviceButton = new QToolButton;
  15545. addDeviceButton->setText(tr("Add Device"));
  15546. NodeInserter *addModbusRtuDevice = new NodeInserter("Modbus RTU Device",
  15547. "Modbus RTU Device",
  15548. "modbusrtudevice");
  15549. connect(addModbusRtuDevice, SIGNAL(triggered(QString, QString)),
  15550. this, SLOT(insertChildNode(QString, QString)));
  15551. QMenu *deviceMenu = new QMenu;
  15552. deviceMenu->addAction(addModbusRtuDevice);
  15553. addDeviceButton->setMenu(deviceMenu);
  15554. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  15555. layout->addRow(QString(), addDeviceButton);
  15556. PortSelector *port = new PortSelector;
  15557. layout->addRow(tr("Port:"), port);
  15558. connect(port, SIGNAL(currentIndexChanged(QString)),
  15559. this, SLOT(updatePort(QString)));
  15560. connect(port, SIGNAL(editTextChanged(QString)),
  15561. this, SLOT(updatePort(QString)));
  15562. BaudSelector *rate = new BaudSelector;
  15563. layout->addRow(tr("Baud:"), rate);
  15564. connect(rate, SIGNAL(currentIndexChanged(QString)),
  15565. this, SLOT(updateBaudRate(QString)));
  15566. ParitySelector *parity = new ParitySelector;
  15567. layout->addRow(tr("Parity:"), parity);
  15568. connect(parity, SIGNAL(currentIndexChanged(QString)),
  15569. this, SLOT(updateParity(QString)));
  15570. FlowSelector *flow = new FlowSelector;
  15571. layout->addRow(tr("Flow Control:"), flow);
  15572. connect(flow, SIGNAL(currentIndexChanged(QString)),
  15573. this, SLOT(updateFlowControl(QString)));
  15574. StopSelector *stop = new StopSelector;
  15575. layout->addRow(tr("Stop Bits:"), stop);
  15576. connect(stop, SIGNAL(currentIndexChanged(QString)),
  15577. this, SLOT(updateStopBits(QString)));
  15578. @<Get device configuration data for current node@>@;
  15579. for(int i = 0; i < configData.size(); i++)
  15580. {
  15581. node = configData.at(i).toElement();
  15582. if(node.attribute("name") == "port")
  15583. {
  15584. int j = port->findText(node.attribute("value"));
  15585. if(j >= 0)
  15586. {
  15587. port->setCurrentIndex(j);
  15588. }
  15589. else
  15590. {
  15591. port->insertItem(0, node.attribute("value"));
  15592. port->setCurrentIndex(0);
  15593. }
  15594. }
  15595. else if(node.attribute("name") == "baudrate")
  15596. {
  15597. rate->setCurrentIndex(rate->findText(node.attribute("value")));
  15598. }
  15599. else if(node.attribute("name") == "parity")
  15600. {
  15601. parity->setCurrentIndex(parity->findText(node.attribute("value")));
  15602. }
  15603. else if(node.attribute("name") == "flowcontrol")
  15604. {
  15605. flow->setCurrentIndex(flow->findText(node.attribute("value")));
  15606. }
  15607. else if(node.attribute("name") == "stopbits")
  15608. {
  15609. stop->setCurrentIndex(stop->findText(node.attribute("value")));
  15610. }
  15611. }
  15612. updatePort(port->currentText());
  15613. updateBaudRate(rate->currentText());
  15614. updateParity(parity->currentText());
  15615. updateFlowControl(flow->currentText());
  15616. updateStopBits(stop->currentText());
  15617. setLayout(layout);
  15618. }
  15619. void ModbusRtuPortConfWidget::updatePort(const QString &newPort)
  15620. {
  15621. updateAttribute("port", newPort);
  15622. }
  15623. void ModbusRtuPortConfWidget::updateBaudRate(const QString &newRate)
  15624. {
  15625. updateAttribute("baudrate", newRate);
  15626. }
  15627. void ModbusRtuPortConfWidget::updateParity(const QString &newParity)
  15628. {
  15629. updateAttribute("parity", newParity);
  15630. }
  15631. void ModbusRtuPortConfWidget::updateFlowControl(const QString &newFlow)
  15632. {
  15633. updateAttribute("flowcontrol", newFlow);
  15634. }
  15635. void ModbusRtuPortConfWidget::updateStopBits(const QString &newStopBits)
  15636. {
  15637. updateAttribute("stopbits", newStopBits);
  15638. }
  15639. @ From here we need to provide a widget for configuring a particular device.
  15640. At a minimum this would require setting the station number to a value between
  15641. 0 and 255. Zero is typically the broadcast address which reaches all devices
  15642. on the bus and is not generally recommended for use except in particular
  15643. circumstances. There are, however, a number of settings that influence all of
  15644. the currently supported child nodes and these settings are in the device
  15645. configuration widget instead of requiring that information to be duplicated
  15646. across multiple child nodes.
  15647. The Modbus RTU protocol is very general in scope and leaves many of the
  15648. details of how to do certain things up to the manufacturer. For rudimentary
  15649. support of devices using this protocol, the documentation for several devices
  15650. was consulted and a test rig with one device was set up. There are a number of
  15651. assumptions made for this initial support and to better support additional
  15652. device classes it may become necessary to expand on what is provided initially.
  15653. The primary focus presently is on the use of PID controllers as temperature
  15654. indicators with the ability to modify a set value in the case where this is
  15655. used as a controller rather than just a display.
  15656. All of the devices studied prior to adding this support made use of scaled
  15657. integer representation. In order to correctly determine the measured process
  15658. value it is necessary to know the unit of the measurement and the position of
  15659. the decimal point. It is generally possible to query this information, however
  15660. it may be useful to provide a way to specify fixed values in the event that a
  15661. device exposes these details in a way that is incompatible with my assumptions.
  15662. @<Class declarations@>=
  15663. class ModbusRtuDeviceConfWidget : public BasicDeviceConfigurationWidget
  15664. {
  15665. @[Q_OBJECT@]@;
  15666. public:@/
  15667. @[Q_INVOKABLE@]@, ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  15668. const QModelIndex &index);
  15669. @[private slots@]:@/
  15670. void updateStationNumber(int newStation);
  15671. void updateFixedUnit(bool newFixed);
  15672. void updateFixedDecimal(bool newFixed);
  15673. void updateUnit(const QString &newUnit);
  15674. void updateUnitAddress(int newAddress);
  15675. void updateValueF(int newValue);
  15676. void updateValueC(int newValue);
  15677. void updatePrecisionAddress(int newAddress);
  15678. void updatePrecisionValue(int newValue);
  15679. private:@/
  15680. QStackedLayout *unitSpecificationLayout;
  15681. QStackedLayout *decimalSpecificationLayout;
  15682. };
  15683. @ This widget has a number of differences from previous configuration widgets.
  15684. Perhaps most significantly there are controls which do not provide a text based
  15685. signal on state change. We also set certain controls as disabled when the
  15686. provided values are not relevant to operations such as when switching between
  15687. fixed decimal position and looking up decimal position from the device. Aside
  15688. from these details the widget operates according to the same principles as the
  15689. other widgets already seen.
  15690. @<ModbusRtuDeviceConfWidget implementation@>=
  15691. ModbusRtuDeviceConfWidget::ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  15692. const QModelIndex &index)
  15693. : BasicDeviceConfigurationWidget(model, index),
  15694. unitSpecificationLayout(new QStackedLayout),
  15695. decimalSpecificationLayout(new QStackedLayout)
  15696. {
  15697. QVBoxLayout *layout = new QVBoxLayout;
  15698. QToolButton *addChannelButton = new QToolButton;
  15699. addChannelButton->setText(tr("Add Channel"));
  15700. NodeInserter *addTemperaturePV = new NodeInserter("Temperature Process Value",
  15701. "Temperature Process Value",
  15702. "modbustemperaturepv");
  15703. NodeInserter *addTemperatureSV = new NodeInserter("Temperature Set Value",
  15704. "Temperature Set Value",
  15705. "modbustemperaturesv");
  15706. connect(addTemperaturePV, SIGNAL(triggered(QString, QString)),
  15707. this, SLOT(insertChildNode(QString, QString)));
  15708. connect(addTemperatureSV, SIGNAL(triggered(QString, QString)),
  15709. this, SLOT(insertChildNode(QString, QString)));
  15710. QMenu *channelMenu = new QMenu;
  15711. channelMenu->addAction(addTemperaturePV);
  15712. channelMenu->addAction(addTemperatureSV);
  15713. addChannelButton->setMenu(channelMenu);
  15714. addChannelButton->setPopupMode(QToolButton::InstantPopup);
  15715. layout->addWidget(addChannelButton);
  15716. QHBoxLayout *stationLayout = new QHBoxLayout;
  15717. QLabel *stationLabel = new QLabel(tr("Station:"));
  15718. QSpinBox *stationNumber = new QSpinBox;
  15719. stationNumber->setMinimum(0);
  15720. stationNumber->setMaximum(255);
  15721. stationLayout->addWidget(stationLabel);
  15722. stationLayout->addWidget(stationNumber);
  15723. layout->addLayout(stationLayout);
  15724. QCheckBox *fixedUnit = new QCheckBox(tr("Fixed Temperature Unit"));
  15725. layout->addWidget(fixedUnit);
  15726. QWidget *fixedUnitPlaceholder = new QWidget(this);
  15727. QHBoxLayout *fixedUnitLayout = new QHBoxLayout;
  15728. QLabel *fixedUnitLabel = new QLabel(tr("Temperature Unit:"));
  15729. QComboBox *fixedUnitSelector = new QComboBox;
  15730. fixedUnitSelector->addItem("Fahrenheit");
  15731. fixedUnitSelector->addItem("Celsius");
  15732. fixedUnitLayout->addWidget(fixedUnitLabel);
  15733. fixedUnitLayout->addWidget(fixedUnitSelector);
  15734. fixedUnitPlaceholder->setLayout(fixedUnitLayout);
  15735. unitSpecificationLayout->addWidget(fixedUnitPlaceholder);
  15736. QWidget *queriedUnitPlaceholder = new QWidget(this);
  15737. QFormLayout *queriedUnitLayout = new QFormLayout;
  15738. ShortHexSpinBox *unitAddress = new ShortHexSpinBox;
  15739. queriedUnitLayout->addRow(tr("Function 0x03 Unit Address:"), unitAddress);
  15740. QSpinBox *valueF = new QSpinBox;
  15741. valueF->setMinimum(0);
  15742. valueF->setMaximum(65535);
  15743. queriedUnitLayout->addRow(tr("Value for Fahrenheit"), valueF);
  15744. QSpinBox *valueC = new QSpinBox;
  15745. valueC->setMinimum(0);
  15746. valueC->setMaximum(65535);
  15747. queriedUnitLayout->addRow(tr("Value for Celsius"), valueC);
  15748. queriedUnitPlaceholder->setLayout(queriedUnitLayout);
  15749. unitSpecificationLayout->addWidget(queriedUnitPlaceholder);
  15750. layout->addLayout(unitSpecificationLayout);
  15751. QCheckBox *fixedPrecision = new QCheckBox(tr("Fixed Precision"));
  15752. layout->addWidget(fixedPrecision);
  15753. QWidget *fixedPrecisionPlaceholder = new QWidget(this);
  15754. QFormLayout *fixedPrecisionLayout = new QFormLayout;
  15755. QSpinBox *fixedPrecisionValue = new QSpinBox;
  15756. fixedPrecisionValue->setMinimum(0);
  15757. fixedPrecisionValue->setMaximum(9);
  15758. fixedPrecisionLayout->addRow("Places after the decimal point:",
  15759. fixedPrecisionValue);
  15760. fixedPrecisionPlaceholder->setLayout(fixedPrecisionLayout);
  15761. decimalSpecificationLayout->addWidget(fixedPrecisionPlaceholder);
  15762. QWidget *queriedPrecisionPlaceholder = new QWidget(this);
  15763. QFormLayout *queriedPrecisionLayout = new QFormLayout;
  15764. ShortHexSpinBox *precisionAddress = new ShortHexSpinBox;
  15765. queriedPrecisionLayout->addRow("Function 0x03 Decimal Position Address:",
  15766. precisionAddress);
  15767. queriedPrecisionPlaceholder->setLayout(queriedPrecisionLayout);
  15768. decimalSpecificationLayout->addWidget(queriedPrecisionPlaceholder);
  15769. layout->addLayout(decimalSpecificationLayout);
  15770. @<Get device configuration data for current node@>@;
  15771. for(int i = 0; i < configData.size(); i++)
  15772. {
  15773. node = configData.at(i).toElement();
  15774. if(node.attribute("name") == "station")
  15775. {
  15776. stationNumber->setValue(node.attribute("value").toInt());
  15777. }
  15778. else if(node.attribute("name") == "fixedunit")
  15779. {
  15780. if(node.attribute("value") == "true")
  15781. {
  15782. fixedUnit->setCheckState(Qt::Checked);
  15783. }
  15784. else if(node.attribute("value") == "false")
  15785. {
  15786. fixedUnit->setCheckState(Qt::Unchecked);
  15787. }
  15788. }
  15789. else if(node.attribute("name") == "fixedprecision")
  15790. {
  15791. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  15792. }
  15793. else if(node.attribute("name") == "unit")
  15794. {
  15795. fixedUnitSelector->setCurrentIndex(fixedUnitSelector->findText(node.attribute("value")));
  15796. }
  15797. else if(node.attribute("name") == "unitaddress")
  15798. {
  15799. unitAddress->setValue(node.attribute("value").toInt());
  15800. }
  15801. else if(node.attribute("name") == "fvalue")
  15802. {
  15803. valueF->setValue(node.attribute("value").toInt());
  15804. }
  15805. else if(node.attribute("name") == "cvalue")
  15806. {
  15807. valueC->setValue(node.attribute("value").toInt());
  15808. }
  15809. else if(node.attribute("name") == "precisionaddress")
  15810. {
  15811. precisionAddress->setValue(node.attribute("value").toInt());
  15812. }
  15813. else if(node.attribute("name") == "precision")
  15814. {
  15815. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  15816. }
  15817. }
  15818. updateStationNumber(stationNumber->value());
  15819. updateFixedUnit(fixedUnit->isChecked());
  15820. updateFixedDecimal(fixedPrecision->isChecked());
  15821. updateUnit(fixedUnitSelector->currentText());
  15822. updateUnitAddress(unitAddress->value());
  15823. updateValueF(valueF->value());
  15824. updateValueC(valueC->value());
  15825. updatePrecisionAddress(precisionAddress->value());
  15826. updatePrecisionValue(fixedPrecisionValue->value());
  15827. connect(stationNumber, SIGNAL(valueChanged(int)),
  15828. this, SLOT(updateStationNumber(int)));
  15829. connect(fixedUnitSelector, SIGNAL(currentIndexChanged(QString)),
  15830. this, SLOT(updateUnit(QString)));
  15831. connect(unitAddress, SIGNAL(valueChanged(int)),
  15832. this, SLOT(updateUnitAddress(int)));
  15833. connect(valueF, SIGNAL(valueChanged(int)),
  15834. this, SLOT(updateValueF(int)));
  15835. connect(valueC, SIGNAL(valueChanged(int)),
  15836. this, SLOT(updateValueC(int)));
  15837. connect(fixedUnit, SIGNAL(toggled(bool)),
  15838. this, SLOT(updateFixedUnit(bool)));
  15839. connect(fixedPrecision, SIGNAL(toggled(bool)),
  15840. this, SLOT(updateFixedDecimal(bool)));
  15841. connect(fixedPrecisionValue, SIGNAL(valueChanged(int)),
  15842. this, SLOT(updatePrecisionValue(int)));
  15843. connect(precisionAddress, SIGNAL(valueChanged(int)),
  15844. this, SLOT(updatePrecisionAddress(int)));
  15845. setLayout(layout);
  15846. }
  15847. void ModbusRtuDeviceConfWidget::updateStationNumber(int newStation)
  15848. {
  15849. updateAttribute("station", QString("%1").arg(newStation));
  15850. }
  15851. void ModbusRtuDeviceConfWidget::updateFixedUnit(bool newFixed)
  15852. {
  15853. if(newFixed)
  15854. {
  15855. unitSpecificationLayout->setCurrentIndex(0);
  15856. updateAttribute("fixedunit", "true");
  15857. }
  15858. else
  15859. {
  15860. unitSpecificationLayout->setCurrentIndex(1);
  15861. updateAttribute("fixedunit", "false");
  15862. }
  15863. }
  15864. void ModbusRtuDeviceConfWidget::updateFixedDecimal(bool newFixed)
  15865. {
  15866. if(newFixed)
  15867. {
  15868. decimalSpecificationLayout->setCurrentIndex(0);
  15869. updateAttribute("fixedprecision", "true");
  15870. }
  15871. else
  15872. {
  15873. decimalSpecificationLayout->setCurrentIndex(1);
  15874. updateAttribute("fixedprecision", "false");
  15875. }
  15876. }
  15877. void ModbusRtuDeviceConfWidget::updateUnit(const QString &newUnit)
  15878. {
  15879. updateAttribute("unit", newUnit);
  15880. }
  15881. void ModbusRtuDeviceConfWidget::updateUnitAddress(int newAddress)
  15882. {
  15883. updateAttribute("unitaddress", QString("%1").arg(newAddress));
  15884. }
  15885. void ModbusRtuDeviceConfWidget::updateValueF(int newValue)
  15886. {
  15887. updateAttribute("fvalue", QString("%1").arg(newValue));
  15888. }
  15889. void ModbusRtuDeviceConfWidget::updateValueC(int newValue)
  15890. {
  15891. updateAttribute("cvalue", QString("%1").arg(newValue));
  15892. }
  15893. void ModbusRtuDeviceConfWidget::updatePrecisionAddress(int newAddress)
  15894. {
  15895. updateAttribute("precisionaddress", QString("%1").arg(newAddress));
  15896. }
  15897. void ModbusRtuDeviceConfWidget::updatePrecisionValue(int newValue)
  15898. {
  15899. updateAttribute("precision", QString("%1").arg(newValue));
  15900. }
  15901. @ Initial Modbus RTU support is very limited and only considers temperature
  15902. process and set values. While in some cases it would be possible to cleverly
  15903. adapt this support to broader categories this is an area that must be extended
  15904. later to cover at least unitless control values and on/off status values. It
  15905. would be ideal to cover a broad range of useful properties. To read process
  15906. values we need to know the address that the current process value can be read
  15907. from.
  15908. @<Class declarations@>=
  15909. class ModbusRtuDeviceTPvConfWidget : public BasicDeviceConfigurationWidget
  15910. {
  15911. @[Q_OBJECT@]@/
  15912. public:@/
  15913. @[Q_INVOKABLE@]@, ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  15914. const QModelIndex &index);
  15915. @[private slots@]:@/
  15916. void updateAddress(int newAddress);
  15917. };
  15918. @ This requires only a single field to store the address to query the current
  15919. process value.
  15920. @<ModbusRtuDeviceTPvConfWidget implementation@>=
  15921. ModbusRtuDeviceTPvConfWidget::ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  15922. const QModelIndex &index)
  15923. : BasicDeviceConfigurationWidget(model, index)
  15924. {
  15925. QFormLayout *layout = new QFormLayout;
  15926. ShortHexSpinBox *address = new ShortHexSpinBox;
  15927. layout->addRow(tr("Function 0x04 Process Value Address"), address);
  15928. @<Get device configuration data for current node@>@;
  15929. for(int i = 0; i < configData.size(); i++)
  15930. {
  15931. node = configData.at(i).toElement();
  15932. if(node.attribute("name") == "address")
  15933. {
  15934. address->setValue(node.attribute("value").toInt());
  15935. break;
  15936. }
  15937. }
  15938. updateAddress(address->value());
  15939. connect(address, SIGNAL(valueChanged(int)), this, SLOT(updateAddress(int)));
  15940. setLayout(layout);
  15941. }
  15942. void ModbusRtuDeviceTPvConfWidget::updateAddress(int newAddress)
  15943. {
  15944. updateAttribute("address", QString("%1").arg(newAddress));
  15945. }
  15946. @ Set values are slightly more complicated as we may want either a fixed range
  15947. or the ability to query the device for its current allowed range, but nothing
  15948. is here that hasn'@q'@>t been seen elsewhere.
  15949. @<Class declarations@>=
  15950. class ModbusRtuDeviceTSvConfWidget : public BasicDeviceConfigurationWidget@/
  15951. {@/
  15952. @[Q_OBJECT@]@;
  15953. public:@/
  15954. Q_INVOKABLE@, ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  15955. const QModelIndex &index);
  15956. @[private slots@]:@/
  15957. void updateReadAddress(int newAddress);
  15958. void updateWriteAddress(int newAddress);
  15959. void updateFixedRange(bool fixed);
  15960. void updateLower(const QString &lower);
  15961. void updateUpper(const QString &upper);
  15962. void updateLowerAddress(int newAddress);
  15963. void updateUpperAddress(int newAddress);@/
  15964. private:@/
  15965. QStackedLayout *boundsLayout;
  15966. };
  15967. @ Upper and lower bounds when operating on a fixed range are still subject to
  15968. decimal position rules in the parent node. It may be a good idea to enforce
  15969. this, however at present the person configuring the system is trusted to know
  15970. what they are doing.
  15971. @<ModbusRtuDeviceTSvConfWidget implementation@>=
  15972. ModbusRtuDeviceTSvConfWidget::ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  15973. const QModelIndex &index)
  15974. : BasicDeviceConfigurationWidget(model, index), boundsLayout(new QStackedLayout)
  15975. {
  15976. QVBoxLayout *layout = new QVBoxLayout;
  15977. QFormLayout *addressLayout = new QFormLayout;
  15978. ShortHexSpinBox *readAddress = new ShortHexSpinBox;
  15979. ShortHexSpinBox *writeAddress = new ShortHexSpinBox;
  15980. addressLayout->addRow(tr("Function 0x04 Read Set Value Address:"), readAddress);
  15981. addressLayout->addRow(tr("Function 0x06 Write Set Value Address:"), writeAddress);
  15982. layout->addLayout(addressLayout);
  15983. QCheckBox *fixedRange = new QCheckBox(tr("Fixed Set Value Range"));
  15984. layout->addWidget(fixedRange);
  15985. QWidget *queriedRangePlaceholder = new QWidget(this);
  15986. QFormLayout *queriedRangeLayout = new QFormLayout;
  15987. ShortHexSpinBox *lowerAddress = new ShortHexSpinBox;
  15988. ShortHexSpinBox *upperAddress = new ShortHexSpinBox;
  15989. queriedRangeLayout->addRow(tr("Function 0x03 Minimum Set Value Address"),
  15990. lowerAddress);
  15991. queriedRangeLayout->addRow(tr("Function 0x03 Maximum Set Value Address"),
  15992. upperAddress);
  15993. queriedRangePlaceholder->setLayout(queriedRangeLayout);
  15994. boundsLayout->addWidget(queriedRangePlaceholder);
  15995. QWidget *fixedRangePlaceholder = new QWidget(this);
  15996. QFormLayout *fixedRangeLayout = new QFormLayout;
  15997. QLineEdit *fixedLower = new QLineEdit;
  15998. QLineEdit *fixedUpper = new QLineEdit;
  15999. fixedRangeLayout->addRow(tr("Minimum Set Value:"), fixedLower);
  16000. fixedRangeLayout->addRow(tr("Maximum Set Value:"), fixedUpper);
  16001. fixedRangePlaceholder->setLayout(fixedRangeLayout);
  16002. boundsLayout->addWidget(fixedRangePlaceholder);
  16003. layout->addLayout(boundsLayout);
  16004. @<Get device configuration data for current node@>@;
  16005. for(int i = 0; i < configData.size(); i++)
  16006. {
  16007. node = configData.at(i).toElement();
  16008. if(node.attribute("name") == "readaddress")
  16009. {
  16010. readAddress->setValue(node.attribute("value").toInt());
  16011. }
  16012. else if(node.attribute("name") == "writeaddress")
  16013. {
  16014. writeAddress->setValue(node.attribute("value").toInt());
  16015. }
  16016. else if(node.attribute("name") == "fixedrange")
  16017. {
  16018. if(node.attribute("value") == "true")
  16019. {
  16020. fixedRange->setCheckState(Qt::Checked);
  16021. }
  16022. else if(node.attribute("value") == "false")
  16023. {
  16024. fixedRange->setCheckState(Qt::Unchecked);
  16025. }
  16026. }
  16027. else if(node.attribute("name") == "fixedlower")
  16028. {
  16029. fixedLower->setText(node.attribute("value"));
  16030. }
  16031. else if(node.attribute("name") == "fixedupper")
  16032. {
  16033. fixedUpper->setText(node.attribute("value"));
  16034. }
  16035. else if(node.attribute("name") == "loweraddress")
  16036. {
  16037. lowerAddress->setValue(node.attribute("value").toInt());
  16038. }
  16039. else if(node.attribute("name") == "upperaddress")
  16040. {
  16041. upperAddress->setValue(node.attribute("value").toInt());
  16042. }
  16043. }
  16044. updateReadAddress(readAddress->value());
  16045. updateWriteAddress(writeAddress->value());
  16046. updateFixedRange(fixedRange->isChecked());
  16047. updateLower(fixedLower->text());
  16048. updateUpper(fixedUpper->text());
  16049. updateLowerAddress(lowerAddress->value());
  16050. updateUpperAddress(upperAddress->value());
  16051. connect(readAddress, SIGNAL(valueChanged(int)),
  16052. this, SLOT(updateReadAddress(int)));
  16053. connect(writeAddress, SIGNAL(valueChanged(int)),
  16054. this, SLOT(updateWriteAddress(int)));
  16055. connect(fixedRange, SIGNAL(toggled(bool)), this, SLOT(updateFixedRange(bool)));
  16056. connect(fixedLower, SIGNAL(textChanged(QString)),
  16057. this, SLOT(updateLower(QString)));
  16058. connect(fixedUpper, SIGNAL(textChanged(QString)),
  16059. this, SLOT(updateUpper(QString)));
  16060. connect(lowerAddress, SIGNAL(valueChanged(int)),
  16061. this, SLOT(updateLowerAddress(int)));
  16062. connect(upperAddress, SIGNAL(valueChanged(int)),
  16063. this, SLOT(updateUpperAddress(int)));
  16064. setLayout(layout);
  16065. }
  16066. void ModbusRtuDeviceTSvConfWidget::updateReadAddress(int newAddress)
  16067. {
  16068. updateAttribute("readaddress", QString("%1").arg(newAddress));
  16069. }
  16070. void ModbusRtuDeviceTSvConfWidget::updateWriteAddress(int newAddress)
  16071. {
  16072. updateAttribute("writeaddress", QString("%1").arg(newAddress));
  16073. }
  16074. void ModbusRtuDeviceTSvConfWidget::updateFixedRange(bool fixed)
  16075. {
  16076. if(fixed)
  16077. {
  16078. updateAttribute("fixedrange", "true");
  16079. boundsLayout->setCurrentIndex(1);
  16080. }
  16081. else
  16082. {
  16083. updateAttribute("fixedrange", "false");
  16084. boundsLayout->setCurrentIndex(0);
  16085. }
  16086. }
  16087. void ModbusRtuDeviceTSvConfWidget::updateLower(const QString &lower)
  16088. {
  16089. updateAttribute("fixedlower", lower);
  16090. }
  16091. void ModbusRtuDeviceTSvConfWidget::updateUpper(const QString &upper)
  16092. {
  16093. updateAttribute("fixedupper", upper);
  16094. }
  16095. void ModbusRtuDeviceTSvConfWidget::updateLowerAddress(int newAddress)
  16096. {
  16097. updateAttribute("loweraddress", QString("%1").arg(newAddress));
  16098. }
  16099. void ModbusRtuDeviceTSvConfWidget::updateUpperAddress(int newAddress)
  16100. {
  16101. updateAttribute("upperaddress", QString("%1").arg(newAddress));
  16102. }
  16103. @ The configuration widgets need to be registered.
  16104. @<Register device configuration widgets@>=
  16105. app.registerDeviceConfigurationWidget("modbusrtuport", ModbusRtuPortConfWidget::staticMetaObject);
  16106. app.registerDeviceConfigurationWidget("modbusrtudevice", ModbusRtuDeviceConfWidget::staticMetaObject);
  16107. app.registerDeviceConfigurationWidget("modbustemperaturepv", ModbusRtuDeviceTPvConfWidget::staticMetaObject);
  16108. app.registerDeviceConfigurationWidget("modbustemperaturesv", ModbusRtuDeviceTSvConfWidget::staticMetaObject);
  16109. @ A |NodeInserter| for the driver configuration widget is also needed. Note
  16110. that this is temporarily disabled. These configuration widgets will become
  16111. useful when I rearchitect the Modbus RTU support in a future release.
  16112. @<Register top level device configuration nodes@>=
  16113. #if 0
  16114. inserter = new NodeInserter(tr("Modbus RTU Port"), tr("Modbus RTU Port"), "modbusrtuport", NULL);
  16115. topLevelNodeInserters.append(inserter);
  16116. #endif
  16117. @** Configuration of Annotation Controls.
  16118. \noindent Aside from the details of hardware devices, the logging view must
  16119. also be able to set up log annotation controls. A few different control types
  16120. are offered. These include simple push buttons which insert a fixed annotation
  16121. when activated, push buttons which insert a value that includes a number which
  16122. is incremented every time the button is pressed, free text entry fields, and
  16123. numeric entry fields.
  16124. The basic push button control should allow configuration of both the button
  16125. text and the annotation text.
  16126. @<Class declarations@>=
  16127. class AnnotationButtonConfWidget : public BasicDeviceConfigurationWidget
  16128. {
  16129. @[Q_OBJECT@]@;
  16130. public:@/
  16131. @[Q_INVOKABLE@]@, AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16132. @[private slots@]:@/
  16133. void updateButtonText(const QString &text);
  16134. void updateAnnotationText(const QString &text);
  16135. };
  16136. @ The constructor sets up the controls for editing this data.
  16137. @<AnnotationButtonConfWidget implementation@>=
  16138. AnnotationButtonConfWidget::AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16139. : BasicDeviceConfigurationWidget(model, index)
  16140. {
  16141. QFormLayout *layout = new QFormLayout;
  16142. QLineEdit *buttonTextEdit = new QLineEdit;
  16143. QLineEdit *annotationTextEdit = new QLineEdit;
  16144. layout->addRow(tr("Button Text:"), buttonTextEdit);
  16145. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  16146. @<Get device configuration data for current node@>@;
  16147. for(int i = 0; i < configData.size(); i++)
  16148. {
  16149. node = configData.at(i).toElement();
  16150. if(node.attribute("name") == "buttontext")
  16151. {
  16152. buttonTextEdit->setText(node.attribute("value"));
  16153. }
  16154. else if(node.attribute("name") == "annotationtext")
  16155. {
  16156. annotationTextEdit->setText(node.attribute("value"));
  16157. }
  16158. }
  16159. updateButtonText(buttonTextEdit->text());
  16160. updateAnnotationText(annotationTextEdit->text());
  16161. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  16162. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  16163. setLayout(layout);
  16164. }
  16165. @ The slots are implemented trivially.
  16166. @<AnnotationButtonConfWidget implementation@>=
  16167. void AnnotationButtonConfWidget::updateButtonText(const QString &text)
  16168. {
  16169. updateAttribute("buttontext", text);
  16170. }
  16171. void AnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  16172. {
  16173. updateAttribute("annotationtext", text);
  16174. }
  16175. @ The control must be registered.
  16176. @<Register device configuration widgets@>=
  16177. app.registerDeviceConfigurationWidget("annotationbutton", AnnotationButtonConfWidget::staticMetaObject);
  16178. @ Closely related to the previous control is one which provides parameterized
  16179. text. Technically this is not needed as both this and the previous
  16180. configuration control map to the same widget in the logging view and
  16181. parameterized annotation text can be used with either. The reason for
  16182. separating these is to indicate that it should be possible to change the text
  16183. and reset the number without altering the default configuration or requiring a
  16184. reinitialization of the logging view.
  16185. @<Class declarations@>=
  16186. class ReconfigurableAnnotationButtonConfWidget : public BasicDeviceConfigurationWidget@/
  16187. {@/
  16188. @[Q_OBJECT@]@;
  16189. public:@/
  16190. Q_INVOKABLE ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16191. @[private slots@]:@/
  16192. void updateButtonText(const QString &text);
  16193. void updateAnnotationText(const QString &text);
  16194. };
  16195. @ The key difference in implementation is the addition of some documentation on
  16196. how to specify a numeric placeholder in the annotation text.
  16197. @<AnnotationButtonConfWidget implementation@>=
  16198. ReconfigurableAnnotationButtonConfWidget::ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16199. : BasicDeviceConfigurationWidget(model, index)
  16200. {
  16201. QFormLayout *layout = new QFormLayout;
  16202. QLineEdit *buttonTextEdit = new QLineEdit;
  16203. QLineEdit *annotationTextEdit = new QLineEdit;
  16204. layout->addRow(tr("Button Text:"), buttonTextEdit);
  16205. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  16206. @<Get device configuration data for current node@>@;
  16207. for(int i = 0; i < configData.size(); i++)
  16208. {
  16209. node = configData.at(i).toElement();
  16210. if(node.attribute("name") == "buttontext")
  16211. {
  16212. buttonTextEdit->setText(node.attribute("value"));
  16213. }
  16214. else if(node.attribute("name") == "annotationtext")
  16215. {
  16216. annotationTextEdit->setText(node.attribute("value"));
  16217. }
  16218. }
  16219. updateButtonText(buttonTextEdit->text());
  16220. updateAnnotationText(annotationTextEdit->text());
  16221. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  16222. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  16223. QTextEdit *documentation = new QTextEdit;
  16224. 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."));
  16225. documentation->setReadOnly(true);
  16226. layout->addRow("", documentation);
  16227. setLayout(layout);
  16228. }
  16229. void ReconfigurableAnnotationButtonConfWidget::updateButtonText(const QString &text)
  16230. {
  16231. updateAttribute("buttontext", text);
  16232. }
  16233. void ReconfigurableAnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  16234. {
  16235. updateAttribute("annotationtext", text);
  16236. }
  16237. @ The control must be registered as usual.
  16238. @<Register device configuration widgets@>=
  16239. app.registerDeviceConfigurationWidget("reconfigurablebutton", ReconfigurableAnnotationButtonConfWidget::staticMetaObject);
  16240. @ While it is generally better to have all measurements logged automatically,
  16241. many roasters would like to keep track of infrequently altered control
  16242. variables which have not been set up for automated logging. A reading from the
  16243. manometer after a fuel adjustment, for example, is frequently not available by
  16244. automated means. In cases such as this, providing for numeric annotation entry
  16245. may be desired. The |AnnotationSpinBox| provides for this. There are a few
  16246. details that are important in this. First is a label to better indicate to the
  16247. operator what values in this control represent. The range of allowed values and
  16248. the number of decimal places is important. This control also allows the
  16249. specification of text to precede and/or follow the numeric value and this must
  16250. be configurable.
  16251. @<Class declarations@>=
  16252. class NoteSpinConfWidget : public BasicDeviceConfigurationWidget
  16253. {
  16254. @[Q_OBJECT@]@;
  16255. public:@/
  16256. @[Q_INVOKABLE@]@, NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16257. @[private slots@]:@/
  16258. void updateLabel(const QString &text);
  16259. void updateMinimum(const QString &minimum);
  16260. void updateMaximum(const QString &maximum);
  16261. void updatePrecision(int precision);
  16262. void updatePretext(const QString &text);
  16263. void updatePosttext(const QString &text);
  16264. };
  16265. @ There is nothing new in the implementation of note.
  16266. @<NoteSpinConfWidget implementation@>=
  16267. NoteSpinConfWidget::NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16268. : BasicDeviceConfigurationWidget(model, index)
  16269. {
  16270. QFormLayout *layout = new QFormLayout;
  16271. QLineEdit *labelEdit = new QLineEdit;
  16272. layout->addRow(tr("Control Label: "), labelEdit);
  16273. QLineEdit *minimumEdit = new QLineEdit;
  16274. layout->addRow(tr("Minimum Value: "), minimumEdit);
  16275. QLineEdit *maximumEdit = new QLineEdit;
  16276. layout->addRow(tr("Maximum Value: "), maximumEdit);
  16277. QSpinBox *precisionEdit = new QSpinBox;
  16278. precisionEdit->setMinimum(0);
  16279. precisionEdit->setMaximum(9);
  16280. layout->addRow(tr("Precision"), precisionEdit);
  16281. QLineEdit *pretext = new QLineEdit;
  16282. layout->addRow(tr("Prefix text"), pretext);
  16283. QLineEdit *posttext = new QLineEdit;
  16284. layout->addRow(tr("Suffix text"), posttext);
  16285. @<Get device configuration data for current node@>@;
  16286. for(int i = 0; i < configData.size(); i++)
  16287. {
  16288. node = configData.at(i).toElement();
  16289. if(node.attribute("name") == "label")
  16290. {
  16291. labelEdit->setText(node.attribute("value"));
  16292. }
  16293. else if(node.attribute("name") == "minimum")
  16294. {
  16295. minimumEdit->setText(node.attribute("value"));
  16296. }
  16297. else if(node.attribute("name") == "maximum")
  16298. {
  16299. maximumEdit->setText(node.attribute("value"));
  16300. }
  16301. else if(node.attribute("name") == "precision")
  16302. {
  16303. precisionEdit->setValue(node.attribute("value").toInt());
  16304. }
  16305. else if(node.attribute("name") == "pretext")
  16306. {
  16307. pretext->setText(node.attribute("value"));
  16308. }
  16309. else if(node.attribute("name") == "posttext")
  16310. {
  16311. posttext->setText(node.attribute("value"));
  16312. }
  16313. }
  16314. updateLabel(labelEdit->text());
  16315. updateMinimum(minimumEdit->text());
  16316. updateMaximum(maximumEdit->text());
  16317. updatePrecision(precisionEdit->value());
  16318. updatePretext(pretext->text());
  16319. updatePosttext(posttext->text());
  16320. connect(labelEdit, SIGNAL(textEdited(QString)), this, SLOT(updateLabel(QString)));
  16321. connect(minimumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMinimum(QString)));
  16322. connect(maximumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMaximum(QString)));
  16323. connect(precisionEdit, SIGNAL(valueChanged(int)), this, SLOT(updatePrecision(int)));
  16324. connect(pretext, SIGNAL(textEdited(QString)), this, SLOT(updatePretext(QString)));
  16325. connect(posttext, SIGNAL(textEdited(QString)), this, SLOT(updatePosttext(QString)));
  16326. setLayout(layout);
  16327. }
  16328. void NoteSpinConfWidget::updateLabel(const QString &text)
  16329. {
  16330. updateAttribute("label", text);
  16331. }
  16332. void NoteSpinConfWidget::updateMinimum(const QString &minimum)
  16333. {
  16334. updateAttribute("minimum", minimum);
  16335. }
  16336. void NoteSpinConfWidget::updateMaximum(const QString &maximum)
  16337. {
  16338. updateAttribute("maximum", maximum);
  16339. }
  16340. void NoteSpinConfWidget::updatePrecision(int precision)
  16341. {
  16342. updateAttribute("precision", QString("%1").arg(precision));
  16343. }
  16344. void NoteSpinConfWidget::updatePretext(const QString &text)
  16345. {
  16346. updateAttribute("pretext", text);
  16347. }
  16348. void NoteSpinConfWidget::updatePosttext(const QString &text)
  16349. {
  16350. updateAttribute("posttext", text);
  16351. }
  16352. @ Configuration widget registration is as usual.
  16353. @<Register device configuration widgets@>=
  16354. app.registerDeviceConfigurationWidget("annotationspinbox", NoteSpinConfWidget::staticMetaObject);
  16355. @i freeannotation.w
  16356. @i settings.w
  16357. @** Communicating with a Device through Modbus RTU.
  16358. \noindent The classes described here need to be further generalized to support
  16359. communications with multiple devices on the same port. The interface is based
  16360. on the |DAQ| class but extended to support additional functionality.
  16361. @<Class declarations@>=
  16362. class ModbusRTUDevice : public QObject
  16363. {
  16364. @[Q_OBJECT@]@;
  16365. public:@/
  16366. ModbusRTUDevice(DeviceTreeModel *model, const QModelIndex &index);
  16367. ~ModbusRTUDevice();
  16368. void queueMessage(QByteArray request, QObject *object, const char *callback);
  16369. @[Q_INVOKABLE@,@, double@]@, SVLower();@t\2\2@>@/
  16370. @[Q_INVOKABLE@,@, double@]@, SVUpper();@t\2\2@>@/
  16371. @[Q_INVOKABLE@,@, int@]@, decimals();@t\2\2@>@/
  16372. QList<Channel*> channels;@/
  16373. @[public slots@]:@/
  16374. void outputSV(double sv);@/
  16375. signals:@/
  16376. void SVLowerChanged(double);
  16377. void SVUpperChanged(double);
  16378. void SVDecimalChanged(int);
  16379. void queueEmpty();@/
  16380. @[private slots@]:@/
  16381. void dataAvailable();
  16382. void sendNextMessage();
  16383. void decimalResponse(QByteArray response);
  16384. void unitResponse(QByteArray response);
  16385. void svlResponse(QByteArray response);
  16386. void svuResponse(QByteArray response);
  16387. void requestMeasurement();
  16388. void mResponse(QByteArray response);
  16389. void ignore(QByteArray response);
  16390. void timeout();@/
  16391. private:@/
  16392. QextSerialPort *port;
  16393. QByteArray responseBuffer;
  16394. QList<QByteArray> messageQueue;
  16395. QList<QObject *> retObjQueue;
  16396. QList<char *> callbackQueue;
  16397. quint16 calculateCRC(QByteArray data);
  16398. QTimer *messageDelayTimer;
  16399. QTimer *commTimeout;
  16400. int delayTime;
  16401. char station;
  16402. int decimalPosition;
  16403. int valueF;
  16404. int valueC;
  16405. bool unitIsF;
  16406. double outputSVLower;
  16407. double outputSVUpper;
  16408. QByteArray outputSVStub;
  16409. QByteArray pvStub;
  16410. QByteArray svStub;
  16411. QByteArray mStub;
  16412. quint16 pvaddress;
  16413. quint16 svaddress;
  16414. bool svenabled;
  16415. bool readingsv;
  16416. double savedpv;
  16417. bool waiting;
  16418. };
  16419. @ The constructor reads its configuration from the configuration sub-tree of the
  16420. port node. This was adapted from a prototype implementation which used
  16421. |QSettings| to store this data. Note that this will only process the first
  16422. device specified on the port, the first process value on that device, and the
  16423. first set value on that device. A much more versatile architecture has been
  16424. planned for a future release which allows multiple devices per bus and
  16425. arbitrarily many monitored addresses per device. Communications are initiated
  16426. immediately upon construction.
  16427. @<ModbusRTUDevice implementation@>=
  16428. ModbusRTUDevice::ModbusRTUDevice(DeviceTreeModel *model,@| const QModelIndex &index)
  16429. : QObject(NULL), messageDelayTimer(new QTimer), commTimeout(new QTimer), unitIsF(@[true@]), readingsv(@[false@]),
  16430. waiting(@[false@])@/
  16431. {@/
  16432. QDomElement portReferenceElement = model->referenceElement(model->data(index,
  16433. Qt::UserRole).toString());
  16434. QDomNodeList portConfigData = portReferenceElement.elementsByTagName("attribute");
  16435. QDomElement node;
  16436. QVariantMap attributes;
  16437. for(int i = 0; i < portConfigData.size(); i++)
  16438. {
  16439. node = portConfigData.at(i).toElement();
  16440. attributes.insert(node.attribute("name"), node.attribute("value"));
  16441. }
  16442. port = new QextSerialPort(attributes.value("port").toString(),
  16443. QextSerialPort::EventDriven);
  16444. int baudRate = attributes.value("baud").toInt();
  16445. port->setBaudRate((BaudRateType)baudRate);
  16446. double temp = ((double)(1) / (double)(baudRate)) * 48;
  16447. delayTime = (int)(temp * 3000);
  16448. messageDelayTimer->setSingleShot(true);
  16449. commTimeout->setSingleShot(true);
  16450. connect(messageDelayTimer, SIGNAL(timeout()), this, SLOT(sendNextMessage()));
  16451. connect(commTimeout, SIGNAL(timeout()), this, SLOT(timeout()));
  16452. port->setDataBits(DATA_8);
  16453. port->setParity((ParityType)attributes.value("parity").toInt());
  16454. port->setStopBits((StopBitsType)attributes.value("stop").toInt());
  16455. port->setFlowControl((FlowType)attributes.value("flow").toInt());
  16456. connect(port, SIGNAL(readyRead()), this, SLOT(dataAvailable()));
  16457. port->open(QIODevice::ReadWrite);
  16458. station = (char)attributes.value("station").toInt();
  16459. if(attributes.value("decimalQuery") == "true")
  16460. {
  16461. decimalPosition = 0;
  16462. QByteArray message;
  16463. message.append(station);
  16464. message.append((char)0x03);
  16465. quint16 address = (quint16)attributes.value("decimalAddress").toInt();
  16466. char *addressBytes = (char*)&address;
  16467. message.append(addressBytes[1]);
  16468. message.append(addressBytes[0]);
  16469. message.append((char)0x00);
  16470. message.append((char)0x01);
  16471. queueMessage(message, this, "decimalResponse(QByteArray)");
  16472. }
  16473. else
  16474. {
  16475. decimalPosition = attributes.value("decimalPosition").toInt();
  16476. }
  16477. valueF = attributes.value("valueF").toInt();
  16478. valueC = attributes.value("valueC").toInt();
  16479. if(attributes.value("unitQuery") == "true")
  16480. {
  16481. QByteArray message;
  16482. message.append(station);
  16483. message.append((char)0x03);
  16484. quint16 address = (quint16)attributes.value("unitAddress").toInt();
  16485. char *addressBytes = (char*)&address;
  16486. message.append(addressBytes[1]);
  16487. message.append(addressBytes[0]);
  16488. message.append((char)0x00);
  16489. message.append((char)0x01);
  16490. queueMessage(message, this, "unitResponse(QByteArray)");
  16491. }
  16492. else
  16493. {
  16494. if(attributes.value("fixedUnit") == "Celsius")
  16495. {
  16496. unitIsF = @[false@];
  16497. }
  16498. }
  16499. if(attributes.value("sVWritable") == "true")
  16500. {
  16501. if(attributes.value("deviceLimit") == "true")
  16502. {
  16503. QByteArray lmessage;
  16504. lmessage.append(station);
  16505. lmessage.append((char)0x03);
  16506. quint16 laddress = (quint16)attributes.value("sVLowerAddr").toInt();
  16507. char *addressBytes = (char*)&laddress;
  16508. lmessage.append(addressBytes[1]);
  16509. lmessage.append(addressBytes[0]);
  16510. lmessage.append((char)0x00);
  16511. lmessage.append((char)0x01);
  16512. queueMessage(lmessage, this, "svlResponse(QByteArray)");
  16513. QByteArray umessage;
  16514. umessage.append(station);
  16515. umessage.append((char)0x03);
  16516. quint16 uaddress = (quint16)attributes.value("sVUpperAddr").toInt();
  16517. addressBytes = (char*)&uaddress;
  16518. umessage.append(addressBytes[1]);
  16519. umessage.append(addressBytes[0]);
  16520. umessage.append((char)0x00);
  16521. umessage.append((char)0x01);
  16522. queueMessage(umessage, this, "svuResponse(QByteArray)");
  16523. }
  16524. else
  16525. {
  16526. outputSVLower = attributes.value("sVLower").toDouble();
  16527. outputSVUpper = attributes.value("sVUpper").toDouble();
  16528. }
  16529. outputSVStub.append(station);
  16530. outputSVStub.append((char)0x06);
  16531. quint16 address = (quint16)attributes.value("sVOutputAddr").toInt();
  16532. char *addressBytes = (char*)&address;
  16533. outputSVStub.append(addressBytes[1]);
  16534. outputSVStub.append(addressBytes[0]);
  16535. }
  16536. Channel *pv = new Channel;
  16537. channels.append(pv);
  16538. pvStub.append(station);
  16539. pvStub.append((char)0x04);
  16540. pvaddress = (quint16)attributes.value("pVAddress").toInt();
  16541. char *pvac = (char*)&pvaddress;
  16542. pvStub.append(pvac[1]);
  16543. pvStub.append(pvac[0]);
  16544. pvStub.append((char)0x00);
  16545. pvStub.append((char)0x01);
  16546. svenabled = attributes.value("sVEnabled").toBool();
  16547. if(svenabled)
  16548. {
  16549. Channel *sv = new Channel;
  16550. channels.append(sv);
  16551. svStub.append(station);
  16552. svStub.append((char)0x04);
  16553. svaddress = (quint16)attributes.value("sVReadAddress").toInt();
  16554. char *svac = (char*)&svaddress;
  16555. svStub.append(svac[1]);
  16556. svStub.append(svac[0]);
  16557. svStub.append((char)0x00);
  16558. svStub.append((char)0x01);
  16559. if(svaddress - pvaddress == 1)
  16560. {
  16561. mStub.append(station);
  16562. mStub.append((char)0x04);
  16563. mStub.append(pvac[1]);
  16564. mStub.append(pvac[0]);
  16565. mStub.append((char)0x00);
  16566. mStub.append((char)0x02);
  16567. }
  16568. }
  16569. connect(this, SIGNAL(queueEmpty()), this, SLOT(requestMeasurement()));
  16570. requestMeasurement();
  16571. }
  16572. double ModbusRTUDevice::SVLower()
  16573. {
  16574. return outputSVLower;
  16575. }
  16576. double ModbusRTUDevice::SVUpper()
  16577. {
  16578. return outputSVUpper;
  16579. }
  16580. int ModbusRTUDevice::decimals()
  16581. {
  16582. return decimalPosition;
  16583. }
  16584. void ModbusRTUDevice::decimalResponse(QByteArray response)
  16585. {
  16586. quint16 temp;
  16587. char *tchar = (char*)&temp;
  16588. tchar[1] = response.at(3);
  16589. tchar[0] = response.at(4);
  16590. decimalPosition = temp;
  16591. emit SVDecimalChanged(decimalPosition);
  16592. }
  16593. void ModbusRTUDevice::unitResponse(QByteArray response)
  16594. {
  16595. quint16 temp;
  16596. char *tchar = (char*)&temp;
  16597. tchar[1] = response.at(3);
  16598. tchar[0] = response.at(4);
  16599. int value = temp;
  16600. if(value == valueF)
  16601. {
  16602. unitIsF = @[true@];
  16603. }
  16604. else
  16605. {
  16606. unitIsF = @[false@];
  16607. }
  16608. }
  16609. void ModbusRTUDevice::svlResponse(QByteArray response)
  16610. {
  16611. quint16 temp;
  16612. char *tchar = (char*)&temp;
  16613. tchar[1] = response.at(3);
  16614. tchar[0] = response.at(4);
  16615. outputSVLower = (double)temp;
  16616. for(int i = 0; i < decimalPosition; i++)
  16617. {
  16618. outputSVLower /= 10;
  16619. }
  16620. emit SVLowerChanged(outputSVLower);
  16621. }
  16622. void ModbusRTUDevice::svuResponse(QByteArray response)
  16623. {
  16624. quint16 temp;
  16625. char *tchar = (char*)&temp;
  16626. tchar[1] = response.at(3);
  16627. tchar[0] = response.at(4);
  16628. outputSVUpper = (double)temp;
  16629. for(int i = 0; i < decimalPosition; i++)
  16630. {
  16631. outputSVUpper /= 10;
  16632. }
  16633. emit SVUpperChanged(outputSVUpper);
  16634. }
  16635. void ModbusRTUDevice::requestMeasurement()
  16636. {
  16637. if(mStub.length() > 0)
  16638. {
  16639. queueMessage(mStub, this, "mResponse(QByteArray)");
  16640. }
  16641. else
  16642. {
  16643. queueMessage(pvStub, this, "mResponse(QByteArray)");
  16644. if(svenabled)
  16645. {
  16646. queueMessage(svStub, this, "mResponse(QByteArray)");
  16647. }
  16648. }
  16649. }
  16650. void ModbusRTUDevice::mResponse(QByteArray response)
  16651. {
  16652. QTime time = QTime::currentTime();
  16653. if(response.at(2) == 0x04)
  16654. {
  16655. @<Process PV and SV@>@;
  16656. }
  16657. else
  16658. {
  16659. @<Process PV or SV@>@;
  16660. }
  16661. }
  16662. @ There are two ways that we might request measurement data. All of the
  16663. devices I'@q'@>ve seen documented provide function 0x4 addresses for PV and SV
  16664. such that SV can be obtained from the address immediately after the address
  16665. from which we obtain PV. In this case we request both values at the same time.
  16666. @<Process PV and SV@>=
  16667. quint16 pv;
  16668. quint16 sv;
  16669. char *pvBytes = (char*)&pv;
  16670. char *svBytes = (char*)&sv;
  16671. pvBytes[1] = response.at(3);
  16672. pvBytes[0] = response.at(4);
  16673. svBytes[1] = response.at(5);
  16674. svBytes[0] = response.at(6);
  16675. double pvOut = (double)pv;
  16676. double svOut = (double)sv;
  16677. for(int i = 0; i < decimalPosition; i++)
  16678. {
  16679. pvOut /= 10;
  16680. svOut /= 10;
  16681. }
  16682. if(!unitIsF)
  16683. {
  16684. pvOut = pvOut * 9 / 5 + 32;
  16685. svOut = svOut * 9 / 5 + 32;
  16686. }
  16687. Measurement pvm(pvOut, time, Units::Fahrenheit);
  16688. Measurement svm(svOut, time, Units::Fahrenheit);
  16689. channels.at(0)->input(pvm);
  16690. channels.at(1)->input(svm);
  16691. @ When not measuring PV and SV at the same time, there are two possibilities.
  16692. One possibility is that SV is not enabled and we will only be reading from PV.
  16693. The other possibility is that we are alternating between reading PV and SV.
  16694. @<Process PV or SV@>=
  16695. quint16 value;
  16696. char *valueBytes = (char*)&value;
  16697. valueBytes[1] = response.at(3);
  16698. valueBytes[0] = response.at(4);
  16699. double valueOut = (double)value;
  16700. for(int i = 0; i < decimalPosition; i++)
  16701. {
  16702. valueOut /= 10;
  16703. }
  16704. if(!unitIsF)
  16705. {
  16706. valueOut = valueOut * 9 / 5 + 32;
  16707. }
  16708. if(!svenabled)
  16709. {
  16710. Measurement vm(valueOut, time, Units::Fahrenheit);
  16711. channels.at(0)->input(vm);
  16712. }
  16713. else
  16714. {
  16715. if(readingsv)
  16716. {
  16717. Measurement pvm(savedpv, time, Units::Fahrenheit);
  16718. Measurement svm(valueOut, time, Units::Fahrenheit);
  16719. channels.at(0)->input(pvm);
  16720. channels.at(1)->input(svm);
  16721. readingsv = false;
  16722. }
  16723. else
  16724. {
  16725. savedpv = valueOut;
  16726. readingsv = true;
  16727. }
  16728. }
  16729. @ The destructor should close the port.
  16730. @<ModbusRTUDevice implementation@>=
  16731. ModbusRTUDevice::~ModbusRTUDevice()
  16732. {
  16733. commTimeout->stop();
  16734. messageDelayTimer->stop();
  16735. port->close();
  16736. }
  16737. @ When data is available it should be read into a buffer. The start of the
  16738. buffer should always be the start of a response and there should never be
  16739. more than one response in the buffer at a time. It is, however, likely that
  16740. this buffer will have incomplete data. This means that we must determine when
  16741. the full response is available before passing the complete response along to
  16742. the appropriate method. If the response has not been received in full, nothing
  16743. is done. We'@q'@>ll be notified of more data shortly.
  16744. When the message we see the response for was queued, a callback was also
  16745. registered to handle the response. Once we have the complete message, we pass
  16746. the response along to the callback that was registered for that message,
  16747. remove the message and callback information from the message queue, and start
  16748. a timer which will trigger sending the next message after a safe amount of
  16749. time has passed.
  16750. If a response is received with an invalid CRC, we do not pass that message
  16751. out. Instead, the message handling queues are kept as they are and the previous
  16752. command will be sent again once the message delay timer is finished.
  16753. @<ModbusRTUDevice implementation@>=
  16754. void ModbusRTUDevice::dataAvailable()
  16755. {
  16756. if(messageDelayTimer->isActive())
  16757. {
  16758. messageDelayTimer->stop();
  16759. }
  16760. responseBuffer.append(port->readAll());
  16761. @<Check Modbus RTU message size@>@;
  16762. commTimeout->stop();
  16763. if(calculateCRC(responseBuffer) == 0)
  16764. {
  16765. QObject *object = retObjQueue.at(0);
  16766. char *method = callbackQueue.at(0);
  16767. QMetaMethod metamethod = @| object->metaObject()->
  16768. method(object->metaObject()->
  16769. indexOfMethod(@|QMetaObject::normalizedSignature(method)));
  16770. metamethod.invoke(object, Qt::QueuedConnection,
  16771. Q_ARG(QByteArray, responseBuffer));
  16772. messageQueue.removeAt(0);
  16773. retObjQueue.removeAt(0);
  16774. callbackQueue.removeAt(0);
  16775. }
  16776. else
  16777. {
  16778. qDebug() << "CRC failed";
  16779. }
  16780. messageDelayTimer->start(delayTime);
  16781. waiting = @[false@];
  16782. responseBuffer.clear();
  16783. }
  16784. @ In Modbus RTU, a response message starts with one byte identifying the device
  16785. the message was sent from, one byte indicating the function, a variable number
  16786. of bytes with the response data, and two bytes used to verify that the response
  16787. was correctly received. In the event of a normal response, messages will be at
  16788. least six bytes long, but in the event of an error it is possible for a message
  16789. to be five bytes long.
  16790. Messages with a function number of 0x01 or 0x02 will be 6 bytes in length.
  16791. Messages with a function number of 0x03 or 0x04 will be at least 7 bytes in
  16792. length with the total length determined by the sum of 5 and the value in the
  16793. fifth byte. Messages with a function number of 0x05, 0x06, or 0x10 will be 8
  16794. bytes in length. Messages with a function number greater than 0x80 will be five
  16795. bytes in length.
  16796. @<Check Modbus RTU message size@>=
  16797. if(responseBuffer.size() < 5)
  16798. {
  16799. return;
  16800. }
  16801. switch(responseBuffer.at(1))
  16802. {
  16803. case 0x01:
  16804. case 0x02:
  16805. if(responseBuffer.size() < 6)
  16806. {
  16807. return;
  16808. }
  16809. responseBuffer = responseBuffer.left(6);
  16810. break;
  16811. case 0x03:
  16812. case 0x04:
  16813. if(responseBuffer.size() < 5 + responseBuffer.at(2))
  16814. {
  16815. return;
  16816. }
  16817. responseBuffer = responseBuffer.left(5 + responseBuffer.at(2));
  16818. break;
  16819. case 0x05:
  16820. case 0x06:
  16821. case 0x10:
  16822. if(responseBuffer.size() < 8)
  16823. {
  16824. return;
  16825. }
  16826. responseBuffer = responseBuffer.left(8);
  16827. break;
  16828. }
  16829. @ When sending and receiving messages, it is necessary to calculate a 16 bit
  16830. cyclic redundancy check code. The algorithm used to calculate this is specified
  16831. by the Modbus RTU protocol documentation. When sending a message, |data| should
  16832. be the message to send except for the CRC bytes which will be appended once
  16833. this method calculates them. When receiving a message, passing the complete
  16834. message back through this method should result in a return value of |0|. Any
  16835. other value indicates an error.
  16836. @<ModbusRTUDevice implementation@>=
  16837. quint16 ModbusRTUDevice::calculateCRC(QByteArray data)
  16838. {
  16839. quint16 retval = 0xFFFF;
  16840. int i = 0;
  16841. while(i < data.size())
  16842. {
  16843. retval ^= 0x00FF & (quint16)data.at(i);
  16844. for(int j = 0; j < 8; j++)
  16845. {
  16846. if(retval & 1)
  16847. {
  16848. retval = (retval >> 1) ^ 0xA001;
  16849. }
  16850. else
  16851. {
  16852. retval >>= 1;
  16853. }
  16854. }
  16855. i++;
  16856. }
  16857. return retval;
  16858. }
  16859. @ When preparing an instance of ModbusRTUDevice, several messages may need to
  16860. be sent to the device in order to determine important details such as how
  16861. measurement data should be interpreted. During normal operation, messages
  16862. might be sent interactively between regular messages to acquire data. When
  16863. queueing a message, we also specify an object and method the response should be
  16864. sent to.
  16865. @<ModbusRTUDevice implementation@>=
  16866. void ModbusRTUDevice::queueMessage(QByteArray request, QObject *object,
  16867. const char *callback)
  16868. {
  16869. messageQueue.append(request);
  16870. retObjQueue.append(object);
  16871. callbackQueue.append(const_cast<char*>(callback));
  16872. if(messageQueue.size() == 1 && !(messageDelayTimer->isActive()))
  16873. {
  16874. sendNextMessage();
  16875. }
  16876. }
  16877. void ModbusRTUDevice::sendNextMessage()
  16878. {
  16879. if(messageQueue.size() > 0 && !waiting)
  16880. {
  16881. QByteArray message = messageQueue.at(0);
  16882. quint16 crc = calculateCRC(message);
  16883. char *check = (char*)&crc;
  16884. message.append(check[0]);
  16885. message.append(check[1]);
  16886. port->write(message);
  16887. commTimeout->start(2000);
  16888. messageDelayTimer->start(delayTime);
  16889. waiting = @[true@];
  16890. }
  16891. else
  16892. {
  16893. emit queueEmpty();
  16894. }
  16895. }
  16896. void ModbusRTUDevice::outputSV(double value)
  16897. {
  16898. for(int i = 0; i < decimalPosition; i++)
  16899. {
  16900. value *= 10;
  16901. }
  16902. quint16 outval = (quint16)value;
  16903. QByteArray message(outputSVStub);
  16904. char *valBytes = (char*)&outval;
  16905. message.append(valBytes[1]);
  16906. message.append(valBytes[0]);
  16907. queueMessage(message, this, "ignore(QByteArray)");
  16908. }
  16909. @ We don'@q'@>t care about the response when sending a new SV.
  16910. @<ModbusRTUDevice implementation@>=
  16911. void ModbusRTUDevice::ignore(QByteArray)
  16912. {
  16913. return;
  16914. }
  16915. @ Sometimes a communications failure will occur in which a response to a
  16916. command is never received. To reset communications we set a timer whenever a
  16917. command is sent and stop that once a full response is received. If the timer
  16918. times out, we should clear the response buffer and attempt to re-establish
  16919. communications. Currently this timeout is hard coded at 2 seconds, however
  16920. this should be configurable and smaller values may well be acceptable.
  16921. @<ModbusRTUDevice implementation@>=
  16922. void ModbusRTUDevice::timeout()
  16923. {
  16924. qDebug() << "Communications timeout.";
  16925. responseBuffer.clear();
  16926. waiting = false;
  16927. messageDelayTimer->start();
  16928. }
  16929. @ This class must be exposed to the host environment.
  16930. @<Function prototypes for scripting@>=
  16931. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine);
  16932. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine);
  16933. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine);
  16934. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine);
  16935. @ The host environment is informed of the constructor.
  16936. @<Set up the scripting engine@>=
  16937. constructor = engine->newFunction(constructModbusRTUDevice);
  16938. value = engine->newQMetaObject(&ModbusRTUDevice::staticMetaObject, constructor);
  16939. engine->globalObject().setProperty("ModbusRTUDevice", value);
  16940. @ The constructor takes the configuration model and the index to the device of
  16941. interest as arguments rather than provide a large number of property setters to
  16942. handle initialization.
  16943. @<Functions for scripting@>=
  16944. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine)
  16945. {
  16946. QScriptValue object;
  16947. if(context->argumentCount() == 2)
  16948. {
  16949. object = engine->newQObject(new ModbusRTUDevice(argument<DeviceTreeModel *>(0, context),
  16950. argument<QModelIndex>(1, context)),
  16951. QScriptEngine::ScriptOwnership);
  16952. setModbusRTUDeviceProperties(object, engine);
  16953. }
  16954. else
  16955. {
  16956. context->throwError("Incorrect number of arguments passed to "@|
  16957. "ModbusRTUDevice constructor. This takes the configuration model "@|
  16958. "and an index.");
  16959. }
  16960. return object;
  16961. }
  16962. @ The host environment needs a way to gain access to the channel objects.
  16963. @<Functions for scripting@>=
  16964. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine)
  16965. {
  16966. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  16967. QScriptValue object;
  16968. if(self)
  16969. {
  16970. if(self->channels.size() > 0)
  16971. {
  16972. object = engine->newQObject(self->channels.at(0));
  16973. setChannelProperties(object, engine);
  16974. }
  16975. }
  16976. return object;
  16977. }
  16978. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine)
  16979. {
  16980. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  16981. QScriptValue object;
  16982. if(self)
  16983. {
  16984. if(self->channels.size() > 1)
  16985. {
  16986. object = engine->newQObject(self->channels.at(1));
  16987. setChannelProperties(object, engine);
  16988. }
  16989. }
  16990. return object;
  16991. }
  16992. @ These methods are set as properties when the object is created.
  16993. @<Functions for scripting@>=
  16994. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine)
  16995. {
  16996. setQObjectProperties(value, engine);
  16997. value.setProperty("pVChannel", engine->newFunction(ModbusRTUDevice_pVChannel));
  16998. value.setProperty("sVChannel", engine->newFunction(ModbusRTUDevice_sVChannel));
  16999. }
  17000. @* Modbus RTU device configuration widget.
  17001. \noindent This class was minimally adapted from a prototype implementation to
  17002. use the new configuration system introduced in \pn{} 1.4.
  17003. With all of the custom widgets for specifying a device configuration in place,
  17004. we can proceed to combine these in a form. As all of the options might use more
  17005. screen space than is available we make this scrollable. Some reorganization of
  17006. this will be done prior to release to enable the use of multiple devices on the
  17007. port which may obviate the need for this, but as there are those who prefer to
  17008. have a small screen it may be better to leave the scroll area in place even
  17009. after such a change.
  17010. @<Class declarations@>=
  17011. class ModbusConfigurator : public BasicDeviceConfigurationWidget
  17012. {
  17013. @[Q_OBJECT@]@;
  17014. public:@/
  17015. Q_INVOKABLE@,@, ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index);@/
  17016. @[private slots@]:@/
  17017. void updatePort(const QString &newPort);
  17018. void updateBaudRate(const QString &newRate);
  17019. void updateParity(const QString &newParity);
  17020. void updateFlowControl(const QString &newFlow);
  17021. void updateStopBits(const QString &newStopBits);
  17022. void updateStation(int station);
  17023. void updateFixedDecimal(bool fixed);
  17024. void updateDecimalAddress(int address);
  17025. void updateDecimalPosition(int position);
  17026. void updateFixedUnit(bool fixed);
  17027. void updateUnitAddress(int address);
  17028. void updateValueForF(int value);
  17029. void updateValueForC(int value);
  17030. void updateUnit(const QString &newUnit);
  17031. void updatePVAddress(int address);
  17032. void updateSVEnabled(bool enabled);
  17033. void updateSVReadAddress(int address);
  17034. void updateDeviceLimit(bool query);
  17035. void updateSVLowerAddress(int address);
  17036. void updateSVUpperAddress(int address);
  17037. void updateSVLower(double value);
  17038. void updateSVUpper(double value);
  17039. void updateSVWritable(bool canWriteSV);
  17040. void updateSVWriteAddress(int address);
  17041. void updatePVColumnName(const QString &name);
  17042. void updateSVColumnName(const QString &name);
  17043. void updatePVHidden(bool hidden);
  17044. void updateSVHidden(bool hidden);@/
  17045. private:@/
  17046. PortSelector *port;
  17047. BaudSelector *baud;
  17048. ParitySelector *parity;
  17049. FlowSelector *flow;
  17050. StopSelector *stop;
  17051. QSpinBox *station;
  17052. QCheckBox *decimalQuery;
  17053. ShortHexSpinBox *decimalAddress;
  17054. QSpinBox *decimalPosition;
  17055. QCheckBox *unitQuery;
  17056. ShortHexSpinBox *unitAddress;
  17057. QSpinBox *valueF;
  17058. QSpinBox *valueC;
  17059. QComboBox *fixedUnit;
  17060. ShortHexSpinBox *pVAddress;
  17061. QCheckBox *sVEnabled;
  17062. ShortHexSpinBox *sVReadAddress;
  17063. QCheckBox *deviceLimit;
  17064. ShortHexSpinBox *sVLowerAddr;
  17065. ShortHexSpinBox *sVUpperAddr;
  17066. QDoubleSpinBox *sVLower;
  17067. QDoubleSpinBox *sVUpper;
  17068. QCheckBox *sVWritable;
  17069. ShortHexSpinBox *sVOutputAddr;
  17070. QLineEdit *pVColumnName;
  17071. QLineEdit *sVColumnName;
  17072. };
  17073. @ Implementation.
  17074. @<ModbusConfigurator implementation@>=
  17075. ModbusConfigurator::ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index)
  17076. : BasicDeviceConfigurationWidget(model, index),
  17077. port(new PortSelector), baud(new BaudSelector), parity(new ParitySelector),
  17078. flow(new FlowSelector), stop(new StopSelector), station(new QSpinBox),
  17079. decimalQuery(new QCheckBox(tr("Enable"))),
  17080. decimalAddress(new ShortHexSpinBox), decimalPosition(new QSpinBox),
  17081. unitQuery(new QCheckBox(tr("Enable"))),
  17082. unitAddress(new ShortHexSpinBox), valueF(new QSpinBox),
  17083. valueC(new QSpinBox), fixedUnit(new QComboBox),
  17084. pVAddress(new ShortHexSpinBox),
  17085. sVEnabled(new QCheckBox(tr("Enable"))),
  17086. sVReadAddress(new ShortHexSpinBox),
  17087. deviceLimit(new QCheckBox(tr("Enable"))),
  17088. sVLowerAddr(new ShortHexSpinBox), sVUpperAddr(new ShortHexSpinBox),
  17089. sVLower(new QDoubleSpinBox), sVUpper(new QDoubleSpinBox),
  17090. sVWritable(new QCheckBox(tr("Enable"))),
  17091. sVOutputAddr(new ShortHexSpinBox),
  17092. pVColumnName(new QLineEdit), sVColumnName(new QLineEdit)
  17093. {
  17094. QHBoxLayout *layout = new QHBoxLayout;
  17095. QWidget *form = new QWidget;
  17096. QHBoxLayout *masterLayout = new QHBoxLayout;
  17097. QVBoxLayout *portAndDeviceLayout = new QVBoxLayout;
  17098. QVBoxLayout *seriesLayout = new QVBoxLayout;
  17099. QFormLayout *serialSection = new QFormLayout;
  17100. serialSection->addRow(QString(tr("Port:")), port);
  17101. serialSection->addRow(QString(tr("Baud rate:")), baud);
  17102. serialSection->addRow(QString(tr("Parity:")), parity);
  17103. serialSection->addRow(QString(tr("Flow control:")), flow);
  17104. serialSection->addRow(QString(tr("Stop bits:")), stop);
  17105. QGroupBox *serialSectionBox = new QGroupBox(tr("Serial Port Configuration"));
  17106. serialSectionBox->setLayout(serialSection);
  17107. portAndDeviceLayout->addWidget(serialSectionBox);
  17108. QFormLayout *deviceSection = new QFormLayout;
  17109. station->setMinimum(1);
  17110. station->setMaximum(255);
  17111. decimalPosition->setMinimum(0);
  17112. decimalPosition->setMaximum(9);
  17113. valueF->setMinimum(0);
  17114. valueF->setMaximum(0xFFFF);
  17115. valueC->setMinimum(0);
  17116. valueC->setMaximum(0xFFFF);
  17117. fixedUnit->addItem(tr("Fahrenheit"), QVariant(QString("F")));
  17118. fixedUnit->addItem(tr("Celsius"), QVariant(QString("C")));
  17119. deviceSection->addRow(tr("Station:"), station);
  17120. deviceSection->addRow(tr("Decimal position from device:"), decimalQuery);
  17121. deviceSection->addRow(tr("Decimal position relative address:"), decimalAddress);
  17122. deviceSection->addRow(tr("Fixed decimal position:"), decimalPosition);
  17123. deviceSection->addRow(tr("Measurement unit from device:"), unitQuery);
  17124. deviceSection->addRow(tr("Current unit relative address:"), unitAddress);
  17125. deviceSection->addRow(tr("Value for Fahrenheit:"), valueF);
  17126. deviceSection->addRow(tr("Value for Celsius:"), valueC);
  17127. deviceSection->addRow(tr("Fixed unit:"), fixedUnit);
  17128. QGroupBox *deviceSectionBox = new QGroupBox(tr("Device Configuration"));
  17129. deviceSectionBox->setLayout(deviceSection);
  17130. portAndDeviceLayout->addWidget(deviceSectionBox);
  17131. QFormLayout *pVSection = new QFormLayout;
  17132. pVSection->addRow(tr("Value relative address:"), pVAddress);
  17133. pVSection->addRow(tr("PV column name:"), pVColumnName);
  17134. QCheckBox *pVHideBox = new QCheckBox(tr("Hide this channel"));
  17135. pVSection->addRow(pVHideBox);
  17136. QGroupBox *processValueBox = new QGroupBox(tr("Process Value"));
  17137. processValueBox->setLayout(pVSection);
  17138. seriesLayout->addWidget(processValueBox);
  17139. QFormLayout *sVSection = new QFormLayout;
  17140. sVLower->setDecimals(1);
  17141. sVLower->setMinimum(0.0);
  17142. sVLower->setMaximum(999.9);
  17143. sVUpper->setDecimals(1);
  17144. sVUpper->setMinimum(0.0);
  17145. sVUpper->setMaximum(999.9);
  17146. sVSection->addRow(tr("Set value:"), sVEnabled);
  17147. sVSection->addRow(tr("Read relative address:"), sVReadAddress);
  17148. sVSection->addRow(tr("SV column name:"), sVColumnName);
  17149. sVSection->addRow(tr("Limits from device:"), deviceLimit);
  17150. sVSection->addRow(tr("Lower limit relative address:"), sVLowerAddr);
  17151. sVSection->addRow(tr("Upper limit relative address:"), sVUpperAddr);
  17152. sVSection->addRow(tr("Lower limit:"), sVLower);
  17153. sVSection->addRow(tr("Upper limit:"), sVUpper);
  17154. sVSection->addRow(tr("Output set value:"), sVWritable);
  17155. sVSection->addRow(tr("Output relative address:"), sVOutputAddr);
  17156. QCheckBox *sVHideBox = new QCheckBox(tr("Hide this channel"));
  17157. sVSection->addRow(sVHideBox);
  17158. QGroupBox *setValueBox = new QGroupBox(tr("Set Value"));
  17159. setValueBox->setLayout(sVSection);
  17160. seriesLayout->addWidget(setValueBox);
  17161. masterLayout->addLayout(portAndDeviceLayout);
  17162. masterLayout->addLayout(seriesLayout);
  17163. form->setLayout(masterLayout);
  17164. @<Get device configuration data for current node@>@;
  17165. for(int i = 0; i < configData.size(); i++)
  17166. {
  17167. node = configData.at(i).toElement();
  17168. if(node.attribute("name") == "port")
  17169. {
  17170. QString portname = node.attribute("value");
  17171. int idx = port->findText(portname);
  17172. if(idx >= 0)
  17173. {
  17174. port->setCurrentIndex(idx);
  17175. }
  17176. else
  17177. {
  17178. port->addItem(portname);
  17179. }
  17180. }
  17181. else if(node.attribute("name") == "baud")
  17182. {
  17183. baud->setCurrentIndex(baud->findText(node.attribute("value")));
  17184. }
  17185. else if(node.attribute("name") == "parity")
  17186. {
  17187. parity->setCurrentIndex(parity->findData(node.attribute("value")));
  17188. }
  17189. else if(node.attribute("name") == "flow")
  17190. {
  17191. flow->setCurrentIndex(flow->findData(node.attribute("value")));
  17192. }
  17193. else if(node.attribute("name") == "stop")
  17194. {
  17195. stop->setCurrentIndex(stop->findData(node.attribute("value")));
  17196. }
  17197. else if(node.attribute("name") == "station")
  17198. {
  17199. station->setValue(node.attribute("value").toInt());
  17200. }
  17201. else if(node.attribute("name") == "decimalQuery")
  17202. {
  17203. if(node.attribute("value") == "true")
  17204. {
  17205. decimalQuery->setChecked(true);
  17206. }
  17207. else
  17208. {
  17209. decimalQuery->setChecked(false);
  17210. }
  17211. }
  17212. else if(node.attribute("name") == "decimalAddress")
  17213. {
  17214. decimalAddress->setValue(node.attribute("value").toInt());
  17215. }
  17216. else if(node.attribute("name") == "decimalPosition")
  17217. {
  17218. decimalPosition->setValue(node.attribute("value").toInt());
  17219. }
  17220. else if(node.attribute("name") == "unitQuery")
  17221. {
  17222. if(node.attribute("value") == "true")
  17223. {
  17224. unitQuery->setChecked(true);
  17225. }
  17226. else
  17227. {
  17228. unitQuery->setChecked(false);
  17229. }
  17230. }
  17231. else if(node.attribute("name") == "unitAddress")
  17232. {
  17233. unitAddress->setValue(node.attribute("value").toInt());
  17234. }
  17235. else if(node.attribute("name") == "valueF")
  17236. {
  17237. valueF->setValue(node.attribute("value").toInt());
  17238. }
  17239. else if(node.attribute("name") == "valueC")
  17240. {
  17241. valueC->setValue(node.attribute("value").toInt());
  17242. }
  17243. else if(node.attribute("name") == "fixedUnit")
  17244. {
  17245. fixedUnit->setCurrentIndex(fixedUnit->findText(node.attribute("value")));
  17246. }
  17247. else if(node.attribute("name") == "pVAddress")
  17248. {
  17249. pVAddress->setValue(node.attribute("value").toInt());
  17250. }
  17251. else if(node.attribute("name") == "sVEnabled")
  17252. {
  17253. if(node.attribute("value") == "true")
  17254. {
  17255. sVEnabled->setChecked(true);
  17256. }
  17257. else
  17258. {
  17259. sVEnabled->setChecked(false);
  17260. }
  17261. }
  17262. else if(node.attribute("name") == "sVReadAddress")
  17263. {
  17264. sVReadAddress->setValue(node.attribute("value").toInt());
  17265. }
  17266. else if(node.attribute("name") == "deviceLimit")
  17267. {
  17268. if(node.attribute("value") == "true")
  17269. {
  17270. deviceLimit->setChecked(true);
  17271. }
  17272. else
  17273. {
  17274. deviceLimit->setChecked(false);
  17275. }
  17276. }
  17277. else if(node.attribute("name") == "sVLowerAddr")
  17278. {
  17279. sVLowerAddr->setValue(node.attribute("value").toInt());
  17280. }
  17281. else if(node.attribute("name") == "sVUpperAddr")
  17282. {
  17283. sVUpperAddr->setValue(node.attribute("value").toInt());
  17284. }
  17285. else if(node.attribute("name") == "sVLower")
  17286. {
  17287. sVLower->setValue(node.attribute("value").toDouble());
  17288. }
  17289. else if(node.attribute("name") == "sVUpper")
  17290. {
  17291. sVUpper->setValue(node.attribute("value").toDouble());
  17292. }
  17293. else if(node.attribute("name") == "sVWritable")
  17294. {
  17295. if(node.attribute("value") == "true")
  17296. {
  17297. sVWritable->setChecked(true);
  17298. }
  17299. else
  17300. {
  17301. sVWritable->setChecked(false);
  17302. }
  17303. }
  17304. else if(node.attribute("name") == "sVOutputAddr")
  17305. {
  17306. sVOutputAddr->setValue(node.attribute("value").toInt());
  17307. }
  17308. else if(node.attribute("name") == "pvcolname")
  17309. {
  17310. pVColumnName->setText(node.attribute("value"));
  17311. }
  17312. else if(node.attribute("name") == "svcolname")
  17313. {
  17314. sVColumnName->setText(node.attribute("value"));
  17315. }
  17316. else if(node.attribute("name") == "pvhidden")
  17317. {
  17318. pVHideBox->setChecked(node.attribute("value") == "true");
  17319. }
  17320. else if(node.attribute("name") == "svhidden")
  17321. {
  17322. sVHideBox->setChecked(node.attribute("value") == "true");
  17323. }
  17324. }
  17325. updatePort(port->currentText());
  17326. updateBaudRate(baud->currentText());
  17327. updateParity(parity->itemData(parity->currentIndex()).toString());
  17328. updateFlowControl(flow->itemData(flow->currentIndex()).toString());
  17329. updateStopBits(stop->itemData(stop->currentIndex()).toString());
  17330. updateStation(station->value());
  17331. updateFixedDecimal(decimalQuery->isChecked());
  17332. updateDecimalAddress(decimalAddress->value());
  17333. updateDecimalPosition(decimalPosition->value());
  17334. updateFixedUnit(unitQuery->isChecked());
  17335. updateUnitAddress(unitAddress->value());
  17336. updateValueForF(valueF->value());
  17337. updateValueForC(valueC->value());
  17338. updateUnit(fixedUnit->currentText());
  17339. updatePVAddress(pVAddress->value());
  17340. updateSVEnabled(sVEnabled->isChecked());
  17341. updateSVReadAddress(sVReadAddress->value());
  17342. updateDeviceLimit(deviceLimit->isChecked());
  17343. updateSVLowerAddress(sVLowerAddr->value());
  17344. updateSVUpperAddress(sVUpperAddr->value());
  17345. updateSVLower(sVLower->value());
  17346. updateSVUpper(sVUpper->value());
  17347. updateSVWritable(sVWritable->isChecked());
  17348. updateSVWriteAddress(sVOutputAddr->value());
  17349. updatePVColumnName(pVColumnName->text());
  17350. updateSVColumnName(sVColumnName->text());
  17351. updatePVHidden(pVHideBox->isChecked());
  17352. updateSVHidden(sVHideBox->isChecked());
  17353. connect(port, SIGNAL(currentIndexChanged(QString)), this, SLOT(updatePort(QString)));
  17354. connect(port, SIGNAL(editTextChanged(QString)), this, SLOT(updatePort(QString)));
  17355. connect(baud, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateBaudRate(QString)));
  17356. connect(parity, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateParity(QString)));
  17357. connect(flow, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateFlowControl(QString)));
  17358. connect(stop, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateStopBits(QString)));
  17359. connect(station, SIGNAL(valueChanged(int)), this, SLOT(updateStation(int)));
  17360. connect(decimalQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedDecimal(bool)));
  17361. connect(decimalAddress, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalAddress(int)));
  17362. connect(decimalPosition, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalPosition(int)));
  17363. connect(unitQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedUnit(bool)));
  17364. connect(unitAddress, SIGNAL(valueChanged(int)), this, SLOT(updateUnitAddress(int)));
  17365. connect(valueF, SIGNAL(valueChanged(int)), this, SLOT(updateValueForF(int)));
  17366. connect(valueC, SIGNAL(valueChanged(int)), this, SLOT(updateValueForC(int)));
  17367. connect(fixedUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateUnit(QString)));
  17368. connect(pVAddress, SIGNAL(valueChanged(int)), this, SLOT(updatePVAddress(int)));
  17369. connect(sVEnabled, SIGNAL(toggled(bool)), this, SLOT(updateSVEnabled(bool)));
  17370. connect(sVReadAddress, SIGNAL(valueChanged(int)), this, SLOT(updateSVReadAddress(int)));
  17371. connect(deviceLimit, SIGNAL(toggled(bool)), this, SLOT(updateDeviceLimit(bool)));
  17372. connect(sVLowerAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVLowerAddress(int)));
  17373. connect(sVUpperAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVUpperAddress(int)));
  17374. connect(sVLower, SIGNAL(valueChanged(double)), this, SLOT(updateSVLower(double)));
  17375. connect(sVUpper, SIGNAL(valueChanged(double)), this, SLOT(updateSVUpper(double)));
  17376. connect(sVWritable, SIGNAL(toggled(bool)), this, SLOT(updateSVWritable(bool)));
  17377. connect(sVOutputAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVWriteAddress(int)));
  17378. connect(pVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updatePVColumnName(QString)));
  17379. connect(sVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updateSVColumnName(QString)));
  17380. connect(pVHideBox, SIGNAL(toggled(bool)), this, SLOT(updatePVHidden(bool)));
  17381. connect(sVHideBox, SIGNAL(toggled(bool)), this, SLOT(updateSVHidden(bool)));
  17382. layout->addWidget(form);
  17383. setLayout(layout);
  17384. }
  17385. void ModbusConfigurator::updatePort(const QString &newPort)
  17386. {
  17387. updateAttribute("port", newPort);
  17388. }
  17389. void ModbusConfigurator::updateBaudRate(const QString &newRate)
  17390. {
  17391. updateAttribute("baud", newRate);
  17392. }
  17393. void ModbusConfigurator::updateParity(const QString &)
  17394. {
  17395. updateAttribute("parity", parity->itemData(parity->currentIndex()).toString());
  17396. }
  17397. void ModbusConfigurator::updateFlowControl(const QString &)
  17398. {
  17399. updateAttribute("flow", flow->itemData(flow->currentIndex()).toString());
  17400. }
  17401. void ModbusConfigurator::updateStopBits(const QString &)
  17402. {
  17403. updateAttribute("stop", stop->itemData(stop->currentIndex()).toString());
  17404. }
  17405. void ModbusConfigurator::updateStation(int station)
  17406. {
  17407. updateAttribute("station", QString("%1").arg(station));
  17408. }
  17409. void ModbusConfigurator::updateFixedDecimal(bool fixed)
  17410. {
  17411. updateAttribute("decimalQuery", fixed ? "true" : "false");
  17412. }
  17413. void ModbusConfigurator::updateDecimalAddress(int address)
  17414. {
  17415. updateAttribute("decimalAddress", QString("%1").arg(address));
  17416. }
  17417. void ModbusConfigurator::updateDecimalPosition(int position)
  17418. {
  17419. updateAttribute("decimalPosition", QString("%1").arg(position));
  17420. }
  17421. void ModbusConfigurator::updateFixedUnit(bool fixed)
  17422. {
  17423. updateAttribute("unitQuery", fixed ? "true" : "false");
  17424. }
  17425. void ModbusConfigurator::updateUnitAddress(int address)
  17426. {
  17427. updateAttribute("unitAddress", QString("%1").arg(address));
  17428. }
  17429. void ModbusConfigurator::updateValueForF(int value)
  17430. {
  17431. updateAttribute("valueF", QString("%1").arg(value));
  17432. }
  17433. void ModbusConfigurator::updateValueForC(int value)
  17434. {
  17435. updateAttribute("valueC", QString("%1").arg(value));
  17436. }
  17437. void ModbusConfigurator::updateUnit(const QString &newUnit)
  17438. {
  17439. updateAttribute("fixedUnit", newUnit);
  17440. }
  17441. void ModbusConfigurator::updatePVAddress(int address)
  17442. {
  17443. updateAttribute("pVAddress", QString("%1").arg(address));
  17444. }
  17445. void ModbusConfigurator::updateSVEnabled(bool enabled)
  17446. {
  17447. updateAttribute("sVEnabled", enabled ? "true" : "false");
  17448. }
  17449. void ModbusConfigurator::updateSVReadAddress(int address)
  17450. {
  17451. updateAttribute("sVReadAddress", QString("%1").arg(address));
  17452. }
  17453. void ModbusConfigurator::updateDeviceLimit(bool query)
  17454. {
  17455. updateAttribute("deviceLimit", query ? "true" : "false");
  17456. }
  17457. void ModbusConfigurator::updateSVLowerAddress(int address)
  17458. {
  17459. updateAttribute("sVLowerAddr", QString("%1").arg(address));
  17460. }
  17461. void ModbusConfigurator::updateSVUpperAddress(int address)
  17462. {
  17463. updateAttribute("sVUpperAddr", QString("%1").arg(address));
  17464. }
  17465. void ModbusConfigurator::updateSVLower(double value)
  17466. {
  17467. updateAttribute("sVLower", QString("%1").arg(value));
  17468. }
  17469. void ModbusConfigurator::updateSVUpper(double value)
  17470. {
  17471. updateAttribute("sVUpper", QString("%1").arg(value));
  17472. }
  17473. void ModbusConfigurator::updateSVWritable(bool canWriteSV)
  17474. {
  17475. updateAttribute("sVWritable", canWriteSV ? "true" : "false");
  17476. }
  17477. void ModbusConfigurator::updateSVWriteAddress(int address)
  17478. {
  17479. updateAttribute("sVOutputAddr", QString("%1").arg(address));
  17480. }
  17481. void ModbusConfigurator::updatePVColumnName(const QString &name)
  17482. {
  17483. updateAttribute("pvcolname", name);
  17484. }
  17485. void ModbusConfigurator::updateSVColumnName(const QString &name)
  17486. {
  17487. updateAttribute("svcolname", name);
  17488. }
  17489. void ModbusConfigurator::updatePVHidden(bool hidden)
  17490. {
  17491. updateAttribute("pvhidden", hidden ? "true" : "false");
  17492. }
  17493. void ModbusConfigurator::updateSVHidden(bool hidden)
  17494. {
  17495. updateAttribute("svhidden", hidden ? "true" : "false");
  17496. }
  17497. @ This is registered with the configuration system.
  17498. @<Register device configuration widgets@>=
  17499. app.registerDeviceConfigurationWidget("modbusrtu", ModbusConfigurator::staticMetaObject);
  17500. @ A |NodeInserter| for the driver configuration widget is also needed.
  17501. @<Register top level device configuration nodes@>=
  17502. inserter = new NodeInserter(tr("Modbus RTU Device"), tr("Modbus RTU Device"), "modbusrtu", NULL);
  17503. topLevelNodeInserters.append(inserter);
  17504. @i modbus.w
  17505. @i unsupportedserial.w
  17506. @i phidgets.w
  17507. @i phidget22.w
  17508. @* Configuration widget for a calibrated data series.
  17509. \noindent This control is used for adding a |LinearSplineInterpolator| to the
  17510. logging view.
  17511. @<Class declarations@>=
  17512. class LinearSplineInterpolationConfWidget : public BasicDeviceConfigurationWidget
  17513. {
  17514. @[Q_OBJECT@]@/
  17515. public:@/
  17516. @[Q_INVOKABLE@]@, LinearSplineInterpolationConfWidget(DeviceTreeModel *model,
  17517. const QModelIndex &index);
  17518. @[private slots@]:@/
  17519. void updateSourceColumn(const QString &source);
  17520. void updateDestinationColumn(const QString &dest);
  17521. void updateKnots();
  17522. private:@/
  17523. SaltModel *tablemodel;
  17524. };
  17525. @ This is configured by specifying a source column name, a destination column
  17526. name, and a two column table. Note that while we only have one widget handling
  17527. the mapping data, we store each column of the table in its own attribute.
  17528. @<LinearSplineInterpolationConfWidget implementation@>=
  17529. LinearSplineInterpolationConfWidget::LinearSplineInterpolationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  17530. : BasicDeviceConfigurationWidget(model, index), tablemodel(new SaltModel(2))
  17531. {
  17532. QFormLayout *layout = new QFormLayout;
  17533. QLineEdit *source = new QLineEdit;
  17534. layout->addRow(tr("Source column name:"), source);
  17535. QLineEdit *destination = new QLineEdit;
  17536. layout->addRow(tr("Destination column name:"), destination);
  17537. tablemodel->setHeaderData(0, Qt::Horizontal, "Input");
  17538. tablemodel->setHeaderData(1, Qt::Horizontal, "Output");
  17539. QTableView *mappingTable = new QTableView;
  17540. mappingTable->setModel(tablemodel);
  17541. NumericDelegate *delegate = new NumericDelegate;
  17542. mappingTable->setItemDelegate(delegate);
  17543. layout->addRow(tr("Mapping data:"), mappingTable);
  17544. @<Get device configuration data for current node@>@;
  17545. for(int i = 0; i < configData.size(); i++)
  17546. {
  17547. node = configData.at(i).toElement();
  17548. if(node.attribute("name") == "source")
  17549. {
  17550. source->setText(node.attribute("value"));
  17551. }
  17552. else if(node.attribute("name") == "destination")
  17553. {
  17554. destination->setText(node.attribute("value"));
  17555. }
  17556. else if(node.attribute("name") == "sourcevalues")
  17557. {
  17558. @<Convert numeric array literal to list@>@;
  17559. int column = 0;
  17560. @<Populate model column from list@>@;
  17561. }
  17562. else if(node.attribute("name") == "destinationvalues")
  17563. {
  17564. @<Convert numeric array literal to list@>@;
  17565. int column = 1;
  17566. @<Populate model column from list@>@;
  17567. }
  17568. }
  17569. updateSourceColumn(source->text());
  17570. updateDestinationColumn(destination->text());
  17571. updateKnots();
  17572. connect(source, SIGNAL(textEdited(QString)), this, SLOT(updateSourceColumn(QString)));
  17573. connect(destination, SIGNAL(textEdited(QString)), this, SLOT(updateDestinationColumn(QString)));
  17574. connect(tablemodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateKnots()));
  17575. setLayout(layout);
  17576. }
  17577. @ The saved data will have come from a previous call to
  17578. |SaltModel::arrayLiteral()| to repopulate the model we need to strip off the
  17579. the start and end of the strings and split them back into separate elements.
  17580. @<Convert numeric array literal to list@>=
  17581. QString data = node.attribute("value");
  17582. if(data.length() > 3)
  17583. {
  17584. data.chop(2);
  17585. data = data.remove(0, 2);
  17586. }
  17587. QStringList itemList = data.split(",");
  17588. @ Once the saved string has been split, the values can be inserted into the
  17589. model.
  17590. @<Populate model column from list@>=
  17591. for(int j = 0; j < itemList.size(); j++)
  17592. {
  17593. tablemodel->setData(tablemodel->index(j, column),
  17594. QVariant(itemList.at(j).toDouble()),
  17595. Qt::DisplayRole);
  17596. }
  17597. @ When data in the table is changed we simply overwrite any previously saved
  17598. data with the current data.
  17599. @<LinearSplineInterpolationConfWidget implementation@>=
  17600. void LinearSplineInterpolationConfWidget::updateKnots()
  17601. {
  17602. updateAttribute("sourcevalues", tablemodel->arrayLiteral(0, Qt::DisplayRole));
  17603. updateAttribute("destinationvalues", tablemodel->arrayLiteral(1, Qt::DisplayRole));
  17604. }
  17605. void LinearSplineInterpolationConfWidget::updateSourceColumn(const QString &source)
  17606. {
  17607. updateAttribute("source", source);
  17608. }
  17609. void LinearSplineInterpolationConfWidget::updateDestinationColumn(const QString &dest)
  17610. {
  17611. updateAttribute("destination", dest);
  17612. }
  17613. @ The widget is registered with the configuration system.
  17614. @<Register device configuration widgets@>=
  17615. app.registerDeviceConfigurationWidget("linearspline", LinearSplineInterpolationConfWidget::staticMetaObject);
  17616. @* Additional Timers.
  17617. \noindent \pn{} 1.6.4 adds support for more timer indicators than just the
  17618. default batch timer. Three new timer types are supported. The first is a
  17619. cooling timer. This is a timer that is initially set to 0, but at the end of a
  17620. batch this is set to a configured time and starts counting down. There are no
  17621. data logging requirements and this is purely a convenience feature, but one
  17622. that supports product and personnel safety best practices as it helps to
  17623. eliminate the practice of a person reaching into the cooling tray as it
  17624. agitates to test if the coffee has cooled.
  17625. @<Class declarations@>=
  17626. class CoolingTimerConfWidget : public BasicDeviceConfigurationWidget
  17627. {
  17628. @[Q_OBJECT@]@/
  17629. public:@/
  17630. @[Q_INVOKABLE@]@, CoolingTimerConfWidget(DeviceTreeModel *model,
  17631. const QModelIndex &index);
  17632. @[private slots@]:@/
  17633. void updateResetTime(QTime time);
  17634. };
  17635. @ The only configurable detail is the vaue the timer should reset to. For this
  17636. a |QTimeEdit| is fine.
  17637. @<CoolingTimerConfWidget implementation@>=
  17638. CoolingTimerConfWidget::CoolingTimerConfWidget(DeviceTreeModel *model,
  17639. const QModelIndex &index)
  17640. : BasicDeviceConfigurationWidget(model, index)
  17641. {
  17642. QHBoxLayout *layout = new QHBoxLayout;
  17643. QLabel *label = new QLabel(tr("Cooling Time: "));
  17644. QTimeEdit *editor = new QTimeEdit;
  17645. editor->setDisplayFormat("mm:ss");
  17646. @<Get device configuration data for current node@>@;
  17647. for(int i = 0; i < configData.size(); i++)
  17648. {
  17649. node = configData.at(i).toElement();
  17650. if(node.attribute("name") == "reset")
  17651. {
  17652. editor->setTime(QTime::fromString(node.attribute("value"), "mm:ss"));
  17653. }
  17654. }
  17655. updateResetTime(editor->time());
  17656. connect(editor, SIGNAL(timeChanged(QTime)),
  17657. this, SLOT(updateResetTime(QTime)));
  17658. layout->addWidget(label);
  17659. layout->addWidget(editor);
  17660. setLayout(layout);
  17661. }
  17662. void CoolingTimerConfWidget::updateResetTime(QTime time)
  17663. {
  17664. updateAttribute("reset", time.toString("mm:ss"));
  17665. }
  17666. @ The widget is registered with the configuration system.
  17667. @<Register device configuration widgets@>=
  17668. app.registerDeviceConfigurationWidget("coolingtimer",
  17669. CoolingTimerConfWidget::staticMetaObject);
  17670. @ The implementation chunk for now is in the main source file.
  17671. @<Class implementations@>=
  17672. @<CoolingTimerConfWidget implementation@>
  17673. @ The other two timer types are intended for measuring ranges of interest
  17674. within a batch. These have more configuration options. First is the range
  17675. timer. Someone setting this up needs to decide how the timer is started.
  17676. Sensible options include starting the timer at the start of the batch,
  17677. starting the timer when a button is pressed, or starting the timer when a set
  17678. point is reached on the ascent of a named data series. Stopping the timer is
  17679. also a configurable concern. This will be stopped at the end of the batch,
  17680. but it might be stopped sooner on reaching some threshold or when a button is
  17681. pressed. There are also questions of how the information is persisted with the
  17682. roasting records.
  17683. @<Class declarations@>=
  17684. class RangeTimerConfWidget : public BasicDeviceConfigurationWidget
  17685. {
  17686. @[Q_OBJECT@]@;
  17687. public:@/
  17688. @[Q_INVOKABLE@]@, RangeTimerConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  17689. @[private slots@]:@/
  17690. void updateStartButtonText(const QString &text);
  17691. void updateStopButtonText(const QString &text);
  17692. void updateStartColumnName(const QString &text);
  17693. void updateStopColumnName(const QString &text);
  17694. void updateStartValue(const QString &text);
  17695. void updateStopValue(const QString &text);
  17696. void updateStartTrigger(int option);
  17697. void updateStopTrigger(int option);
  17698. };
  17699. @ The constructor sets up controls for configuring these details.
  17700. @<RangeTimerConfWidget implementation@>=
  17701. RangeTimerConfWidget::RangeTimerConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  17702. : BasicDeviceConfigurationWidget(model, index)
  17703. {
  17704. QVBoxLayout *layout = new QVBoxLayout;
  17705. QGroupBox *startConfigurationGroup = new QGroupBox(tr("Start trigger"));
  17706. QRadioButton *startBatchOption = new QRadioButton(tr("Start of batch"));
  17707. QRadioButton *buttonOption = new QRadioButton(tr("Manual"));
  17708. QRadioButton *thresholdOption = new QRadioButton(tr("At temperature"));
  17709. QButtonGroup *startOptionGroup = new QButtonGroup;
  17710. startOptionGroup->addButton(startBatchOption, 1);
  17711. startOptionGroup->addButton(buttonOption, 2);
  17712. startOptionGroup->addButton(thresholdOption, 3);
  17713. startBatchOption->setChecked(true);
  17714. QGridLayout *startOptions = new QGridLayout;
  17715. startOptions->addWidget(startBatchOption, 0, 0);
  17716. startOptions->addWidget(buttonOption, 1, 0);
  17717. startOptions->addWidget(thresholdOption, 2, 0);
  17718. QLabel *buttonTextLabel = new QLabel(tr("Button Text: "));
  17719. QLineEdit *buttonTextEdit = new QLineEdit;
  17720. QHBoxLayout *buttonTextOptions = new QHBoxLayout;
  17721. buttonTextOptions->addWidget(buttonTextLabel);
  17722. buttonTextOptions->addWidget(buttonTextEdit);
  17723. startOptions->addLayout(buttonTextOptions, 1, 1);
  17724. QFormLayout *thresholdOptions = new QFormLayout;
  17725. QLineEdit *startColumnName = new QLineEdit;
  17726. QLineEdit *startValue = new QLineEdit;
  17727. thresholdOptions->addRow(tr("Column Name: "), startColumnName);
  17728. thresholdOptions->addRow(tr("Value: "), startValue);
  17729. startOptions->addLayout(thresholdOptions, 2, 1);
  17730. startConfigurationGroup->setLayout(startOptions);
  17731. layout->addWidget(startConfigurationGroup);
  17732. QGroupBox *stopConfigurationGroup = new QGroupBox(tr("Stop trigger"));
  17733. QRadioButton *stopBatchOption = new QRadioButton(tr("End of batch"));
  17734. QRadioButton *stopButtonOption = new QRadioButton(tr("Manual"));
  17735. QRadioButton *stopThresholdOption = new QRadioButton(tr("At temperature"));
  17736. QButtonGroup *stopOptionGroup = new QButtonGroup;
  17737. stopOptionGroup->addButton(stopBatchOption, 1);
  17738. stopOptionGroup->addButton(stopButtonOption, 2);
  17739. stopOptionGroup->addButton(stopThresholdOption, 3);
  17740. stopBatchOption->setChecked(true);
  17741. QGridLayout *stopOptions = new QGridLayout;
  17742. stopOptions->addWidget(stopBatchOption, 0, 0);
  17743. stopOptions->addWidget(stopButtonOption, 1, 0);
  17744. stopOptions->addWidget(stopThresholdOption, 2, 0);
  17745. QLabel *stopButtonLabel = new QLabel(tr("Button Text: "));
  17746. QLineEdit *stopButtonEdit = new QLineEdit;
  17747. QHBoxLayout *stopButtonTextOptions = new QHBoxLayout;
  17748. stopButtonTextOptions->addWidget(stopButtonLabel);
  17749. stopButtonTextOptions->addWidget(stopButtonEdit);
  17750. stopOptions->addLayout(stopButtonTextOptions, 1, 1);
  17751. QLineEdit *stopColumnName = new QLineEdit;
  17752. QLineEdit *stopValue = new QLineEdit;
  17753. QFormLayout *stopThresholdOptions = new QFormLayout;
  17754. stopThresholdOptions->addRow(tr("Column Name: "), stopColumnName);
  17755. stopThresholdOptions->addRow(tr("Value: "), stopValue);
  17756. stopOptions->addLayout(stopThresholdOptions, 2, 1);
  17757. stopConfigurationGroup->setLayout(stopOptions);
  17758. layout->addWidget(stopConfigurationGroup);
  17759. @<Get device configuration data for current node@>@;
  17760. for(int i = 0; i < configData.size(); i++)
  17761. {
  17762. node = configData.at(i).toElement();
  17763. if(node.attribute("name") == "startbuttontext")
  17764. {
  17765. buttonTextEdit->setText(node.attribute("value"));
  17766. }
  17767. else if(node.attribute("name") == "stopbuttontext")
  17768. {
  17769. stopButtonEdit->setText(node.attribute("value"));
  17770. }
  17771. else if(node.attribute("name") == "startcolumnname")
  17772. {
  17773. startColumnName->setText(node.attribute("value"));
  17774. }
  17775. else if(node.attribute("name") == "stopcolumnname")
  17776. {
  17777. stopColumnName->setText(node.attribute("value"));
  17778. }
  17779. else if(node.attribute("name") == "startvalue")
  17780. {
  17781. startValue->setText(node.attribute("value"));
  17782. }
  17783. else if(node.attribute("name") == "stopvalue")
  17784. {
  17785. stopValue->setText(node.attribute("value"));
  17786. }
  17787. else if(node.attribute("name") == "starttrigger")
  17788. {
  17789. if(node.attribute("value") == "batch")
  17790. {
  17791. startBatchOption->setChecked(true);
  17792. }
  17793. else if(node.attribute("value") == "manual")
  17794. {
  17795. buttonOption->setChecked(true);
  17796. }
  17797. else if(node.attribute("value") == "value")
  17798. {
  17799. thresholdOption->setChecked(true);
  17800. }
  17801. }
  17802. else if(node.attribute("name") == "stoptrigger")
  17803. {
  17804. if(node.attribute("value") == "batch")
  17805. {
  17806. stopBatchOption->setChecked(true);
  17807. }
  17808. else if(node.attribute("value") == "manual")
  17809. {
  17810. stopButtonOption->setChecked(true);
  17811. }
  17812. else if(node.attribute("value") == "value")
  17813. {
  17814. stopThresholdOption->setChecked(true);
  17815. }
  17816. }
  17817. }
  17818. updateStartButtonText(buttonTextEdit->text());
  17819. updateStopButtonText(stopButtonEdit->text());
  17820. updateStartColumnName(startColumnName->text());
  17821. updateStopColumnName(stopColumnName->text());
  17822. updateStartValue(startValue->text());
  17823. updateStopValue(stopValue->text());
  17824. updateStartTrigger(startOptionGroup->checkedId());
  17825. updateStopTrigger(stopOptionGroup->checkedId());
  17826. setLayout(layout);
  17827. connect(buttonTextEdit, SIGNAL(textChanged(QString)),
  17828. this, SLOT(updateStartButtonText(QString)));
  17829. connect(stopButtonEdit, SIGNAL(textChanged(QString)),
  17830. this, SLOT(updateStopButtonText(QString)));
  17831. connect(startColumnName, SIGNAL(textChanged(QString)),
  17832. this, SLOT(updateStartColumnName(QString)));
  17833. connect(stopColumnName, SIGNAL(textChanged(QString)),
  17834. this, SLOT(updateStopColumnName(QString)));
  17835. connect(startValue, SIGNAL(textChanged(QString)),
  17836. this, SLOT(updateStartValue(QString)));
  17837. connect(stopValue, SIGNAL(textChanged(QString)),
  17838. this, SLOT(updateStopValue(QString)));
  17839. connect(startOptionGroup, SIGNAL(buttonClicked(int)),
  17840. this, SLOT(updateStartTrigger(int)));
  17841. connect(stopOptionGroup, SIGNAL(buttonClicked(int)),
  17842. this, SLOT(updateStopTrigger(int)));
  17843. }
  17844. @ Small methods update the configuration as usual.
  17845. @<RangeTimerConfWidget implementation@>=
  17846. void RangeTimerConfWidget::updateStartButtonText(const QString &text)
  17847. {
  17848. updateAttribute("startbuttontext", text);
  17849. }
  17850. void RangeTimerConfWidget::updateStopButtonText(const QString &text)
  17851. {
  17852. updateAttribute("stopbuttontext", text);
  17853. }
  17854. void RangeTimerConfWidget::updateStartColumnName(const QString &text)
  17855. {
  17856. updateAttribute("startcolumnname", text);
  17857. }
  17858. void RangeTimerConfWidget::updateStopColumnName(const QString &text)
  17859. {
  17860. updateAttribute("stopcolumnname", text);
  17861. }
  17862. void RangeTimerConfWidget::updateStartValue(const QString &text)
  17863. {
  17864. updateAttribute("startvalue", text);
  17865. }
  17866. void RangeTimerConfWidget::updateStopValue(const QString &text)
  17867. {
  17868. updateAttribute("stopvalue", text);
  17869. }
  17870. void RangeTimerConfWidget::updateStartTrigger(int option)
  17871. {
  17872. switch(option)
  17873. {
  17874. case 1:
  17875. updateAttribute("starttrigger", "batch");
  17876. break;
  17877. case 2:
  17878. updateAttribute("starttrigger", "manual");
  17879. break;
  17880. case 3:
  17881. updateAttribute("starttrigger", "value");
  17882. break;
  17883. default:
  17884. break;
  17885. }
  17886. }
  17887. void RangeTimerConfWidget::updateStopTrigger(int option)
  17888. {
  17889. switch(option)
  17890. {
  17891. case 1:
  17892. updateAttribute("stoptrigger", "batch");
  17893. break;
  17894. case 2:
  17895. updateAttribute("stoptrigger", "manual");
  17896. break;
  17897. case 3:
  17898. updateAttribute("stoptrigger", "value");
  17899. break;
  17900. default:
  17901. break;
  17902. }
  17903. }
  17904. @ The widget is registered with the configuration system.
  17905. @<Register device configuration widgets@>=
  17906. app.registerDeviceConfigurationWidget("rangetimer",
  17907. RangeTimerConfWidget::staticMetaObject);
  17908. @ The implementation chunk for now is in the main source file.
  17909. @<Class implementations@>=
  17910. @<RangeTimerConfWidget implementation@>
  17911. @ The multirange timer is a little different. To keep configuration tractible,
  17912. this is slightly less general purpose than the range timer and only supports
  17913. automatic triggering on a single data series.
  17914. @<Class declarations@>=
  17915. class MultiRangeTimerConfWidget : public BasicDeviceConfigurationWidget
  17916. {
  17917. @[Q_OBJECT@]@/
  17918. public:@/
  17919. @[Q_INVOKABLE@]@, MultiRangeTimerConfWidget(DeviceTreeModel *model,
  17920. const QModelIndex &index);
  17921. @[private slots@]:@/
  17922. void updateColumnName(const QString &text);
  17923. void updateRangeData();
  17924. private:@/
  17925. SaltModel *tablemodel;
  17926. };
  17927. @ These limitations allow a rather small set of controls for configuration. A
  17928. line edit to specify the data series used for automatic triggering and a table
  17929. which specifies the name of the timed range and an ending temperature.
  17930. @<MultiRangeTimerConfWidget implementation@>=
  17931. MultiRangeTimerConfWidget::MultiRangeTimerConfWidget(DeviceTreeModel *model,
  17932. const QModelIndex &index)
  17933. : BasicDeviceConfigurationWidget(model, index), tablemodel(new SaltModel(2))
  17934. {
  17935. QFormLayout *layout = new QFormLayout;
  17936. QLineEdit *trigger = new QLineEdit;
  17937. layout->addRow(tr("Trigger column name:"), trigger);
  17938. tablemodel->setHeaderData(0, Qt::Horizontal, "Range Name");
  17939. tablemodel->setHeaderData(1, Qt::Horizontal, "End Temperature");
  17940. QTableView *rangeTable = new QTableView;
  17941. rangeTable->setModel(tablemodel);
  17942. layout->addRow(tr("Range data:"), rangeTable);
  17943. @<Get device configuration data for current node@>@;
  17944. for(int i = 0; i < configData.size(); i++)
  17945. {
  17946. node = configData.at(i).toElement();
  17947. if(node.attribute("name") == "trigger")
  17948. {
  17949. trigger->setText(node.attribute("value"));
  17950. }
  17951. else if(node.attribute("name") == "rangenames")
  17952. {
  17953. QString data = node.attribute("value");
  17954. if(data.length() > 3)
  17955. {
  17956. data.chop(2);
  17957. data = data.remove(0, 2);
  17958. }
  17959. QStringList itemList = data.split(", ");
  17960. for(int j = 0; j < itemList.size(); j++)
  17961. {
  17962. QString item = itemList.at(j);
  17963. item.chop(1);
  17964. item = item.remove(0, 1);
  17965. tablemodel->setData(tablemodel->index(j, 0),
  17966. QVariant(item), Qt::DisplayRole);
  17967. }
  17968. }
  17969. else if(node.attribute("name") == "endtemps")
  17970. {
  17971. @<Convert numeric array literal to list@>@;
  17972. int column = 1;
  17973. @<Populate model column from list@>@;
  17974. }
  17975. }
  17976. updateColumnName(trigger->text());
  17977. updateRangeData();
  17978. connect(trigger, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  17979. connect(tablemodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateRangeData()));
  17980. setLayout(layout);
  17981. }
  17982. @ The update mechanisms are reasonably straightforward. Table updates just
  17983. refresh the entire table instead of attempting to be clever about updating only
  17984. the element that changed.
  17985. @<MultiRangeTimerConfWidget implementation@>=
  17986. void MultiRangeTimerConfWidget::updateRangeData()
  17987. {
  17988. updateAttribute("rangenames", tablemodel->quotedArrayLiteral(0, Qt::DisplayRole));
  17989. updateAttribute("endtemps", tablemodel->arrayLiteral(1, Qt::DisplayRole));
  17990. }
  17991. void MultiRangeTimerConfWidget::updateColumnName(const QString &text)
  17992. {
  17993. updateAttribute("trigger", text);
  17994. }
  17995. @ The widget is registered with the configuration system.
  17996. @<Register device configuration widgets@>=
  17997. app.registerDeviceConfigurationWidget("multirangetimer",
  17998. MultiRangeTimerConfWidget::staticMetaObject);
  17999. @ The implementation is in the main source file.
  18000. @<Class implementations@>=
  18001. @<MultiRangeTimerConfWidget implementation@>
  18002. @* Profile Translation Configuration Widget.
  18003. \noindent Configuring profile translation requires knowing which column to use
  18004. for matching purposes and the value to match.
  18005. @<Class declarations@>=
  18006. class TranslationConfWidget : public BasicDeviceConfigurationWidget
  18007. {
  18008. @[Q_OBJECT@]@;
  18009. public:@/
  18010. @[Q_INVOKABLE@]@, TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  18011. @[private slots@]:@/
  18012. void updateMatchingColumn(const QString &column);
  18013. void updateTemperature();
  18014. void updateDelay();
  18015. private:@/
  18016. QDoubleSpinBox *temperatureValue;
  18017. QComboBox *unitSelector;
  18018. QSpinBox *delaySelector;
  18019. };
  18020. @ The constructor sets up our user interface.
  18021. @<TranslationConfWidget implementation@>=
  18022. TranslationConfWidget::TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  18023. : BasicDeviceConfigurationWidget(model, index),
  18024. temperatureValue(new QDoubleSpinBox), unitSelector(new QComboBox),
  18025. delaySelector(new QSpinBox)
  18026. {
  18027. unitSelector->addItem("Fahrenheit");
  18028. unitSelector->addItem("Celsius");
  18029. temperatureValue->setMinimum(0);
  18030. temperatureValue->setMaximum(1000);
  18031. QFormLayout *layout = new QFormLayout;
  18032. QLineEdit *column = new QLineEdit;
  18033. layout->addRow(tr("Column to match:"), column);
  18034. layout->addRow(tr("Unit:"), unitSelector);
  18035. layout->addRow(tr("Value:"), temperatureValue);
  18036. layout->addRow(tr("Start of batch safety delay:"), delaySelector);
  18037. @<Get device configuration data for current node@>@;
  18038. for(int i = 0; i < configData.size(); i++)
  18039. {
  18040. node = configData.at(i).toElement();
  18041. if(node.attribute("name") == "column")
  18042. {
  18043. column->setText(node.attribute("value"));
  18044. }
  18045. else if(node.attribute("name") == "unit")
  18046. {
  18047. unitSelector->setCurrentIndex(unitSelector->findText(node.attribute("value")));
  18048. }
  18049. else if(node.attribute("name") == "value")
  18050. {
  18051. temperatureValue->setValue(node.attribute("value").toDouble());
  18052. }
  18053. else if(node.attribute("name") == "delay")
  18054. {
  18055. delaySelector->setValue(node.attribute("value").toInt());
  18056. }
  18057. }
  18058. updateMatchingColumn(column->text());
  18059. updateTemperature();
  18060. updateDelay();
  18061. connect(column, SIGNAL(textEdited(QString)), this, SLOT(updateMatchingColumn(QString)));
  18062. connect(unitSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateTemperature()));
  18063. connect(temperatureValue, SIGNAL(valueChanged(double)), this, SLOT(updateTemperature()));
  18064. connect(delaySelector, SIGNAL(valueChanged(int)), this, SLOT(updateDelay()));
  18065. setLayout(layout);
  18066. }
  18067. @ To update the temperature at which to match we save both the values of the
  18068. two widgets which control this and the value in Fahrenheit so we don'@q'@>t need to
  18069. run unit conversions during view initialization.
  18070. @<TranslationConfWidget implementation@>=
  18071. void TranslationConfWidget::updateTemperature()
  18072. {
  18073. updateAttribute("unit", unitSelector->currentText());
  18074. updateAttribute("value", QString("%1").arg(temperatureValue->value()));
  18075. if(unitSelector->currentText() == "Fahrenheit")
  18076. {
  18077. updateAttribute("FValue", QString("%1").arg(temperatureValue->value()));
  18078. }
  18079. else
  18080. {
  18081. updateAttribute("FValue", QString("%1").arg(temperatureValue->value() * 9 / 5 + 32));
  18082. }
  18083. }
  18084. void TranslationConfWidget::updateMatchingColumn(const QString &column)
  18085. {
  18086. updateAttribute("column", column);
  18087. }
  18088. void TranslationConfWidget::updateDelay()
  18089. {
  18090. updateAttribute("delay", QString("%1").arg(delaySelector->value()));
  18091. }
  18092. @ This is registered with the configuration system.
  18093. @<Register device configuration widgets@>=
  18094. app.registerDeviceConfigurationWidget("translation", TranslationConfWidget::staticMetaObject);
  18095. @i rate.w
  18096. @i mergeseries.w
  18097. @i dataqsdk.w
  18098. @i scales.w
  18099. @i valueannotation.w
  18100. @i thresholdannotation.w
  18101. @i user.w
  18102. @i roastcoloredit.w
  18103. @** Local changes.
  18104. \noindent This is the end of \pn{} as distributed by its author. It is expected
  18105. that some might have need of a program like \pn, but require some modification.
  18106. The patching capabilities of \cweb{} can be used to produce these local
  18107. modifications. This section is provided for those whose change requirements are
  18108. sufficiently extensive to require the introduction of new sections to the
  18109. program.
  18110. @** Index.
  18111. \noindent Following is a list of identifiers used in \pn, with underlined
  18112. entries pointing to where \cweb{} has guessed that the identifier was defined.
  18113. All references are to section numbers instead of page numbers.
  18114. \def\nullsec{--}