mainform.cpp 232 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276
  1. /*
  2. ktigcc - TIGCC IDE for KDE
  3. Copyright (C) 2004-2007 Kevin Kofler
  4. Copyright (C) 2006 Joey Adams
  5. Copyright (C) 2007 Konrad Meyer
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software Foundation,
  16. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  17. */
  18. #include <k3listview.h>
  19. class DnDListView : public K3ListView {
  20. private:
  21. public:
  22. DnDListView (QWidget * parent = 0) : K3ListView(parent) {}
  23. // Make my hand-coded drag&drop code work (public part).
  24. // Maybe the built-in drag&drop support in K3ListView could be made to work as
  25. // expected, but for now just bypass it to use the existing code I wrote for
  26. // QListView.
  27. virtual void takeItem(Q3ListViewItem *i) {Q3ListView::takeItem(i);}
  28. virtual void setAcceptDrops(bool on) {Q3ListView::setAcceptDrops(on);}
  29. protected:
  30. virtual Q3DragObject *dragObject();
  31. virtual void dropEvent (QDropEvent *e);
  32. virtual void dragEnterEvent (QDragEnterEvent *e);
  33. virtual void dragMoveEvent (QDragMoveEvent *e);
  34. // Make my hand-coded drag&drop code work (protected part).
  35. virtual void contentsDragMoveEvent(QDragMoveEvent *e) {
  36. Q3ListView::contentsDragMoveEvent(e);
  37. }
  38. virtual void contentsMouseMoveEvent(QMouseEvent *e) {
  39. Q3ListView::contentsMouseMoveEvent(e);
  40. }
  41. virtual void contentsDragLeaveEvent(QDragLeaveEvent *e) {
  42. Q3ListView::contentsDragLeaveEvent(e);
  43. }
  44. virtual void contentsDropEvent(QDropEvent *e) {
  45. Q3ListView::contentsDropEvent(e);
  46. }
  47. virtual void contentsDragEnterEvent(QDragEnterEvent *e) {
  48. Q3ListView::contentsDragEnterEvent(e);
  49. }
  50. virtual void startDrag() {
  51. Q3ListView::startDrag();
  52. }
  53. virtual void rename(Q3ListViewItem *item, int c);
  54. virtual void keyPressEvent(QKeyEvent *e);
  55. };
  56. // Yes, this is an ugly hack... Any better suggestions?
  57. #define K3ListView DnDListView
  58. #include "mainform.h"
  59. #undef K3ListView
  60. #include <QVariant>
  61. #include <QHash>
  62. #include <QImage>
  63. #include <QString>
  64. #include <QStringList>
  65. #include <QByteArray>
  66. #include <QPair>
  67. #include <QRegExp>
  68. #include <QApplication>
  69. #include <QLabel>
  70. #include <QStatusBar>
  71. #include <QTimer>
  72. #include <QDateTime>
  73. #include <Q3DragObject>
  74. #include <QDir>
  75. #include <QClipboard>
  76. #include <QShortcut>
  77. #include <QEventLoop>
  78. #include <QCoreApplication>
  79. #include <QDockWidget>
  80. #include <QFileInfo>
  81. #include <QDateTime>
  82. #include <QTextCodec>
  83. #include <QTextDocument>
  84. #include <QTimer>
  85. #include <QToolButton>
  86. #include <Q3ListBox>
  87. #include <QTimerEvent>
  88. #include <Q3PtrList>
  89. #include <QList>
  90. #include <QVector>
  91. #include <QDragMoveEvent>
  92. #include <QDragLeaveEvent>
  93. #include <QKeyEvent>
  94. #include <QResizeEvent>
  95. #include <QEvent>
  96. #include <QDropEvent>
  97. #include <Q3PopupMenu>
  98. #include <QDragEnterEvent>
  99. #include <QPixmap>
  100. #include <QMouseEvent>
  101. #include <QCloseEvent>
  102. #include <QAssistantClient>
  103. #include <QDBusConnection>
  104. #include <QDBusReply>
  105. #include <QAction>
  106. #include <kapplication.h>
  107. #include <kparts/factory.h>
  108. #include <klibloader.h>
  109. #include <ktexteditor/editor.h>
  110. #include <ktexteditor/document.h>
  111. #include <ktexteditor/view.h>
  112. #include <ktexteditor/cursor.h>
  113. #include <ktexteditor/range.h>
  114. #include <ktexteditor/smartcursor.h>
  115. #include <ktexteditor/smartinterface.h>
  116. #include <ktexteditor/commandinterface.h>
  117. #include <ktexteditor/configinterface.h>
  118. #include <kconfig.h>
  119. #include <kconfiggroup.h>
  120. #include <ktexteditor/configpage.h>
  121. #include <kaboutdata.h>
  122. #include <khelpmenu.h>
  123. #include <kfiledialog.h>
  124. #include <kurl.h>
  125. #include <kmessagebox.h>
  126. #include <kdirwatch.h>
  127. #include <kfinddialog.h>
  128. #include <kfind.h>
  129. #include <kreplacedialog.h>
  130. #include <kreplace.h>
  131. #include <kglobal.h>
  132. #include <kicontheme.h>
  133. #include <kicon.h>
  134. #include <kiconloader.h>
  135. #include <kprocess.h>
  136. #include <kshell.h>
  137. #include <ktextbrowser.h>
  138. #include <krun.h>
  139. #include <kpushbutton.h>
  140. #include <kmacroexpander.h>
  141. #include <kstandardaction.h>
  142. #include <kactioncollection.h>
  143. #include <cstdio>
  144. #include <cstdlib>
  145. #include <cstring>
  146. #include <unistd.h>
  147. #include <glib.h>
  148. #include <ticonv.h>
  149. #include <ticables.h>
  150. #include <tifiles.h>
  151. #include <ticalcs.h>
  152. #include "ktigcc.h"
  153. #include "srcfilewin.h"
  154. #include "tpr.h"
  155. #include "preferences.h"
  156. #include "projectoptions.h"
  157. #include "errorlist.h"
  158. #include "programoutput.h"
  159. #include "tiemu.h"
  160. #include "callbacks.h"
  161. #include "parsing.h"
  162. #include "functions.h"
  163. #include "toolsdlg.h"
  164. #include "newsdlg.h"
  165. #include "completion.h"
  166. #if defined(Q_WS_X11)
  167. #include <kwindowsystem.h>
  168. #define ACTIVATE_WINDOW(winid) KWindowSystem::activateWindow(winid)
  169. #elif defined(Q_WS_WIN)
  170. #include <windows.h>
  171. #define ACTIVATE_WINDOW(winid) SetForegroundWindow(winid)
  172. #else
  173. #define ACTIVATE_WINDOW(winid) ((void)0)
  174. #endif
  175. using std::puts;
  176. using std::exit;
  177. #define TIGCC_TPR_Filter "*.tpr|TIGCC Projects (*.tpr)\n"
  178. #define TIGCC_H_Filter "*.h|Header Files (*.h)\n"
  179. #define TIGCC_C_Filter "*.c|C Files (*.c)\n"
  180. #define TIGCC_S_Filter "*.s|GNU Assembly Files (*.s)\n"
  181. #define TIGCC_ASM_Filter "*.asm|A68k Assembly Files (*.asm)\n"
  182. #define TIGCC_QLL_Filter "*.qll|Quill Files (*.qll)\n"
  183. #define TIGCC_O_Filter "*.o|Object Files (*.o)\n"
  184. #define TIGCC_A_Filter "*.a|Archive Files (*.a)\n"
  185. #define TIGCC_TXT_Filter "*.txt|Text Files (*.txt)\n"
  186. #define TIGCCAllFilter "*|All Files (*)"
  187. enum {TIGCCOpenProjectFileFilter,TIGCCAddFilesFilter};
  188. #define IS_CATEGORY(item) ((item) && ((item)==hFilesListItem \
  189. || (item)==cFilesListItem \
  190. || (item)==sFilesListItem \
  191. || (item)==asmFilesListItem \
  192. || (item)==qllFilesListItem \
  193. || (item)==oFilesListItem \
  194. || (item)==aFilesListItem \
  195. || (item)==txtFilesListItem \
  196. || (item)==othFilesListItem))
  197. #define IS_EDITABLE_CATEGORY(item) ((item) && ((item)==hFilesListItem \
  198. || (item)==cFilesListItem \
  199. || (item)==sFilesListItem \
  200. || (item)==asmFilesListItem \
  201. || (item)==qllFilesListItem \
  202. || (item)==txtFilesListItem))
  203. #define IS_FOLDER(item) ((item) && (item)->rtti()==0x716CC0)
  204. #define IS_FILE(item) ((item) && (item)->rtti()==0x716CC1)
  205. #define CATEGORY_OF(category,item) Q3ListViewItem *category=(item); \
  206. while (category->parent()->rtti()==0x716CC0) \
  207. category=category->parent()
  208. #define COUNTER_FOR_CATEGORY(category) ((category)==hFilesListItem?hFileCount: \
  209. (category)==cFilesListItem?cFileCount: \
  210. (category)==sFilesListItem?sFileCount: \
  211. (category)==asmFilesListItem?asmFileCount: \
  212. (category)==qllFilesListItem?qllFileCount: \
  213. (category)==oFilesListItem?oFileCount: \
  214. (category)==aFilesListItem?aFileCount: \
  215. (category)==txtFilesListItem?txtFileCount: \
  216. othFileCount)
  217. #define CURRENT_VIEW (static_cast<KTextEditor::View *>(widgetStack->visibleWidget()))
  218. #define SYSICON(sysname,name) (preferences.useSystemIcons?KIconLoader::global()->loadIcon((sysname),KIconLoader::Small,KIconLoader::SizeSmall):QPixmap(":/images/" name))
  219. #define SET_TEXT_SAFE(doc,text) do { \
  220. disableViewEvents=TRUE; \
  221. (doc)->setText((text)); \
  222. disableViewEvents=FALSE; \
  223. } while(0)
  224. static Q3ListViewItem *currentListItem;
  225. static Q3ListViewItem *replaceCurrentDocument;
  226. static int replaceCurrentLine;
  227. static bool compiling;
  228. class KReplaceWithSelection : public KReplace {
  229. public:
  230. KReplaceWithSelection(const QString &pattern, const QString &replacement,
  231. long options, QWidget *parent=0) :
  232. KReplace(pattern,replacement,options,parent), m_haveSelection(FALSE) {}
  233. void setSelection(int selStartLine, int selStartCol,
  234. int selEndLine, int selEndCol)
  235. {
  236. m_haveSelection=TRUE;
  237. m_selStartLine=selStartLine;
  238. m_selStartCol=selStartCol;
  239. m_selEndLine=selEndLine;
  240. m_selEndCol=selEndCol;
  241. }
  242. void setSelection(const KTextEditor::Range &selRange)
  243. {
  244. m_haveSelection=TRUE;
  245. selRange.start().position(m_selStartLine,m_selStartCol);
  246. selRange.end().position(m_selEndLine,m_selEndCol);
  247. }
  248. void invalidateSelection() {m_haveSelection=FALSE;}
  249. bool haveSelection() {
  250. // If another document was put under the cursor, invalidate selection.
  251. // The m_haveSelection&& is technically redundant, but necessary to avoid
  252. // possible undefined behavior if replaceCurrentDocument has been deleted.
  253. if (m_haveSelection&&currentListItem!=replaceCurrentDocument)
  254. m_haveSelection=FALSE;
  255. return m_haveSelection;
  256. }
  257. int selStartLine() {return m_selStartLine;}
  258. int selStartCol() {return m_selStartCol;}
  259. int selEndLine() {return m_selEndLine;}
  260. int selEndCol() {return m_selEndCol;}
  261. // Override to ask for restarting when replacing in a selection.
  262. bool shouldRestart(bool forceAsking=FALSE, bool showNumMatches=TRUE)
  263. {
  264. return KReplace::shouldRestart(forceAsking||m_haveSelection,showNumMatches);
  265. }
  266. protected:
  267. virtual bool validateMatch(const QString &text, int index, int matchedlength)
  268. {
  269. if (!KReplace::validateMatch(text,index,matchedlength)) return FALSE;
  270. // If another document was put under the cursor, invalidate selection.
  271. // The m_haveSelection&& is technically redundant, but necessary to avoid
  272. // possible undefined behavior if replaceCurrentDocument has been deleted.
  273. if (m_haveSelection&&currentListItem!=replaceCurrentDocument)
  274. m_haveSelection=FALSE;
  275. if (!m_haveSelection) return TRUE;
  276. if (replaceCurrentLine==m_selStartLine && replaceCurrentLine==m_selEndLine)
  277. return (index>=m_selStartCol)&&(index+matchedlength<=m_selEndCol);
  278. else if (replaceCurrentLine==m_selStartLine)
  279. return (index>=m_selStartCol);
  280. else if (replaceCurrentLine==m_selEndLine)
  281. return (index+matchedlength<=m_selEndCol);
  282. else
  283. return (replaceCurrentLine>=m_selStartLine&&replaceCurrentLine<=m_selEndLine);
  284. }
  285. private:
  286. bool m_haveSelection;
  287. int m_selStartLine, m_selStartCol, m_selEndLine, m_selEndCol;
  288. };
  289. static KReplaceWithSelection *kreplace;
  290. // All the methods are inline because otherwise QT Designer will mistake them
  291. // for slots of the main form.
  292. class ListViewFolder : public K3ListViewItem {
  293. public:
  294. ListViewFolder(Q3ListView *parent) : K3ListViewItem(parent)
  295. {
  296. setPixmap(0,SYSICON("folder","folder1.png"));
  297. setDragEnabled(TRUE);
  298. setDropEnabled(TRUE);
  299. }
  300. ListViewFolder(Q3ListViewItem *parent) : K3ListViewItem(parent)
  301. {
  302. setPixmap(0,SYSICON("folder","folder1.png"));
  303. setDragEnabled(TRUE);
  304. setDropEnabled(TRUE);
  305. }
  306. ListViewFolder(Q3ListView *parent, Q3ListViewItem *after)
  307. : K3ListViewItem(parent, after)
  308. {
  309. setPixmap(0,SYSICON("folder","folder1.png"));
  310. setDropEnabled(TRUE);
  311. setDragEnabled(TRUE);
  312. }
  313. ListViewFolder(Q3ListViewItem *parent, Q3ListViewItem *after)
  314. : K3ListViewItem(parent, after)
  315. {
  316. setPixmap(0,SYSICON("folder","folder1.png"));
  317. setDragEnabled(TRUE);
  318. setDropEnabled(TRUE);
  319. }
  320. virtual int rtti(void) const {return 0x716CC0;}
  321. // Work around gratuitous API difference. Why do I have to do this? That's
  322. // what startRename is a virtual method for. K3ListViewItem should do this.
  323. virtual void startRename(int col)
  324. {
  325. static_cast<K3ListView *>(listView())->rename(this,col);
  326. }
  327. protected:
  328. };
  329. class ListViewFile : public K3ListViewItem {
  330. public:
  331. ListViewFile(Q3ListView *parent) : K3ListViewItem(parent),
  332. kateView(NULL), isNew(TRUE),
  333. modifiedSinceLastCompile(TRUE)
  334. {
  335. setPixmap(0,SYSICON("unknown","filex.png"));
  336. setDragEnabled(TRUE);
  337. setDropEnabled(TRUE);
  338. setRenameEnabled(0,TRUE);
  339. }
  340. ListViewFile(Q3ListViewItem *parent) : K3ListViewItem(parent),
  341. kateView(NULL), isNew(TRUE),
  342. modifiedSinceLastCompile(TRUE)
  343. {
  344. setPixmap(0,SYSICON("unknown","filex.png"));
  345. setDragEnabled(TRUE);
  346. setDropEnabled(TRUE);
  347. setRenameEnabled(0,TRUE);
  348. }
  349. ListViewFile(Q3ListView *parent, Q3ListViewItem *after)
  350. : K3ListViewItem(parent, after), kateView(NULL), isNew(TRUE),
  351. modifiedSinceLastCompile(TRUE)
  352. {
  353. setPixmap(0,SYSICON("unknown","filex.png"));
  354. setDropEnabled(TRUE);
  355. setDragEnabled(TRUE);
  356. setRenameEnabled(0,TRUE);
  357. }
  358. ListViewFile(Q3ListViewItem *parent, Q3ListViewItem *after)
  359. : K3ListViewItem(parent, after), kateView(NULL),
  360. isNew(TRUE), modifiedSinceLastCompile(TRUE)
  361. {
  362. setPixmap(0,SYSICON("unknown","filex.png"));
  363. setDragEnabled(TRUE);
  364. setDropEnabled(TRUE);
  365. setRenameEnabled(0,TRUE);
  366. }
  367. virtual ~ListViewFile()
  368. {
  369. MainForm::deleteErrorsForLVFile(this);
  370. if (kreplace && replaceCurrentDocument==this) {
  371. replaceCurrentDocument=static_cast<Q3ListViewItem *>(NULL);
  372. kreplace->invalidateSelection();
  373. }
  374. if (!fileName.isEmpty() && fileName[0]=='/')
  375. KDirWatch::self()->removeFile(fileName);
  376. if (kateView) {
  377. KTextEditor::Document *doc=kateView->document();
  378. delete kateView;
  379. delete doc;
  380. }
  381. }
  382. virtual int rtti(void) const {return 0x716CC1;}
  383. KTextEditor::View *kateView;
  384. QString fileName; // full name of the file
  385. bool isNew;
  386. bool modifiedSinceLastCompile;
  387. LineStartList lineStartList;
  388. // Work around gratuitous API difference. Why do I have to do this? That's
  389. // what startRename is a virtual method for. K3ListViewItem should do this.
  390. virtual void startRename(int col)
  391. {
  392. static_cast<K3ListView *>(listView())->rename(this,col);
  393. }
  394. protected:
  395. };
  396. class ListViewRoot : public K3ListViewItem {
  397. public:
  398. ListViewRoot(Q3ListView *parent) : K3ListViewItem(parent)
  399. {
  400. setRenameEnabled(0,TRUE);
  401. // dragging not really allowed, but don't let the cursor run around when dragged
  402. setDragEnabled(TRUE);
  403. }
  404. ListViewRoot(Q3ListViewItem *parent) : K3ListViewItem(parent)
  405. {
  406. setRenameEnabled(0,TRUE);
  407. // dragging not really allowed, but don't let the cursor run around when dragged
  408. setDragEnabled(TRUE);
  409. }
  410. ListViewRoot(Q3ListView *parent, Q3ListViewItem *after)
  411. : K3ListViewItem(parent, after)
  412. {
  413. setRenameEnabled(0,TRUE);
  414. // dragging not really allowed, but don't let the cursor run around when dragged
  415. setDragEnabled(TRUE);
  416. }
  417. ListViewRoot(Q3ListViewItem *parent, Q3ListViewItem *after)
  418. : K3ListViewItem(parent, after)
  419. {
  420. setRenameEnabled(0,TRUE);
  421. // dragging not really allowed, but don't let the cursor run around when dragged
  422. setDragEnabled(TRUE);
  423. }
  424. // Work around gratuitous API difference. Why do I have to do this? That's
  425. // what startRename is a virtual method for. K3ListViewItem should do this.
  426. virtual void startRename(int col)
  427. {
  428. static_cast<K3ListView *>(listView())->rename(this,col);
  429. }
  430. protected:
  431. };
  432. // These should be instance variables in clean C++, but QT Designer won't let me
  433. // touch the class definition, so this is all I can do. And there is only one
  434. // instance of MainForm anyway.
  435. static Q3ListViewItem *rootListItem;
  436. static Q3ListViewItem *hFilesListItem;
  437. static Q3ListViewItem *cFilesListItem;
  438. static Q3ListViewItem *sFilesListItem;
  439. static Q3ListViewItem *asmFilesListItem;
  440. static Q3ListViewItem *qllFilesListItem;
  441. static Q3ListViewItem *oFilesListItem;
  442. static Q3ListViewItem *aFilesListItem;
  443. static Q3ListViewItem *txtFilesListItem;
  444. static Q3ListViewItem *othFilesListItem;
  445. static bool projectIsDirty, projectNeedsRelink;
  446. static QLabel *leftStatusLabel;
  447. static QLabel *rowStatusLabel;
  448. static QLabel *colStatusLabel;
  449. static QLabel *charsStatusLabel;
  450. static QLabel *rightStatusLabel;
  451. static KHelpMenu *khelpmenu;
  452. static Q3PopupMenu *te_popup;
  453. static bool headersModified;
  454. static QDockWidget *errorListDock;
  455. static ErrorList *errorList;
  456. static unsigned errorCountTotal=0,errorCountErrors=0,errorCountWarnings=0;
  457. static QString programOutput;
  458. QAssistantClient *assistant;
  459. static unsigned fileCount=0, hFileCount=0, cFileCount=0, sFileCount=0, asmFileCount=0, qllFileCount=0, oFileCount=0, aFileCount=0, txtFileCount=0, othFileCount=0;
  460. tprSettings settings;
  461. tprLibOpts libopts;
  462. static QString projectFileName;
  463. static QString lastDirectory;
  464. QClipboard *clipboard;
  465. static QShortcut *shortcuts[18];
  466. static KFindDialog *kfinddialog;
  467. QStringList findHistory, replacementHistory;
  468. static Q3ListViewItem *findCurrentDocument;
  469. static int findCurrentLine;
  470. QList<SourceFileWindow *> sourceFiles;
  471. static Q3PopupMenu *findFunctionsPopup;
  472. bool have_usb;
  473. Tools tools, tempTools;
  474. int toolIndex;
  475. bool disableViewEvents=FALSE;
  476. Q3DragObject *DnDListView::dragObject() {
  477. Q3ListViewItem *currItem=selectedItem();
  478. if (currItem==rootListItem || currItem->parent()==rootListItem)
  479. return NULL;
  480. Q3StoredDrag *storedDrag=new Q3StoredDrag("x-ktigcc-dnd", this);
  481. static QByteArray data(sizeof(Q3ListViewItem*));
  482. data.duplicate(reinterpret_cast<char *>(&currItem),
  483. sizeof(Q3ListViewItem*));
  484. storedDrag->setEncodedData(data);
  485. return storedDrag;
  486. }
  487. void DnDListView::dropEvent(QDropEvent *e) {
  488. if (!compiling && e->source()==this && e->provides("x-ktigcc-dnd")) {
  489. Q3ListViewItem *currItem;
  490. currItem = *reinterpret_cast<Q3ListViewItem * const *>((const char *)e->encodedData("x-ktigcc-dnd"));
  491. if (IS_FOLDER(currItem) && !IS_CATEGORY(currItem)) {
  492. // dropping folder
  493. // can only drop on folder or category
  494. Q3ListViewItem *item=itemAt(e->pos());
  495. if (IS_FOLDER(item)) {
  496. // need same category
  497. CATEGORY_OF(srcCategory,currItem);
  498. CATEGORY_OF(destCategory,item);
  499. if (srcCategory == destCategory) {
  500. // can't move folder into itself
  501. for (Q3ListViewItem *destFolder=item; IS_FOLDER(destFolder); destFolder=destFolder->parent()) {
  502. if (destFolder==currItem) goto ignore;
  503. }
  504. // move folder
  505. e->accept();
  506. currItem->parent()->takeItem(currItem);
  507. item->insertItem(currItem);
  508. // put it at the right place
  509. if (currItem->nextSibling()) {
  510. Q3ListViewItem *lastItem=currItem->nextSibling();
  511. while(lastItem->nextSibling())
  512. lastItem=lastItem->nextSibling();
  513. currItem->moveItem(lastItem);
  514. }
  515. projectIsDirty=TRUE;
  516. projectNeedsRelink=TRUE;
  517. } else {ignore: e->ignore();}
  518. } else e->ignore();
  519. } else if (IS_FILE(currItem)) {
  520. // dropping file
  521. Q3ListViewItem *item=itemAt(e->pos());
  522. if (IS_FOLDER(item)) {
  523. // drop on folder
  524. // don't allow more than one Quill file per project
  525. CATEGORY_OF(srcCategory,currItem);
  526. CATEGORY_OF(destCategory,item);
  527. if (qllFilesListItem && srcCategory != qllFilesListItem
  528. && destCategory == qllFilesListItem && qllFileCount) {
  529. ignore2: e->ignore();
  530. } else {
  531. // moving from editable to non-editable category -
  532. // prompt for saving
  533. if (IS_EDITABLE_CATEGORY(srcCategory)
  534. && !IS_EDITABLE_CATEGORY(destCategory)) {
  535. if (static_cast<MainForm *>(parent()->parent()->parent())->fileSavePrompt(currItem))
  536. goto ignore2;
  537. if (!static_cast<ListViewFile *>(currItem)->fileName.isEmpty()
  538. && static_cast<ListViewFile *>(currItem)->fileName[0]=='/')
  539. KDirWatch::self()->removeFile(static_cast<ListViewFile *>(currItem)->fileName);
  540. }
  541. // moving from non-editable to editable category
  542. if (!IS_EDITABLE_CATEGORY(srcCategory)
  543. && IS_EDITABLE_CATEGORY(destCategory)) {
  544. static_cast<ListViewFile *>(currItem)->kateView=reinterpret_cast<KTextEditor::View *>(static_cast<MainForm *>(parent()->parent()->parent())->createView(static_cast<ListViewFile *>(currItem)->fileName,QString::null,destCategory));
  545. MainForm::createErrorCursorsForSourceFile(currItem);
  546. // force reloading the text buffer
  547. if (currentListItem==currItem)
  548. currentListItem=NULL;
  549. }
  550. // move file
  551. e->accept();
  552. currItem->parent()->takeItem(currItem);
  553. COUNTER_FOR_CATEGORY(srcCategory)--;
  554. item->insertItem(currItem);
  555. COUNTER_FOR_CATEGORY(destCategory)++;
  556. // put it at the right place
  557. if (IS_FILE(currItem->nextSibling())) {
  558. Q3ListViewItem *lastItem=currItem->nextSibling();
  559. while(IS_FILE(lastItem->nextSibling()))
  560. lastItem=lastItem->nextSibling();
  561. currItem->moveItem(lastItem);
  562. }
  563. projectIsDirty=TRUE;
  564. projectNeedsRelink=TRUE;
  565. setSelected(currItem,TRUE);
  566. ensureItemVisible(currItem);
  567. // update editor and counters
  568. static_cast<MainForm *>(parent()->parent()->parent())->fileTreeClicked(currItem);
  569. // moving from non-editable to editable category
  570. if (!IS_EDITABLE_CATEGORY(srcCategory)
  571. && IS_EDITABLE_CATEGORY(destCategory)) {
  572. if (!static_cast<ListViewFile *>(currItem)->fileName.isEmpty()
  573. && static_cast<ListViewFile *>(currItem)->fileName[0]=='/')
  574. KDirWatch::self()->addFile(static_cast<ListViewFile *>(currItem)->fileName);
  575. }
  576. // moving from editable to non-editable category
  577. if (IS_EDITABLE_CATEGORY(srcCategory)
  578. && !IS_EDITABLE_CATEGORY(destCategory)) {
  579. KTextEditor::Document *doc=static_cast<ListViewFile *>(currItem)->kateView->document();
  580. delete static_cast<ListViewFile *>(currItem)->kateView;
  581. delete doc;
  582. static_cast<ListViewFile *>(currItem)->kateView=NULL;
  583. }
  584. // moving from editable to editable category
  585. if (IS_EDITABLE_CATEGORY(srcCategory)
  586. && IS_EDITABLE_CATEGORY(destCategory)
  587. && srcCategory!=destCategory) {
  588. // update highlighting mode
  589. QString fileText=static_cast<ListViewFile *>(currItem)->kateView->document()->text();
  590. static_cast<ListViewFile *>(currItem)->kateView->document()->setHighlightingMode(
  591. (destCategory==qllFilesListItem?
  592. QLL_HL_MODE:
  593. (destCategory==sFilesListItem||(destCategory==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]=='|'))?
  594. S_HL_MODE:
  595. (destCategory==asmFilesListItem||(destCategory==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]==';'))?
  596. ASM_HL_MODE:
  597. (destCategory==cFilesListItem||destCategory==hFilesListItem)?
  598. C_HL_MODE:
  599. "None"));
  600. }
  601. // update icon
  602. currItem->setPixmap(0,
  603. destCategory==cFilesListItem||destCategory==qllFilesListItem?SYSICON("text-x-csrc","filec.png"):
  604. destCategory==hFilesListItem?SYSICON("text-x-chdr","fileh.png"):
  605. destCategory==sFilesListItem||destCategory==asmFilesListItem?SYSICON("text-x-hex","files.png"):
  606. destCategory==txtFilesListItem?SYSICON("text-plain","filet.png"):
  607. destCategory==oFilesListItem||destCategory==aFilesListItem?SYSICON("application-x-object","fileo.png"):
  608. SYSICON("unknown","filex.png"));
  609. }
  610. } else if (IS_FILE(item)) {
  611. // drop on file
  612. // need same parent, but different items
  613. if (currItem->parent() == item->parent()
  614. && currItem != item) {
  615. // reorder files
  616. // figure out which one is the first
  617. for (Q3ListViewItem *i=currItem->parent()->firstChild();i;
  618. i=i->nextSibling()) {
  619. if (i==currItem) {
  620. // currItem is first, move currItem after item
  621. e->accept();
  622. currItem->moveItem(item);
  623. projectIsDirty=TRUE;
  624. projectNeedsRelink=TRUE;
  625. break;
  626. } else if (i==item) {
  627. // item is first, move currItem before item
  628. e->accept();
  629. currItem->moveItem(item);
  630. item->moveItem(currItem);
  631. projectIsDirty=TRUE;
  632. projectNeedsRelink=TRUE;
  633. break;
  634. }
  635. }
  636. } else e->ignore();
  637. } else e->ignore();
  638. } else e->ignore();
  639. } else e->ignore();
  640. }
  641. void DnDListView::dragEnterEvent(QDragEnterEvent *e) {
  642. if (!compiling && e->source()==this&&(e->provides("x-ktigcc-dnd")))
  643. e->accept();
  644. }
  645. void DnDListView::dragMoveEvent(QDragMoveEvent *e) {
  646. if (!compiling && e->source()==this && e->provides("x-ktigcc-dnd")) {
  647. Q3ListViewItem *currItem;
  648. currItem = *reinterpret_cast<Q3ListViewItem * const *>((const char *)e->encodedData("x-ktigcc-dnd"));
  649. if (IS_FOLDER(currItem) && !IS_CATEGORY(currItem)) {
  650. // dropping folder
  651. // can only drop on folder or category
  652. Q3ListViewItem *item=itemAt(e->pos());
  653. if (IS_FOLDER(item)) {
  654. // need same category
  655. CATEGORY_OF(srcCategory,currItem);
  656. CATEGORY_OF(destCategory,item);
  657. if (srcCategory == destCategory) {
  658. // can't move folder into itself
  659. for (Q3ListViewItem *destFolder=item; IS_FOLDER(destFolder); destFolder=destFolder->parent()) {
  660. if (destFolder==currItem) goto ignore;
  661. }
  662. e->accept();
  663. } else {ignore: e->ignore();}
  664. } else e->ignore();
  665. } else if (IS_FILE(currItem)) {
  666. // dropping file
  667. Q3ListViewItem *item=itemAt(e->pos());
  668. if (IS_FOLDER(item)) {
  669. // drop on folder
  670. // don't allow more than one Quill file per project
  671. CATEGORY_OF(srcCategory,currItem);
  672. CATEGORY_OF(destCategory,item);
  673. if (qllFilesListItem && srcCategory != qllFilesListItem
  674. && destCategory == qllFilesListItem && qllFileCount)
  675. e->ignore();
  676. else
  677. e->accept();
  678. } else if (IS_FILE(item)) {
  679. // drop on file
  680. // need same parent, but different items
  681. if (currItem->parent() == item->parent()
  682. && currItem != item) e->accept(); else e->ignore();
  683. } else e->ignore();
  684. } else e->ignore();
  685. } else e->ignore();
  686. }
  687. // K3ListView::rename won't work properly if I don't do this. :-/
  688. void DnDListView::rename(Q3ListViewItem *item, int c) {
  689. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,1000);
  690. ensureItemVisible(item);
  691. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,1000);
  692. K3ListView::rename(item,c);
  693. }
  694. void DnDListView::keyPressEvent(QKeyEvent *e)
  695. {
  696. if (e->key()==Qt::Key_Delete && e->state()==0) {
  697. Q3ListViewItem *item=currentItem();
  698. if (item)
  699. static_cast<MainForm *>(parent()->parent()->parent())->removeItem(item);
  700. e->accept();
  701. } else QWidget::keyPressEvent(e);
  702. }
  703. enum ErrorTypes {etError, etWarning, etInfo};
  704. class ErrorListItem : public K3ListViewItem {
  705. public:
  706. ErrorListItem(MainForm *pMainForm, ErrorTypes errType,
  707. const QString &errFile, const QString &errFunc,
  708. const QString &errMsg, int errLine, int errColumn)
  709. : K3ListViewItem(errorList->errorListView,
  710. errorList->errorListView->lastItem()),
  711. lvFile(0), srcFile(0), cursor(0), errorLine(-1), errorColumn(0),
  712. mainForm(pMainForm), errorType(errType)
  713. {
  714. QString errMessage=errMsg.trimmed();
  715. if (!errMessage.isEmpty()) errMessage[0]=errMessage[0].toUpper();
  716. switch(errType) {
  717. case etError:
  718. setPixmap(0,SYSICON("dialog-error","error.png"));
  719. break;
  720. case etWarning:
  721. setPixmap(0,SYSICON("dialog-warning","warning.png"));
  722. break;
  723. default:
  724. setPixmap(0,SYSICON("dialog-information","info.png"));
  725. break;
  726. }
  727. setText(0,errMessage);
  728. setText(1,errFile);
  729. setText(2,errFunc=="__exit"?"_exit":
  730. (errFunc=="__main"?"_main":errFunc));
  731. if (!errFile.isEmpty() && !errFile.endsWith(".a")) {
  732. // Look for the source file with the error.
  733. if (!findSourceFile(errFile) && errFile.endsWith(".o")) {
  734. QString errSrcFile=errFile;
  735. int lengthWoExt=errSrcFile.length()-2;
  736. errSrcFile.truncate(lengthWoExt);
  737. errSrcFile.append(".c");
  738. if (!findSourceFile(errSrcFile)) {
  739. errSrcFile.truncate(lengthWoExt);
  740. errSrcFile.append(".s");
  741. if (!findSourceFile(errSrcFile)) {
  742. errSrcFile.truncate(lengthWoExt);
  743. errSrcFile.append(".asm");
  744. findSourceFile(errSrcFile);
  745. }
  746. }
  747. }
  748. // Not found. Try to open it instead.
  749. // Don't do this if the name ends with ".tpr" because that would cause
  750. // openProject to close the current project and load the new one instead.
  751. if (!lvFile && !srcFile && !errFile.endsWith(".tpr",FALSE)) {
  752. if (errFile.contains('/')&&getPathType(errFile)==PATH_FILE)
  753. mainForm->openProject(errFile);
  754. else if (getPathType(QString("%1/include/c/%2").arg(tigcc_base).arg(errFile))==PATH_FILE)
  755. mainForm->openProject(QString("%1/include/c/%2").arg(tigcc_base).arg(errFile));
  756. else if (getPathType(QString("%1/include/asm/%2").arg(tigcc_base).arg(errFile))==PATH_FILE)
  757. mainForm->openProject(QString("%1/include/asm/%2").arg(tigcc_base).arg(errFile));
  758. else if (getPathType(QString("%1/include/s/%2").arg(tigcc_base).arg(errFile))==PATH_FILE)
  759. mainForm->openProject(QString("%1/include/s/%2").arg(tigcc_base).arg(errFile));
  760. findSourceFile(errFile);
  761. }
  762. }
  763. if (errLine!=-1 && (lvFile || srcFile)) {
  764. if (errColumn==-1) errColumn=0;
  765. const LineStartList &lineStartList=lvFile?lvFile->lineStartList
  766. :srcFile->lineStartList;
  767. if (lineStartList.isEmpty()) {
  768. errorLine=errLine;
  769. errorColumn=errColumn;
  770. } else if (errLine<lineStartList.count()) {
  771. QPair<unsigned,unsigned> pos=lineStartList[errLine];
  772. errorLine=(int)pos.first;
  773. errorColumn=(int)pos.second+errColumn;
  774. }
  775. createCursor();
  776. }
  777. if (preferences.jumpToError && errType==etError
  778. && errorList->errorListView->selectedItems().isEmpty()) {
  779. errorList->errorListView->setSelected(this,TRUE);
  780. jumpToLocation();
  781. }
  782. errorCountTotal++;
  783. if (errType==etError) errorCountErrors++;
  784. if (errType==etWarning) errorCountWarnings++;
  785. errorList->errorCount->setText(QString::number(errorCountErrors));
  786. errorList->warningCount->setText(QString::number(errorCountWarnings));
  787. mainForm->projectErrorsAndWarningsAction->setEnabled(TRUE);
  788. mainForm->projectErrorsAndWarnings(TRUE);
  789. }
  790. virtual ~ErrorListItem()
  791. {
  792. if (errorType==etError) errorCountErrors--;
  793. if (errorType==etWarning) errorCountWarnings--;
  794. errorList->errorCount->setText(QString::number(errorCountErrors));
  795. errorList->warningCount->setText(QString::number(errorCountWarnings));
  796. if (!--errorCountTotal) {
  797. mainForm->projectErrorsAndWarnings(FALSE);
  798. mainForm->projectErrorsAndWarningsAction->setEnabled(FALSE);
  799. }
  800. }
  801. virtual int rtti(void) const {return static_cast<int>(errorType);}
  802. void createCursor(void)
  803. {
  804. if (errorLine!=-1) {
  805. KTextEditor::View *kateView=lvFile?lvFile->kateView:(srcFile?srcFile->kateView
  806. :static_cast<KTextEditor::View *>(NULL));
  807. if (kateView && errorLine<kateView->document()->lines()) {
  808. // Extract the main token for the error message.
  809. QString errMessage=text(0);
  810. int quotePos=errMessage.find('\'');
  811. if (quotePos>=0) {
  812. QString token=errMessage.mid(quotePos+1);
  813. int quotePos2=token.find('\'');
  814. if (quotePos2>=0) {
  815. token.truncate(quotePos2);
  816. if (!token.isEmpty()) {
  817. // Skip whitespace up to this token. TIGCC IDE does that too. Must
  818. // have something to do with how source splitting works.
  819. int i=errorColumn;
  820. QString textLine=kateView->document()->line(errorLine);
  821. int lineLength=kateView->document()->lineLength(errorLine);
  822. int tokenLength=token.length();
  823. while ((i<lineLength) && textLine[i].isSpace()
  824. && textLine.mid(i,tokenLength)!=token) i++;
  825. if (textLine.mid(i,tokenLength)==token) errorColumn=i;
  826. }
  827. }
  828. }
  829. KTextEditor::SmartInterface* smart =
  830. qobject_cast<KTextEditor::SmartInterface*>(kateView->document());
  831. cursor=smart->newSmartCursor(errorLine,errorColumn);
  832. }
  833. }
  834. }
  835. void jumpToLocation(void)
  836. {
  837. // If the error corresponds to a list view file, select it. This will also
  838. // instantiate the Kate view and call createCursor for us.
  839. if (lvFile) mainForm->fileTreeClicked(lvFile);
  840. // If it corresponds to an external source file, activate the window.
  841. if (srcFile) ACTIVATE_WINDOW(srcFile->winId());
  842. // Now jump to the cursor's location if we have one.
  843. KTextEditor::View *kateView=lvFile?lvFile->kateView:(srcFile?srcFile->kateView
  844. :static_cast<KTextEditor::View *>(NULL));
  845. if (cursor && kateView)
  846. kateView->setCursorPosition(*cursor);
  847. }
  848. ListViewFile *lvFile;
  849. SourceFileWindow *srcFile;
  850. KTextEditor::SmartCursor *cursor;
  851. private:
  852. int errorLine;
  853. int errorColumn;
  854. MainForm *mainForm;
  855. ErrorTypes errorType;
  856. bool findSourceFile(const QString &fileName)
  857. {
  858. bool inProject;
  859. void *sourceFile;
  860. bool found=mainForm->findSourceFile(inProject,sourceFile,fileName);
  861. if (found) {
  862. if (inProject)
  863. lvFile=reinterpret_cast<ListViewFile *>(sourceFile);
  864. else
  865. srcFile=reinterpret_cast<SourceFileWindow *>(sourceFile);
  866. }
  867. return found;
  868. }
  869. };
  870. // This static helper function is needed because of limitations of both .ui.h
  871. // files and C++: we can't have methods of other classes than MainForm here
  872. // unless we write them into the class definition or Qt Designer gets confused,
  873. // and C++ won't let 2 classes reference each other in methods declared within
  874. // the class definition. And item is of type QListViewItem rather than
  875. // ListViewFile because of another Qt Designer limitation: It isn't possible to
  876. // use custom types in a .ui file method because it doesn't forward-declare them
  877. // properly.
  878. void MainForm::deleteErrorsForLVFile(Q3ListViewItem *item)
  879. {
  880. Q3ListViewItemIterator lvit(errorList->errorListView);
  881. Q3ListViewItem *errorItem;
  882. while ((errorItem=lvit.current())) {
  883. ++lvit;
  884. if (static_cast<ErrorListItem *>(errorItem)->lvFile
  885. ==static_cast<ListViewFile *>(item))
  886. delete errorItem;
  887. }
  888. }
  889. // Another static helper function, in this case because srcfilewin.ui.h doesn't
  890. // have access to ErrorListItem for similar reasons. (I'd have to duplicate the
  891. // class definition, one time with inline functions and one time without.)
  892. void MainForm::deleteErrorsForSrcFile(void *srcFile)
  893. {
  894. Q3ListViewItemIterator lvit(errorList->errorListView);
  895. Q3ListViewItem *errorItem;
  896. while ((errorItem=lvit.current())) {
  897. ++lvit;
  898. if (static_cast<ErrorListItem *>(errorItem)->srcFile
  899. ==reinterpret_cast<SourceFileWindow *>(srcFile))
  900. delete errorItem;
  901. }
  902. }
  903. // And another.
  904. void MainForm::createErrorCursorsForSourceFile(Q3ListViewItem *item)
  905. {
  906. Q3ListViewItemIterator lvit(errorList->errorListView);
  907. Q3ListViewItem *errorItem;
  908. for (errorItem=lvit.current();errorItem;errorItem=(++lvit).current()) {
  909. if (static_cast<ErrorListItem *>(errorItem)->lvFile
  910. ==static_cast<ListViewFile *>(item))
  911. static_cast<ErrorListItem *>(errorItem)->createCursor();
  912. }
  913. }
  914. // And the last.
  915. void MainForm::deleteOverwrittenErrorsIn(void *srcFile)
  916. {
  917. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  918. Q3ListViewItemIterator lvit(errorList->errorListView);
  919. ErrorListItem *errorItem;
  920. while ((errorItem=static_cast<ErrorListItem *>(lvit.current()))) {
  921. ++lvit;
  922. if (errorItem->srcFile==sourceFile && errorItem->cursor) {
  923. int line,col;
  924. errorItem->cursor->position(line,col);
  925. int curline,curcol;
  926. sourceFile->kateView->cursorPosition().position(curline,curcol);
  927. if (curline==line && curcol==col)
  928. delete errorItem;
  929. }
  930. }
  931. }
  932. void MainForm::errorListView_clicked(Q3ListViewItem *item)
  933. {
  934. if (item) {
  935. static_cast<ErrorListItem *>(item)->jumpToLocation();
  936. errorList->setFocus();
  937. }
  938. }
  939. bool MainForm::findSourceFile(bool &inProject, void *&srcFile, const QString &fileName)
  940. {
  941. bool compareAbsPaths=fileName.contains('/');
  942. Q3ListViewItemIterator lvit(fileTree);
  943. Q3ListViewItem *item;
  944. for (item=lvit.current();item;item=(++lvit).current()) {
  945. if (IS_FILE(item)
  946. && (compareAbsPaths?fileName==static_cast<ListViewFile *>(item)->fileName
  947. :fileName==QFileInfo(static_cast<ListViewFile *>(item)->fileName).fileName())) {
  948. inProject=TRUE;
  949. srcFile=static_cast<ListViewFile *>(item);
  950. return TRUE;
  951. }
  952. }
  953. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  954. if (compareAbsPaths?fileName==sourceFile->fileName
  955. :fileName==QFileInfo(sourceFile->fileName).fileName()) {
  956. inProject=FALSE;
  957. srcFile=sourceFile;
  958. return TRUE;
  959. }
  960. }
  961. return FALSE;
  962. }
  963. void sendCommand(KTextEditor::View *view, const QString &cmd)
  964. {
  965. KTextEditor::CommandInterface *cmdIface=
  966. qobject_cast<KTextEditor::CommandInterface*>(view->document()->editor());
  967. KTextEditor::Command *command=cmdIface->queryCommand(cmd);
  968. QString msg; // thrown away
  969. command->exec(view,cmd,msg);
  970. }
  971. void setTabWidth(KTextEditor::View *view, unsigned tabWidth)
  972. {
  973. sendCommand(view,QString("set-tab-width %1").arg(tabWidth));
  974. }
  975. MainForm::MainForm(QWidget* parent, const char* name, Qt::WindowFlags fl)
  976. : QMainWindow(parent, name, fl)
  977. {
  978. setupUi(this);
  979. (void)statusBar();
  980. QPixmap smallIcon(":/images/ktigcc.png");
  981. QPixmap largeIcon(":/images/icon.png");
  982. QIcon windowIcon(smallIcon);
  983. windowIcon.addPixmap(largeIcon);
  984. setWindowIcon(windowIcon);
  985. #ifdef Q_WS_X11
  986. KWindowSystem::setIcons(winId(),largeIcon,smallIcon);
  987. #endif
  988. ticables_library_init();
  989. tifiles_library_init();
  990. ticalcs_library_init();
  991. have_usb=ticables_is_usb_enabled();
  992. compiling=FALSE;
  993. headersModified=FALSE;
  994. loadPreferences();
  995. loadSystemHeaderCompletion();
  996. fileNewFolderAction->setEnabled(FALSE);
  997. te_popup = new Q3PopupMenu(this);
  998. te_popup->insertItem("&Open file at cursor",0);
  999. te_popup->insertItem("&Find symbol declaration",1);
  1000. te_popup->insertSeparator();
  1001. te_popup->insertItem("&Undo",2);
  1002. te_popup->insertItem("&Redo",3);
  1003. te_popup->insertSeparator();
  1004. te_popup->insertItem("&Clear",4);
  1005. te_popup->insertItem("Cu&t",5);
  1006. te_popup->insertItem("Cop&y",6);
  1007. te_popup->insertItem("&Paste",7);
  1008. te_popup->insertSeparator();
  1009. te_popup->insertItem("&Select all",8);
  1010. te_popup->insertSeparator();
  1011. te_popup->insertItem("&Increase indent",9);
  1012. te_popup->insertItem("&Decrease indent",10);
  1013. connect(te_popup,SIGNAL(aboutToShow()),this,SLOT(te_popup_aboutToShow()));
  1014. connect(te_popup,SIGNAL(activated(int)),this,SLOT(te_popup_activated(int)));
  1015. QList<int> list;
  1016. list.append(150);
  1017. list.append(500);
  1018. splitter->setSizes(list);
  1019. leftStatusLabel=new QLabel("0 Files Total",this);
  1020. leftStatusLabel->setMaximumWidth(splitter->sizes().first());
  1021. statusBar()->addWidget(leftStatusLabel,1);
  1022. rowStatusLabel=new QLabel("",this);
  1023. rowStatusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
  1024. statusBar()->addWidget(rowStatusLabel,1);
  1025. rowStatusLabel->hide();
  1026. colStatusLabel=new QLabel("",this);
  1027. colStatusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
  1028. statusBar()->addWidget(colStatusLabel,1);
  1029. colStatusLabel->hide();
  1030. charsStatusLabel=new QLabel("",this);
  1031. statusBar()->addWidget(charsStatusLabel,1);
  1032. charsStatusLabel->hide();
  1033. rightStatusLabel=new QLabel("",this);
  1034. rightStatusLabel->setMaximumWidth(splitter->sizes().last());
  1035. statusBar()->addWidget(rightStatusLabel,1);
  1036. statusBar()->setSizeGripEnabled(FALSE);
  1037. connect(statusBar(),SIGNAL(messageChanged(const QString &)),this,SLOT(statusBar_messageChanged(const QString &)));
  1038. fileTree->setSorting(-1);
  1039. fileTree->setColumnWidthMode(0,Q3ListView::Maximum);
  1040. fileTree->header()->hide();
  1041. fileTree->setAlternateBackground(QColor());
  1042. rootListItem=new ListViewRoot(fileTree);
  1043. rootListItem->setText(0,"Project1");
  1044. rootListItem->setPixmap(0,SYSICON("system-run","tpr.png"));
  1045. rootListItem->setOpen(TRUE);
  1046. Q3ListViewItem *folderListItem=new ListViewFolder(rootListItem);
  1047. hFilesListItem=folderListItem;
  1048. folderListItem->setText(0,"Header Files");
  1049. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1050. cFilesListItem=folderListItem;
  1051. folderListItem->setText(0,"C Files");
  1052. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1053. sFilesListItem=folderListItem;
  1054. folderListItem->setText(0,"GNU Assembly Files");
  1055. char a68k_path[strlen(tigcc_base)+10];
  1056. sprintf(a68k_path, "%s/bin/a68k", tigcc_base);
  1057. if(access(a68k_path, F_OK) != -1) {
  1058. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1059. asmFilesListItem=folderListItem;
  1060. folderListItem->setText(0,"A68k Assembly Files");
  1061. } else {
  1062. asmFilesListItem=NULL;
  1063. fileNewA68kAssemblyHeaderAction->setVisible(FALSE);
  1064. fileNewA68kAssemblySourceFileAction->setVisible(FALSE);
  1065. }
  1066. if (quill_drv) {
  1067. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1068. qllFilesListItem=folderListItem;
  1069. folderListItem->setText(0,"Quill Files");
  1070. } else {
  1071. qllFilesListItem=NULL;
  1072. fileNewQuillSourceFileAction->setVisible(FALSE);
  1073. }
  1074. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1075. oFilesListItem=folderListItem;
  1076. folderListItem->setText(0,"Object Files");
  1077. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1078. aFilesListItem=folderListItem;
  1079. folderListItem->setText(0,"Archive Files");
  1080. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1081. txtFilesListItem=folderListItem;
  1082. folderListItem->setText(0,"Text Files");
  1083. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1084. othFilesListItem=folderListItem;
  1085. folderListItem->setText(0,"Other Files");
  1086. khelpmenu=new KHelpMenu(this,pabout);
  1087. assistant=new QAssistantClient("",this);
  1088. QStringList args(QString("-profile"));
  1089. args.append(QString("%1/doc/html/qt-assistant.adp").arg(tigcc_base));
  1090. assistant->setArguments(args);
  1091. lastDirectory=QString("%1/tigcc-projects").arg(QDir::homePath());
  1092. if (!QDir(lastDirectory).exists() && !QDir().mkdir(lastDirectory))
  1093. lastDirectory=QString("%1/projects").arg(tigcc_base);
  1094. projectFileName="";
  1095. projectIsDirty=FALSE;
  1096. projectNeedsRelink=FALSE;
  1097. connect(KDirWatch::self(),SIGNAL(created(const QString &)),this,SLOT(KDirWatch_dirty(const QString &)));
  1098. connect(KDirWatch::self(),SIGNAL(dirty(const QString &)),this,SLOT(KDirWatch_dirty(const QString &)));
  1099. KDirWatch::self()->startScan();
  1100. clipboard=QApplication::clipboard();
  1101. connect(clipboard,SIGNAL(dataChanged()),this,SLOT(clipboard_dataChanged()));
  1102. shortcuts[0]=new QShortcut(Qt::ALT+Qt::Key_Backspace,this);
  1103. shortcuts[0]->setEnabled(FALSE);
  1104. shortcuts[1]=new QShortcut(Qt::SHIFT+Qt::ALT+Qt::Key_Backspace,this);
  1105. shortcuts[1]->setEnabled(FALSE);
  1106. shortcuts[2]=new QShortcut(Qt::SHIFT+Qt::Key_Delete,this);
  1107. shortcuts[2]->setEnabled(FALSE);
  1108. shortcuts[3]=new QShortcut(Qt::CTRL+Qt::Key_Insert,this);
  1109. shortcuts[3]->setEnabled(FALSE);
  1110. shortcuts[4]=new QShortcut(Qt::SHIFT+Qt::Key_Insert,this);
  1111. shortcuts[4]->setEnabled(FALSE);
  1112. shortcuts[5]=new QShortcut(Qt::Key_F1,this);
  1113. shortcuts[5]->setEnabled(FALSE);
  1114. shortcuts[6]=new QShortcut(Qt::Key_Enter,this);
  1115. shortcuts[6]->setEnabled(FALSE);
  1116. shortcuts[7]=new QShortcut(Qt::Key_Return,this);
  1117. shortcuts[7]->setEnabled(FALSE);
  1118. shortcuts[8]=new QShortcut(Qt::CTRL+Qt::Key_J,this);
  1119. shortcuts[8]->setEnabled(FALSE);
  1120. shortcuts[9]=new QShortcut(Qt::CTRL+Qt::Key_Space,this);
  1121. shortcuts[9]->setEnabled(FALSE);
  1122. shortcuts[10]=new QShortcut(Qt::CTRL+Qt::Key_M,this);
  1123. shortcuts[10]->setEnabled(FALSE);
  1124. shortcuts[11]=new QShortcut(Qt::CTRL+Qt::Key_Tab,this);
  1125. shortcuts[11]->setEnabled(TRUE);
  1126. shortcuts[12]=new QShortcut(Qt::CTRL+Qt::Key_G,this);
  1127. shortcuts[12]->setEnabled(TRUE);
  1128. shortcuts[13]=new QShortcut(Qt::SHIFT+Qt::CTRL+Qt::ALT+Qt::Key_F9,this);
  1129. shortcuts[13]->setEnabled(TRUE);
  1130. shortcuts[14]=new QShortcut(Qt::SHIFT+Qt::ALT+Qt::Key_F8,this);
  1131. shortcuts[14]->setEnabled(TRUE);
  1132. shortcuts[15]=new QShortcut(Qt::CTRL+Qt::ALT+Qt::Key_F9,this);
  1133. shortcuts[15]->setEnabled(TRUE);
  1134. shortcuts[16]=new QShortcut(Qt::CTRL+Qt::Key_F9,this);
  1135. shortcuts[16]->setEnabled(TRUE);
  1136. shortcuts[17]=new QShortcut(Qt::CTRL+Qt::Key_Return,this);
  1137. shortcuts[17]->setEnabled(FALSE);
  1138. connect(shortcuts[0],SIGNAL(activated()),this,SLOT(shortcut_0_activated()));
  1139. connect(shortcuts[1],SIGNAL(activated()),this,SLOT(shortcut_1_activated()));
  1140. connect(shortcuts[2],SIGNAL(activated()),this,SLOT(shortcut_2_activated()));
  1141. connect(shortcuts[3],SIGNAL(activated()),this,SLOT(shortcut_3_activated()));
  1142. connect(shortcuts[4],SIGNAL(activated()),this,SLOT(shortcut_4_activated()));
  1143. connect(shortcuts[5],SIGNAL(activated()),this,SLOT(shortcut_5_activated()));
  1144. connect(shortcuts[6],SIGNAL(activated()),this,SLOT(shortcut_6_activated()));
  1145. connect(shortcuts[7],SIGNAL(activated()),this,SLOT(shortcut_7_activated()));
  1146. connect(shortcuts[8],SIGNAL(activated()),this,SLOT(shortcut_8_activated()));
  1147. connect(shortcuts[9],SIGNAL(activated()),this,SLOT(shortcut_9_activated()));
  1148. connect(shortcuts[10],SIGNAL(activated()),this,SLOT(shortcut_10_activated()));
  1149. connect(shortcuts[11],SIGNAL(activated()),this,SLOT(shortcut_11_activated()));
  1150. connect(shortcuts[12],SIGNAL(activated()),this,SLOT(shortcut_12_activated()));
  1151. connect(shortcuts[13],SIGNAL(activated()),this,SLOT(shortcut_13_activated()));
  1152. connect(shortcuts[14],SIGNAL(activated()),this,SLOT(shortcut_14_activated()));
  1153. connect(shortcuts[15],SIGNAL(activated()),this,SLOT(shortcut_15_activated()));
  1154. connect(shortcuts[16],SIGNAL(activated()),this,SLOT(shortcut_16_activated()));
  1155. connect(shortcuts[17],SIGNAL(activated()),this,SLOT(findOpenFileAtCursor()));
  1156. kfinddialog = static_cast<KFindDialog *>(NULL);
  1157. kreplace = static_cast<KReplaceWithSelection *>(NULL);
  1158. connect(fileNewAction,SIGNAL(triggered()),this,SLOT(fileNewProject()));
  1159. if (preferences.useSystemIcons) {
  1160. // Set the preferred icon size so system toolbar icons don't get annoying
  1161. // padding.
  1162. int toolbarIconSize=KIconLoader().currentSize(KIconLoader::MainToolbar);
  1163. setIconSize(QSize(toolbarIconSize,toolbarIconSize));
  1164. fileNewAction->setIcon(KIcon("document-new"));
  1165. fileNewMenu->menuAction()->setIcon(KIcon("document-new"));
  1166. fileOpenAction->setIcon(KIcon("document-open"));
  1167. fileSaveAllAction->setIcon(KIcon("document-save"));
  1168. filePrintAction->setIcon(KIcon("document-print"));
  1169. filePrintQuicklyAction->setIcon(KIcon("document-print"));
  1170. editClearAction->setIcon(KIcon("edit-delete"));
  1171. editCutAction->setIcon(KIcon("edit-cut"));
  1172. editCopyAction->setIcon(KIcon("edit-copy"));
  1173. editPasteAction->setIcon(KIcon("edit-paste"));
  1174. projectAddFilesAction->setIcon(KIcon("list-add"));
  1175. projectCompileAction->setIcon(KIcon("run-build-file"));
  1176. projectMakeAction->setIcon(KIcon("run-build"));
  1177. projectBuildAction->setIcon(KIcon("view-refresh"));
  1178. helpContentsAction->setIcon(KIcon("help-contents"));
  1179. helpDocumentationAction->setIcon(KIcon("help-contents"));
  1180. helpSearchAction->setIcon(KIcon("system-search"));
  1181. findFindAction->setIcon(KIcon("edit-find"));
  1182. findReplaceAction->setIcon(KIcon("edit-find-replace"));
  1183. helpIndexAction->setIcon(KIcon("view-list-text"));
  1184. editUndoAction->setIcon(KIcon("edit-undo"));
  1185. editRedoAction->setIcon(KIcon("edit-redo"));
  1186. findFunctionsAction->setIcon(KIcon("view-list-tree"));
  1187. editIncreaseIndentAction->setIcon(KIcon("format-indent-more"));
  1188. editDecreaseIndentAction->setIcon(KIcon("format-indent-less"));
  1189. projectStopCompilationAction->setIcon(KIcon("process-stop"));
  1190. projectForceQuitAction->setIcon(KIcon("dialog-cancel"));
  1191. helpNewsAction->setIcon(KIcon("view-pim-news"));
  1192. debugRunAction->setIcon(KIcon("media-playback-start"));
  1193. debugPauseAction->setIcon(KIcon("media-playback-pause"));
  1194. toolsConfigureAction->setIcon(KIcon("configure"));
  1195. debugResetAction->setIcon(KIcon("media-playback-stop"));
  1196. } else fileNewMenu->menuAction()->setIcon(QIcon(QPixmap(":/images/00.png")));
  1197. QToolButton *fileNewButton=static_cast<QToolButton *>(toolBar
  1198. ->widgetForAction(fileNewAction));
  1199. fileNewButton->setPopupMode(QToolButton::MenuButtonPopup);
  1200. fileNewButton->setMenu(fileNewMenu);
  1201. QToolButton *fileOpenButton=static_cast<QToolButton *>(toolBar
  1202. ->widgetForAction(fileOpenAction));
  1203. QMenu *fileOpenMenu=new QMenu(this);
  1204. fileOpenMenu->setObjectName(QString::fromUtf8("fileOpenMenu"));
  1205. fileOpenMenu->addAction(fileRecent1Action);
  1206. fileOpenMenu->addAction(fileRecent2Action);
  1207. fileOpenMenu->addAction(fileRecent3Action);
  1208. fileOpenMenu->addAction(fileRecent4Action);
  1209. fileOpenButton->setPopupMode(QToolButton::MenuButtonPopup);
  1210. fileOpenButton->setMenu(fileOpenMenu);
  1211. QToolButton *findFunctionsButton=static_cast<QToolButton *>(toolBar
  1212. ->widgetForAction(findFunctionsAction));
  1213. findFunctionsPopup=new Q3PopupMenu(findFunctionsButton);
  1214. connect(findFunctionsPopup,SIGNAL(aboutToShow()),
  1215. this,SLOT(findFunctionsPopup_aboutToShow()));
  1216. connect(findFunctionsPopup,SIGNAL(aboutToHide()),
  1217. this,SLOT(findFunctionsPopup_aboutToHide()));
  1218. connect(findFunctionsPopup,SIGNAL(activated(int)),
  1219. this,SLOT(findFunctionsPopup_activated(int)));
  1220. findFunctionsButton->setPopupMode(QToolButton::MenuButtonPopup);
  1221. findFunctionsButton->setMenu(findFunctionsPopup);
  1222. errorListDock=new QDockWidget("Errors and Warnings",this);
  1223. errorListDock->setFloating(false);
  1224. errorListDock->setFeatures(QDockWidget::DockWidgetClosable);
  1225. errorListDock->setAllowedAreas(Qt::BottomDockWidgetArea);
  1226. errorList=new ErrorList(errorListDock);
  1227. errorListDock->setWidget(errorList);
  1228. addDockWidget(Qt::BottomDockWidgetArea,errorListDock);
  1229. errorList->show();
  1230. errorListDock->hide();
  1231. connect(errorListDock,SIGNAL(visibilityChanged(bool)),
  1232. this,SLOT(projectErrorsAndWarnings(bool)));
  1233. errorList->errorListView->setSorting(-1);
  1234. errorList->errorListView->setAlternateBackground(QColor());
  1235. connect(errorList->errorListView,SIGNAL(clicked(Q3ListViewItem *)),
  1236. this,SLOT(errorListView_clicked(Q3ListViewItem *)));
  1237. if (preferences.linkTarget!=LT_TIEMU) {
  1238. debugPauseAction->setEnabled(FALSE);
  1239. debugResetAction->setEnabled(FALSE);
  1240. }
  1241. if (preferences.linkTarget==LT_NONE) {
  1242. menuBar()->setItemVisible(5,FALSE); //debugMenu
  1243. debugRunAction->setVisible(FALSE);
  1244. debugPauseAction->setVisible(FALSE);
  1245. }
  1246. KConfigGroup recentFiles=pconfig->group("Recent files");
  1247. if (parg) {
  1248. QString fileName=QDir().absoluteFilePath(parg);
  1249. if (!openProject(fileName)) goto openRecent;
  1250. } else {
  1251. openRecent:;
  1252. QString mostrecent=recentFiles.readEntry("Current project");
  1253. if (!mostrecent.isNull() && !mostrecent.isEmpty())
  1254. openProject(mostrecent);
  1255. }
  1256. updateRecent();
  1257. KConfigGroup toolsConfig=pconfig->group("Tools");
  1258. unsigned toolCount=toolsConfig.readEntry("Count",0u);
  1259. tools.resize(toolCount);
  1260. for (unsigned idx=0; idx<toolCount; idx++) {
  1261. KConfigGroup toolConfig=pconfig->group(QString("Tool %1").arg(idx));
  1262. Tool &tool=tools[idx];
  1263. tool.title=toolConfig.readEntry("Title");
  1264. tool.commandLine=toolConfig.readEntry("Command Line");
  1265. tool.workingDirectory=toolConfig.readEntry("Working Directory");
  1266. tool.runInTerminal=toolConfig.readEntry("Terminal",false);
  1267. }
  1268. updateToolsMenu();
  1269. connect(toolsMenu,SIGNAL(activated(int)),this,SLOT(toolsMenu_activated(int)));
  1270. startTimer(100);
  1271. if (preferences.downloadHeadlines) {
  1272. NewsDialog newsDialog(this);
  1273. if (newsDialog.loadNews())
  1274. newsDialog.exec();
  1275. }
  1276. }
  1277. MainForm::~MainForm()
  1278. {
  1279. while (!sourceFiles.isEmpty()) {
  1280. delete sourceFiles.first();
  1281. }
  1282. if (kreplace) delete kreplace;
  1283. if (kfinddialog) delete kfinddialog;
  1284. for (int i=0; i<18; i++) delete shortcuts[i];
  1285. delete te_popup;
  1286. delete leftStatusLabel;
  1287. delete rowStatusLabel;
  1288. delete colStatusLabel;
  1289. delete charsStatusLabel;
  1290. delete rightStatusLabel;
  1291. delete rootListItem;
  1292. delete khelpmenu;
  1293. delete assistant;
  1294. delete errorList;
  1295. delete errorListDock;
  1296. ticalcs_library_exit();
  1297. tifiles_library_exit();
  1298. ticables_library_exit();
  1299. }
  1300. void MainForm::te_popup_aboutToShow()
  1301. {
  1302. te_popup->setItemEnabled(0,findOpenFileAtCursorAction->isEnabled());
  1303. te_popup->setItemEnabled(1,findFindSymbolDeclarationAction->isEnabled());
  1304. te_popup->setItemEnabled(2,editUndoAction->isEnabled());
  1305. te_popup->setItemEnabled(3,editRedoAction->isEnabled());
  1306. te_popup->setItemEnabled(4,editClearAction->isEnabled());
  1307. te_popup->setItemEnabled(5,editCutAction->isEnabled());
  1308. te_popup->setItemEnabled(6,editCopyAction->isEnabled());
  1309. te_popup->setItemEnabled(7,editPasteAction->isEnabled());
  1310. te_popup->setItemEnabled(8,editSelectAllAction->isEnabled());
  1311. te_popup->setItemEnabled(9,editIncreaseIndentAction->isEnabled());
  1312. te_popup->setItemEnabled(10,editDecreaseIndentAction->isEnabled());
  1313. }
  1314. void MainForm::te_popup_activated(int index)
  1315. {
  1316. switch (index) {
  1317. case 0: findOpenFileAtCursor(); break;
  1318. case 1: findFindSymbolDeclaration(); break;
  1319. case 2: editUndo(); break;
  1320. case 3: editRedo(); break;
  1321. case 4: editClear(); break;
  1322. case 5: editCut(); break;
  1323. case 6: editCopy(); break;
  1324. case 7: editPaste(); break;
  1325. case 8: editSelectAll(); break;
  1326. case 9: editIncreaseIndent(); break;
  1327. case 10: editDecreaseIndent(); break;
  1328. default: break;
  1329. }
  1330. }
  1331. void MainForm::shortcutActivated(int index)
  1332. {
  1333. if (CURRENT_VIEW && CURRENT_VIEW->hasFocus()) {
  1334. switch (index) {
  1335. case 0: editUndo(); break;
  1336. case 1: editRedo(); break;
  1337. case 2: editCut(); break;
  1338. case 3: editCopy(); break;
  1339. case 4: editPaste(); break;
  1340. case 5: // F1 context help
  1341. {
  1342. int line,col,i;
  1343. CURRENT_VIEW->cursorPosition().position(line,col);
  1344. QString textLine=CURRENT_VIEW->document()->line(line);
  1345. QString wordUnderCursor;
  1346. for (i=col-1;i>=0;i--) {
  1347. QChar c=textLine[i];
  1348. if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')
  1349. || c=='_' || c=='$' || c=='#')
  1350. wordUnderCursor.prepend(c);
  1351. }
  1352. int len=textLine.length();
  1353. for (i=col;i<len;i++) {
  1354. QChar c=textLine[i];
  1355. if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')
  1356. || c=='_' || c=='$' || c=='#')
  1357. wordUnderCursor.append(c);
  1358. }
  1359. // always open at least the index
  1360. force_qt_assistant_page(1);
  1361. assistant->openAssistant();
  1362. if (wordUnderCursor.isEmpty()) return;
  1363. QString docFile=lookup_doc_keyword(wordUnderCursor);
  1364. if (docFile.isEmpty()) return;
  1365. // wait for Qt Assistant to actually open
  1366. while (!assistant->isOpen())
  1367. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,1000);
  1368. assistant->showPage(QString(tigcc_base)+QString("/doc/html/")+docFile);
  1369. break;
  1370. }
  1371. case 6:
  1372. case 7:
  1373. // keyReturn is not in any interface, but it's a public slot...
  1374. CURRENT_VIEW->qt_metacall(QMetaObject::InvokeMetaMethod,
  1375. CURRENT_VIEW->metaObject()->indexOfMethod("keyReturn()"),NULL);
  1376. current_view_newLineHook();
  1377. break;
  1378. case 8:
  1379. new TemplatePopup(CURRENT_VIEW);
  1380. break;
  1381. case 9:
  1382. case 10:
  1383. if (IS_FILE(currentListItem)
  1384. && CURRENT_VIEW==static_cast<ListViewFile *>(currentListItem)->kateView) {
  1385. QString fileText=CURRENT_VIEW->document()->text();
  1386. CATEGORY_OF(category,currentListItem);
  1387. // Completion only operates on C files.
  1388. if (category==cFilesListItem || category==qllFilesListItem
  1389. || (category==hFilesListItem && !fileText.isEmpty()
  1390. && fileText[0]!='|' && fileText[0]!=';')) {
  1391. // Disable newLineHook.
  1392. shortcuts[6]->setEnabled(FALSE);
  1393. shortcuts[7]->setEnabled(FALSE);
  1394. new CompletionPopup(CURRENT_VIEW,pathInProject(currentListItem),this,this);
  1395. }
  1396. }
  1397. break;
  1398. case 11: // next file
  1399. case 12:
  1400. case_11:
  1401. {
  1402. Q3ListViewItem *item=currentListItem;
  1403. if (!item) item=rootListItem;
  1404. Q3ListViewItem *origItem=item;
  1405. do {
  1406. item=item->itemBelow();
  1407. if (!item) item=rootListItem;
  1408. if (item==origItem) return; // no suitable items to select
  1409. } while (item==rootListItem || IS_CATEGORY(item));
  1410. fileTreeClicked(item);
  1411. if (CURRENT_VIEW) CURRENT_VIEW->setFocus();
  1412. break;
  1413. }
  1414. case 13: // switch transfer target
  1415. case 14:
  1416. case_13:
  1417. {
  1418. preferences.linkTarget=(preferences.linkTarget==LT_TIEMU)?LT_REALCALC:LT_TIEMU;
  1419. savePreferences();
  1420. // Apply the preferences to the debug menu.
  1421. debugPauseAction->setEnabled(!compiling&&preferences.linkTarget==LT_TIEMU);
  1422. debugResetAction->setEnabled(!compiling&&preferences.linkTarget==LT_TIEMU);
  1423. bool runnable=!settings.archive&&!settings.flash_os&&preferences.linkTarget!=LT_NONE;
  1424. menuBar()->setItemVisible(5,runnable); //debugMenu
  1425. debugRunAction->setVisible(runnable);
  1426. debugPauseAction->setVisible(runnable);
  1427. break;
  1428. }
  1429. case 15: projectCompile(); break;
  1430. case 16: projectMake(); break;
  1431. default: break;
  1432. }
  1433. } else {
  1434. switch (index) {
  1435. case 6:
  1436. case 7:
  1437. {
  1438. QKeyEvent *keyEvent=new QKeyEvent(QEvent::KeyPress,Qt::Key_Return,'\n',0,"\n");
  1439. QApplication::postEvent(focusWidget(),keyEvent);
  1440. break;
  1441. }
  1442. case 11: goto case_11;
  1443. case 12: goto case_11;
  1444. case 13: goto case_13;
  1445. case 14: goto case_13;
  1446. case 15: projectCompile(); break;
  1447. case 16: projectMake(); break;
  1448. default: break;
  1449. }
  1450. }
  1451. }
  1452. void MainForm::completionPopup_closed()
  1453. {
  1454. if (IS_FILE(currentListItem)) {
  1455. CATEGORY_OF(category,currentListItem->parent());
  1456. if (IS_EDITABLE_CATEGORY(category)) {
  1457. // Restore newLineHook.
  1458. shortcuts[6]->setEnabled(TRUE);
  1459. shortcuts[7]->setEnabled(TRUE);
  1460. }
  1461. }
  1462. }
  1463. void MainForm::shortcut_0_activated()
  1464. {
  1465. shortcutActivated(0);
  1466. }
  1467. void MainForm::shortcut_1_activated()
  1468. {
  1469. shortcutActivated(1);
  1470. }
  1471. void MainForm::shortcut_2_activated()
  1472. {
  1473. shortcutActivated(2);
  1474. }
  1475. void MainForm::shortcut_3_activated()
  1476. {
  1477. shortcutActivated(3);
  1478. }
  1479. void MainForm::shortcut_4_activated()
  1480. {
  1481. shortcutActivated(4);
  1482. }
  1483. void MainForm::shortcut_5_activated()
  1484. {
  1485. shortcutActivated(5);
  1486. }
  1487. void MainForm::shortcut_6_activated()
  1488. {
  1489. shortcutActivated(6);
  1490. }
  1491. void MainForm::shortcut_7_activated()
  1492. {
  1493. shortcutActivated(7);
  1494. }
  1495. void MainForm::shortcut_8_activated()
  1496. {
  1497. shortcutActivated(8);
  1498. }
  1499. void MainForm::shortcut_9_activated()
  1500. {
  1501. shortcutActivated(9);
  1502. }
  1503. void MainForm::shortcut_10_activated()
  1504. {
  1505. shortcutActivated(10);
  1506. }
  1507. void MainForm::shortcut_11_activated()
  1508. {
  1509. shortcutActivated(11);
  1510. }
  1511. void MainForm::shortcut_12_activated()
  1512. {
  1513. shortcutActivated(12);
  1514. }
  1515. void MainForm::shortcut_13_activated()
  1516. {
  1517. shortcutActivated(13);
  1518. }
  1519. void MainForm::shortcut_14_activated()
  1520. {
  1521. shortcutActivated(14);
  1522. }
  1523. void MainForm::shortcut_15_activated()
  1524. {
  1525. shortcutActivated(15);
  1526. }
  1527. void MainForm::shortcut_16_activated()
  1528. {
  1529. shortcutActivated(16);
  1530. }
  1531. void MainForm::clearProject()
  1532. {
  1533. headersModified=FALSE;
  1534. newSettings(&settings,&libopts);
  1535. rootListItem->setText(0,"Project1");
  1536. projectFileName="";
  1537. fileTreeClicked(rootListItem);
  1538. // Better do this now or the file destructors will have to iterate over the
  1539. // error list each time, and I'd have to clear the list at the end anyway
  1540. // because an error might not have a source file assigned.
  1541. errorList->errorListView->clear();
  1542. programOutput=QString::null;
  1543. projectProgramOutputAction->setEnabled(FALSE);
  1544. Q3ListViewItem *f, *next;
  1545. for (f=hFilesListItem->firstChild();f;f=next) {
  1546. next=f->nextSibling();
  1547. delete f;
  1548. }
  1549. for (f=cFilesListItem->firstChild();f;f=next) {
  1550. next=f->nextSibling();
  1551. delete f;
  1552. }
  1553. for (f=sFilesListItem->firstChild();f;f=next) {
  1554. next=f->nextSibling();
  1555. delete f;
  1556. }
  1557. if (asmFilesListItem) {
  1558. for (f=asmFilesListItem->firstChild();f;f=next) {
  1559. next=f->nextSibling();
  1560. delete f;
  1561. }
  1562. }
  1563. if (qllFilesListItem) {
  1564. for (f=qllFilesListItem->firstChild();f;f=next) {
  1565. next=f->nextSibling();
  1566. delete f;
  1567. }
  1568. }
  1569. for (f=oFilesListItem->firstChild();f;f=next) {
  1570. next=f->nextSibling();
  1571. delete f;
  1572. }
  1573. for (f=aFilesListItem->firstChild();f;f=next) {
  1574. next=f->nextSibling();
  1575. delete f;
  1576. }
  1577. for (f=txtFilesListItem->firstChild();f;f=next) {
  1578. next=f->nextSibling();
  1579. delete f;
  1580. }
  1581. for (f=othFilesListItem->firstChild();f;f=next) {
  1582. next=f->nextSibling();
  1583. delete f;
  1584. }
  1585. fileCount=cFileCount=hFileCount=sFileCount=asmFileCount=qllFileCount=oFileCount=aFileCount=txtFileCount=othFileCount=0;
  1586. projectCompletion.clear();
  1587. projectIsDirty=FALSE;
  1588. projectNeedsRelink=FALSE;
  1589. menuBar()->setItemVisible(5,preferences.linkTarget!=LT_NONE); //debugMenu
  1590. debugRunAction->setVisible(preferences.linkTarget!=LT_NONE);
  1591. debugPauseAction->setVisible(preferences.linkTarget!=LT_NONE);
  1592. updateLeftStatusLabel();
  1593. }
  1594. void MainForm::fileNewProject()
  1595. {
  1596. if (compiling || savePrompt())
  1597. return;
  1598. clearProject();
  1599. KConfigGroup recentFiles=pconfig->group("Recent files");
  1600. recentFiles.writeEntry("Current project","");
  1601. pconfig->sync();
  1602. }
  1603. QString MainForm::findFilter(unsigned short job)
  1604. {
  1605. QString ret;
  1606. if (job==TIGCCOpenProjectFileFilter)
  1607. {
  1608. ret="*.tpr *.h *.c *.s ";
  1609. if (asmFilesListItem)
  1610. ret+="*.asm ";
  1611. if (qllFilesListItem)
  1612. ret+="*.qll ";
  1613. ret+="*.txt";
  1614. ret+="|All TIGCC Files ("+ret+")\n"
  1615. TIGCC_TPR_Filter TIGCC_H_Filter TIGCC_C_Filter TIGCC_S_Filter;
  1616. if (asmFilesListItem)
  1617. ret+=TIGCC_ASM_Filter;
  1618. if (qllFilesListItem)
  1619. ret+=TIGCC_QLL_Filter;
  1620. ret+=TIGCC_TXT_Filter TIGCCAllFilter;
  1621. }
  1622. else if (job==TIGCCAddFilesFilter)
  1623. {
  1624. ret="*.h *.c *.s ";
  1625. if (asmFilesListItem)
  1626. ret+="*.asm ";
  1627. if (qllFilesListItem)
  1628. ret+="*.qll ";
  1629. ret+="*.o *.a *.txt";
  1630. ret+="|All TIGCC Files ("+ret+")\n"
  1631. TIGCC_H_Filter TIGCC_C_Filter TIGCC_S_Filter;
  1632. if (asmFilesListItem)
  1633. ret+=TIGCC_ASM_Filter;
  1634. if (qllFilesListItem)
  1635. ret+=TIGCC_QLL_Filter;
  1636. ret+=TIGCC_O_Filter TIGCC_A_Filter TIGCC_TXT_Filter TIGCCAllFilter;
  1637. }
  1638. return ret;
  1639. }
  1640. QString MainForm::SGetFileName(int mode,const QString &fileFilter,const QString &caption,QWidget *parent)
  1641. {
  1642. QString ret;
  1643. if (static_cast<KFileDialog::OperationMode>(mode)==KFileDialog::Opening)
  1644. ret=KFileDialog::getOpenFileName(lastDirectory,fileFilter,parent,caption);
  1645. else
  1646. ret=KFileDialog::getSaveFileName(lastDirectory,fileFilter,parent,caption);
  1647. if (!ret.isNull())
  1648. {
  1649. KUrl dir;
  1650. dir.setPath(ret);
  1651. dir.setFileName("");
  1652. lastDirectory=dir.path();
  1653. }
  1654. return ret;
  1655. }
  1656. //no mode, since it you can't save multiple.
  1657. QStringList MainForm::SGetFileName_Multiple(const QString &fileFilter,const QString &caption,QWidget *parent)
  1658. {
  1659. QStringList ret;
  1660. ret=KFileDialog::getOpenFileNames(lastDirectory,fileFilter,parent,caption);
  1661. if (!ret.empty())
  1662. {
  1663. KUrl dir;
  1664. dir.setPath(ret[0]);
  1665. dir.setFileName("");
  1666. lastDirectory=dir.path();
  1667. }
  1668. return ret;
  1669. }
  1670. void MainForm::updateRecent()
  1671. {
  1672. KConfigGroup recentFiles=pconfig->group("Recent files");
  1673. QString recent=recentFiles.readEntry("Recent file 1");
  1674. if (recent.isNull())
  1675. fileRecent1Action->setVisible(FALSE);
  1676. else {
  1677. QString recentcut=recent.mid(recent.findRev('/')+1);
  1678. recentcut.truncate(recentcut.findRev('.'));
  1679. fileRecent1Action->setVisible(TRUE);
  1680. fileRecent1Action->setText(recentcut);
  1681. fileRecent1Action->setStatusTip(recent);
  1682. }
  1683. recent=recentFiles.readEntry("Recent file 2");
  1684. if (recent.isNull())
  1685. fileRecent2Action->setVisible(FALSE);
  1686. else {
  1687. QString recentcut=recent.mid(recent.findRev('/')+1);
  1688. recentcut.truncate(recentcut.findRev('.'));
  1689. fileRecent2Action->setVisible(TRUE);
  1690. fileRecent2Action->setText(recentcut);
  1691. fileRecent2Action->setStatusTip(recent);
  1692. }
  1693. recent=recentFiles.readEntry("Recent file 3");
  1694. if (recent.isNull())
  1695. fileRecent3Action->setVisible(FALSE);
  1696. else {
  1697. QString recentcut=recent.mid(recent.findRev('/')+1);
  1698. recentcut.truncate(recentcut.findRev('.'));
  1699. fileRecent3Action->setVisible(TRUE);
  1700. fileRecent3Action->setText(recentcut);
  1701. fileRecent3Action->setStatusTip(recent);
  1702. }
  1703. recent=recentFiles.readEntry("Recent file 4");
  1704. if (recent.isNull())
  1705. fileRecent4Action->setVisible(FALSE);
  1706. else {
  1707. QString recentcut=recent.mid(recent.findRev('/')+1);
  1708. recentcut.truncate(recentcut.findRev('.'));
  1709. fileRecent4Action->setVisible(TRUE);
  1710. fileRecent4Action->setText(recentcut);
  1711. fileRecent4Action->setStatusTip(recent);
  1712. }
  1713. }
  1714. void MainForm::addRecent(const QString &fileName)
  1715. {
  1716. unsigned i,j;
  1717. // Pick up any changes to the list of recent files from other instances
  1718. pconfig->sync();
  1719. pconfig->reparseConfiguration();
  1720. KConfigGroup recentFiles=pconfig->group("Recent files");
  1721. // Find recent file to overwrite. If it isn't one of the first 3, by
  1722. // elimination, it is the last, thus the test only goes up to <4, not <=4.
  1723. for (i=1;i<4;i++) {
  1724. QString recenti=recentFiles.readEntry(QString("Recent file %1").arg(i));
  1725. if (recenti.isNull() || !recenti.compare(fileName))
  1726. break;
  1727. }
  1728. // Move entries up
  1729. for (j=i;j>1;j--) {
  1730. recentFiles.writeEntry(QString("Recent file %1").arg(j),recentFiles.readEntry(QString("Recent file %1").arg(j-1)));
  1731. }
  1732. // The first recent file is the current project.
  1733. recentFiles.writeEntry("Recent file 1",fileName);
  1734. recentFiles.writeEntry("Current project",fileName);
  1735. pconfig->sync();
  1736. updateRecent();
  1737. }
  1738. Q3ListViewItem * MainForm::openFile(Q3ListViewItem * category, Q3ListViewItem * parent, const QString &fileCaption, const QString &fileName)
  1739. {
  1740. switch (getPathType(fileName)) {
  1741. case PATH_FILE: // OK
  1742. break;
  1743. case PATH_NOTFOUND:
  1744. KMessageBox::error(this,QString("File \'%1\' not found").arg(fileName));
  1745. return NULL;
  1746. default:
  1747. KMessageBox::error(this,QString("\'%1\' is not a regular file").arg(fileName));
  1748. return NULL;
  1749. }
  1750. Q3ListViewItem *item=NULL, *next=parent->firstChild();
  1751. for (; IS_FILE(next); next=item->nextSibling())
  1752. item=next;
  1753. ListViewFile *newFile=item?new ListViewFile(parent,item)
  1754. :new ListViewFile(parent);
  1755. newFile->isNew=FALSE;
  1756. newFile->modifiedSinceLastCompile=FALSE;
  1757. newFile->setText(0,fileCaption);
  1758. newFile->setPixmap(0,
  1759. category==cFilesListItem||category==qllFilesListItem?SYSICON("text-x-csrc","filec.png"):
  1760. category==hFilesListItem?SYSICON("text-x-chdr","fileh.png"):
  1761. category==sFilesListItem||category==asmFilesListItem?SYSICON("text-x-hex","files.png"):
  1762. category==txtFilesListItem?SYSICON("text-plain","filet.png"):
  1763. category==oFilesListItem||category==aFilesListItem?SYSICON("application-x-object","fileo.png"):
  1764. SYSICON("unknown","filex.png"));
  1765. newFile->fileName=fileName;
  1766. if (IS_EDITABLE_CATEGORY(category)) {
  1767. newFile->kateView=reinterpret_cast<KTextEditor::View *>(createView(fileName,QString::null,category));
  1768. KDirWatch::self()->addFile(fileName);
  1769. }
  1770. fileCount++;
  1771. COUNTER_FOR_CATEGORY(category)++;
  1772. return newFile;
  1773. }
  1774. Q3ListViewItem *MainForm::createFolder(Q3ListViewItem *parent,const QString &name)
  1775. {
  1776. Q3ListViewItem *item=parent->firstChild();
  1777. Q3ListViewItem *startItem=item;
  1778. Q3ListViewItem *newItem;
  1779. for (; item; item=item->nextSibling())
  1780. {
  1781. if (IS_FOLDER(item) && !item->text(0).compare(name))
  1782. return item;
  1783. }
  1784. item=NULL;
  1785. for (;startItem;startItem=item->nextSibling())
  1786. item=startItem;
  1787. newItem=item?new ListViewFolder(parent,item)
  1788. :new ListViewFolder(parent);
  1789. newItem->setText(0,name);
  1790. newItem->setOpen(TRUE);
  1791. return newItem;
  1792. }
  1793. void *MainForm::createView(const QString &fileName, const QString &fileText, Q3ListViewItem *category)
  1794. {
  1795. // Create Document object.
  1796. KParts::Factory *factory = (KParts::Factory *)
  1797. KLibLoader::self()->factory ("katepart");
  1798. if (!factory) qFatal("Failed to load KatePart");
  1799. KTextEditor::Document *doc = (KTextEditor::Document *)
  1800. factory->createPart(0,this,"KTextEditor::Document");
  1801. // Open the file.
  1802. doc->setEncoding(preferences.useCalcCharset?"TI-89":QTextCodec::codecForLocale()->name());
  1803. if (!fileName.isNull()) doc->openUrl(KUrl(fileName));
  1804. // Set text.
  1805. if (!fileText.isNull()) {
  1806. SET_TEXT_SAFE(doc,fileText);
  1807. doc->setModified(FALSE);
  1808. // clearUndo and clearRedo are not in any interface, but they are public slots...
  1809. doc->qt_metacall(QMetaObject::InvokeMetaMethod,
  1810. doc->metaObject()->indexOfMethod("clearUndo()"),NULL);
  1811. doc->qt_metacall(QMetaObject::InvokeMetaMethod,
  1812. doc->metaObject()->indexOfMethod("clearRedo()"),NULL);
  1813. }
  1814. // Create View object.
  1815. KTextEditor::View *newView = (KTextEditor::View *) doc->createView(widgetStack);
  1816. newView->hide();
  1817. newView->setSizePolicy(QSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored,0,0));
  1818. // Set highlighting mode.
  1819. QString firstLine;
  1820. if (doc->lines()) firstLine=doc->line(0);
  1821. newView->document()->setHighlightingMode(
  1822. (category==qllFilesListItem?
  1823. QLL_HL_MODE:
  1824. (category==sFilesListItem||(category==hFilesListItem&&!firstLine.isEmpty()&&firstLine[0]=='|'))?
  1825. S_HL_MODE:
  1826. (category==asmFilesListItem||(category==hFilesListItem&&!firstLine.isEmpty()&&firstLine[0]==';'))?
  1827. ASM_HL_MODE:
  1828. (category==cFilesListItem||category==hFilesListItem)?
  1829. C_HL_MODE:
  1830. "None"));
  1831. // Set options.
  1832. KTextEditor::ConfigInterface *configiface
  1833. =qobject_cast<KTextEditor::ConfigInterface*>(newView);
  1834. configiface->setConfigValue("dynamic-word-wrap",false);
  1835. if (preferences.removeTrailingSpaces) {
  1836. sendCommand(newView,"set-remove-trailing-space 1");
  1837. sendCommand(newView,"set-remove-trailing-space-save 1");
  1838. } else {
  1839. sendCommand(newView,"set-remove-trailing-space 0");
  1840. sendCommand(newView,"set-remove-trailing-space-save 0");
  1841. }
  1842. setTabWidth(newView,
  1843. (category==sFilesListItem||category==asmFilesListItem||((category==hFilesListItem&&!firstLine.isEmpty()&&(firstLine[0]=='|'||firstLine[0]==';'))))?preferences.tabWidthAsm:
  1844. (category==cFilesListItem||category==qllFilesListItem||category==hFilesListItem)?preferences.tabWidthC:
  1845. 8
  1846. );
  1847. connect(newView,SIGNAL(cursorPositionChanged(KTextEditor::View*,const KTextEditor::Cursor&)),this,SLOT(current_view_cursorPositionChanged(KTextEditor::View*,const KTextEditor::Cursor&)));
  1848. connect(newView,SIGNAL(textInserted(KTextEditor::View*,const KTextEditor::Cursor&,const QString&)),
  1849. this,SLOT(current_view_textInserted(KTextEditor::View*,const KTextEditor::Cursor&,const QString&)));
  1850. connect(newView,SIGNAL(selectionChanged(KTextEditor::View*)),this,SLOT(current_view_selectionChanged(KTextEditor::View*)));
  1851. connect(newView->document(),SIGNAL(textChanged(KTextEditor::Document*)),this,SLOT(current_view_textChanged(KTextEditor::Document*)));
  1852. connect(newView->document(),SIGNAL(undoChanged()),this,SLOT(current_view_undoChanged()));
  1853. newView->setContextMenu(te_popup);
  1854. newView->setCursorPosition(KTextEditor::Cursor(0,0));
  1855. // Clear unwanted KatePart shortcuts causing conflicts
  1856. QList<QAction *>actions=newView->actionCollection()->actions();
  1857. foreach(QAction *action, actions) action->setShortcuts(QKeySequence::UnknownKey);
  1858. return newView;
  1859. }
  1860. void MainForm::adoptSourceFile(void *srcFile)
  1861. {
  1862. if (compiling) return;
  1863. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  1864. QString fileName=sourceFile->fileName;
  1865. KTextEditor::View *newView=sourceFile->kateView;
  1866. // Determine category and caption.
  1867. Q3ListViewItem *category=othFilesListItem;
  1868. QString suffix,caption;
  1869. int p;
  1870. p=fileName.findRev('/');
  1871. if (p<0) p=-1;
  1872. caption=fileName.mid(p+1);
  1873. p=caption.findRev('.');
  1874. if (p>=0) {
  1875. suffix=caption.mid(p+1);
  1876. caption.truncate(p);
  1877. }
  1878. if (!checkFileName(fileName,extractAllFileNames())) {
  1879. KMessageBox::error(this,QString("The file \'%1\' is already included in the project.").arg(caption));
  1880. return;
  1881. }
  1882. if (!suffix.compare("h"))
  1883. category=hFilesListItem;
  1884. else if (!suffix.compare("c"))
  1885. category=cFilesListItem;
  1886. else if (!suffix.compare("s"))
  1887. category=sFilesListItem;
  1888. else if (!suffix.compare("asm"))
  1889. category=asmFilesListItem;
  1890. else if (!suffix.compare("qll"))
  1891. category=qllFilesListItem;
  1892. else
  1893. category=txtFilesListItem;
  1894. if (category && category==qllFilesListItem && qllFileCount) {
  1895. KMessageBox::error(this,"There may be only one Quill source file in each project.","Quill Error");
  1896. return;
  1897. }
  1898. if (!category)
  1899. category=txtFilesListItem;
  1900. // Create file tree entry.
  1901. Q3ListViewItem *item=NULL, *next=category->firstChild();
  1902. for (; IS_FILE(next); next=item->nextSibling())
  1903. item=next;
  1904. ListViewFile *newFile=item?new ListViewFile(category,item)
  1905. :new ListViewFile(category);
  1906. newFile->isNew=FALSE;
  1907. newFile->setText(0,caption);
  1908. newFile->setPixmap(0,
  1909. category==cFilesListItem||category==qllFilesListItem?SYSICON("text-x-csrc","filec.png"):
  1910. category==hFilesListItem?SYSICON("text-x-chdr","fileh.png"):
  1911. category==sFilesListItem||category==asmFilesListItem?SYSICON("text-x-hex","files.png"):
  1912. SYSICON("text-plain","filet.png"));
  1913. newFile->fileName=fileName;
  1914. newFile->modifiedSinceLastCompile=newView->document()->isModified();
  1915. // Adopt View object.
  1916. newFile->kateView=newView;
  1917. newView->hide();
  1918. newView->reparent(widgetStack,QPoint());
  1919. newView->setSizePolicy(QSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored,0,0));
  1920. KDirWatch::self()->addFile(fileName);
  1921. fileCount++;
  1922. COUNTER_FOR_CATEGORY(category)++;
  1923. // Set highlighting mode.
  1924. QString fileText=newView->document()->text();
  1925. newView->document()->setHighlightingMode(
  1926. (category==qllFilesListItem?
  1927. QLL_HL_MODE:
  1928. (category==sFilesListItem||(category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]=='|'))?
  1929. S_HL_MODE:
  1930. (category==asmFilesListItem||(category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]==';'))?
  1931. ASM_HL_MODE:
  1932. (category==cFilesListItem||category==hFilesListItem)?
  1933. C_HL_MODE:
  1934. "None"));
  1935. // Set options.
  1936. setTabWidth(newView,
  1937. (category==sFilesListItem||category==asmFilesListItem||((category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&(fileText[0]=='|'||fileText[0]==';'))))?preferences.tabWidthAsm:
  1938. (category==cFilesListItem||category==qllFilesListItem||category==hFilesListItem)?preferences.tabWidthC:
  1939. 8
  1940. );
  1941. connect(newView,SIGNAL(cursorPositionChanged(KTextEditor::View*,const KTextEditor::Cursor&)),this,SLOT(current_view_cursorPositionChanged(KTextEditor::View*,const KTextEditor::Cursor&)));
  1942. connect(newView,SIGNAL(textInserted(KTextEditor::View*,const KTextEditor::Cursor&,const QString&)),
  1943. this,SLOT(current_view_textInserted(KTextEditor::View*,const KTextEditor::Cursor&,const QString&)));
  1944. connect(newView,SIGNAL(selectionChanged(KTextEditor::View*)),this,SLOT(current_view_selectionChanged(KTextEditor::View*)));
  1945. connect(newView->document(),SIGNAL(textChanged(KTextEditor::Document*)),this,SLOT(current_view_textChanged(KTextEditor::Document*)));
  1946. connect(newView->document(),SIGNAL(undoChanged()),this,SLOT(current_view_undoChanged()));
  1947. newView->setContextMenu(te_popup);
  1948. // Mark project dirty.
  1949. projectIsDirty=TRUE;
  1950. projectNeedsRelink=TRUE;
  1951. // Select file.
  1952. fileTreeClicked(newFile);
  1953. // Update errors to point to the in-project source file instead of the
  1954. // external one.
  1955. Q3ListViewItemIterator lvit(errorList->errorListView);
  1956. Q3ListViewItem *errorItem;
  1957. for (errorItem=lvit.current();errorItem;errorItem=(++lvit).current()) {
  1958. if (static_cast<ErrorListItem *>(errorItem)->srcFile==sourceFile) {
  1959. static_cast<ErrorListItem *>(errorItem)->srcFile=static_cast<SourceFileWindow *>(NULL);
  1960. static_cast<ErrorListItem *>(errorItem)->lvFile=newFile;
  1961. }
  1962. }
  1963. // Close separate source view.
  1964. sourceFile->kateView=static_cast<KTextEditor::View *>(NULL);
  1965. sourceFile->deleteLater();
  1966. }
  1967. void MainForm::fileOpen_addList(Q3ListViewItem *category,void *fileListV,void *dir, const QString &open_file)
  1968. {
  1969. int i,e;
  1970. int p,pslash;
  1971. KUrl tmp;
  1972. TPRFileList *fileList=(TPRFileList*)fileListV;
  1973. QString caption;
  1974. QString treePath;
  1975. Q3ListViewItem *parent;
  1976. e=fileList->path.count();
  1977. if (e) category->setOpen(TRUE);
  1978. for (i=0;i<e;i++)
  1979. {
  1980. tmp=*reinterpret_cast<const KUrl *>(dir);
  1981. kurlNewFileName(tmp,fileList->path[i]);
  1982. caption=fileList->path[i];
  1983. //fixed suffix truncation for file paths such as "/root/.dot/nodot" so it wouldn't truncate to "/root/"
  1984. p=caption.findRev('.');
  1985. pslash=caption.findRev('/');
  1986. if (p>=0&&p>pslash) caption.truncate(p);
  1987. if (pslash>=0) caption.remove(0,pslash+1);
  1988. treePath=fileList->folder[i].trimmed();
  1989. //check for a backslash at the end and remove it if it's there.
  1990. if (!treePath.isEmpty() && treePath[treePath.length()-1]=='\\')
  1991. treePath.truncate(treePath.length()-1);
  1992. parent=category;
  1993. if (!treePath.isEmpty())
  1994. {
  1995. while ((p=treePath.find('\\'))>=0)
  1996. {
  1997. parent=createFolder(parent,treePath.left(p));
  1998. treePath.remove(0,p+1);
  1999. }
  2000. parent=createFolder(parent,treePath);
  2001. }
  2002. ListViewFile *newFile=static_cast<ListViewFile *>(openFile(category,parent,caption,tmp.path()));
  2003. if (!newFile) continue;
  2004. if (!newFile->fileName.compare(open_file))
  2005. fileTreeClicked(newFile);
  2006. }
  2007. }
  2008. // Returns TRUE if the file is a project, FALSE if the file is a source file.
  2009. bool MainForm::openProject(const QString &fileName)
  2010. {
  2011. TPRDataStruct TPRData;
  2012. KUrl dir;
  2013. bool isProject=fileName.endsWith(".tpr",FALSE);
  2014. dir.setPath(fileName);
  2015. switch (getPathType(fileName)) {
  2016. case PATH_FILE: // OK
  2017. break;
  2018. case PATH_NOTFOUND:
  2019. KMessageBox::error(this,QString("File \'%1\' not found").arg(fileName));
  2020. return isProject;
  2021. default:
  2022. KMessageBox::error(this,QString("\'%1\' is not a regular file").arg(fileName));
  2023. return isProject;
  2024. }
  2025. if (isProject) {
  2026. int ret=loadTPR(fileName, &TPRData);
  2027. if (ret == -1) {
  2028. KMessageBox::error(this,QString("Can't open \'%1\'").arg(fileName));
  2029. return TRUE;
  2030. }
  2031. if (ret > 0) {
  2032. KMessageBox::error(this,QString("Error at line %2 of \'%1\'").arg(fileName).arg(ret));
  2033. return TRUE;
  2034. }
  2035. if (TPRData.asm_files.path.count() && !asmFilesListItem) {
  2036. KMessageBox::error(this,"This project needs A68k, which is not installed.");
  2037. return TRUE;
  2038. }
  2039. if (TPRData.quill_files.path.count() && !qllFilesListItem) {
  2040. KMessageBox::error(this,"This project needs quill.drv, which is not installed.");
  2041. return TRUE;
  2042. }
  2043. if (TPRData.settings.fargo && !have_fargo) {
  2044. KMessageBox::error(this,"This project needs fargo.a, which is not installed.");
  2045. return TRUE;
  2046. }
  2047. if (TPRData.settings.flash_os && !have_flashos) {
  2048. KMessageBox::error(this,"This project needs flashos.a, which is not installed.");
  2049. return TRUE;
  2050. }
  2051. clearProject();
  2052. fileOpen_addList(hFilesListItem,&TPRData.h_files,&dir,TPRData.open_file);
  2053. fileOpen_addList(cFilesListItem,&TPRData.c_files,&dir,TPRData.open_file);
  2054. fileOpen_addList(qllFilesListItem,&TPRData.quill_files,&dir,TPRData.open_file);
  2055. fileOpen_addList(sFilesListItem,&TPRData.s_files,&dir,TPRData.open_file);
  2056. fileOpen_addList(asmFilesListItem,&TPRData.asm_files,&dir,TPRData.open_file);
  2057. fileOpen_addList(oFilesListItem,&TPRData.o_files,&dir,TPRData.open_file);
  2058. fileOpen_addList(aFilesListItem,&TPRData.a_files,&dir,TPRData.open_file);
  2059. fileOpen_addList(txtFilesListItem,&TPRData.txt_files,&dir,TPRData.open_file);
  2060. fileOpen_addList(othFilesListItem,&TPRData.oth_files,&dir,TPRData.open_file);
  2061. rootListItem->setText(0,TPRData.prj_name);
  2062. projectFileName=fileName;
  2063. settings=TPRData.settings;
  2064. libopts=TPRData.libopts;
  2065. bool runnable=!settings.archive&&!settings.flash_os&&preferences.linkTarget!=LT_NONE;
  2066. menuBar()->setItemVisible(5,runnable); //debugMenu
  2067. debugRunAction->setVisible(runnable);
  2068. debugPauseAction->setVisible(runnable);
  2069. updateLeftStatusLabel();
  2070. updateRightStatusLabel();
  2071. addRecent(fileName);
  2072. return TRUE;
  2073. } else {
  2074. Q3ListViewItem *category=othFilesListItem;
  2075. QString suffix,caption;
  2076. int p;
  2077. p=fileName.findRev('/');
  2078. if (p<0) p=-1;
  2079. caption=fileName.mid(p+1);
  2080. p=caption.findRev('.');
  2081. if (p>=0) {
  2082. suffix=caption.mid(p+1);
  2083. caption.truncate(p);
  2084. }
  2085. if (extractAllFileNames().contains(fileName)) {
  2086. KMessageBox::error(this,QString("The file \'%1\' is already included in the project.").arg(caption));
  2087. return FALSE;
  2088. }
  2089. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  2090. if (!fileName.compare(sourceFile->fileName)) {
  2091. ACTIVATE_WINDOW(sourceFile->winId());
  2092. return FALSE;
  2093. }
  2094. }
  2095. if (!suffix.compare("h"))
  2096. category=hFilesListItem;
  2097. else if (!suffix.compare("c"))
  2098. category=cFilesListItem;
  2099. else if (!suffix.compare("s"))
  2100. category=sFilesListItem;
  2101. else if (!suffix.compare("asm") && asmFilesListItem)
  2102. category=asmFilesListItem;
  2103. else if (!suffix.compare("qll") && qllFilesListItem)
  2104. category=qllFilesListItem;
  2105. else if (!suffix.compare("txt"))
  2106. category=txtFilesListItem;
  2107. else {
  2108. KMessageBox::error(this,QString("\'%1\' is not a valid file for opening.").arg(fileName));
  2109. return FALSE;
  2110. }
  2111. int firstChar=peekFirstChar(fileName);
  2112. if (firstChar==-2) {
  2113. KMessageBox::error(this,QString("Can't open \'%1\'").arg(fileName));
  2114. return FALSE;
  2115. }
  2116. int type=((category==sFilesListItem||(category==hFilesListItem&&firstChar=='|'))?
  2117. 2:
  2118. (category==asmFilesListItem||(category==hFilesListItem&&firstChar==';'))?
  2119. 3:
  2120. (category==cFilesListItem||category==qllFilesListItem||category==hFilesListItem)?
  2121. 1:
  2122. 0);
  2123. new SourceFileWindow(this,fileName,
  2124. (category==qllFilesListItem)?QLL_ENABLED_HL_MODE:
  2125. (type==2)?S_ENABLED_HL_MODE:
  2126. (type==3)?ASM_ENABLED_HL_MODE:
  2127. (type==1)?C_ENABLED_HL_MODE:
  2128. "None",
  2129. (category==qllFilesListItem)?&(preferences.synQll.enabled):
  2130. (type==2)?&(preferences.synS.enabled):
  2131. (type==3)?&(preferences.synAsm.enabled):
  2132. (type==1)?&(preferences.synC.enabled):
  2133. NULL,category,(type==1),(type>1),category==txtFilesListItem);
  2134. return FALSE;
  2135. }
  2136. }
  2137. void MainForm::fileOpen()
  2138. {
  2139. if (compiling || savePrompt())
  2140. return;
  2141. QString fileName=SGetFileName(KFileDialog::Opening,findFilter(TIGCCOpenProjectFileFilter),"Open Project/File",this);
  2142. KUrl dir;
  2143. dir.setPath(fileName);
  2144. if (fileName.isEmpty())
  2145. return;
  2146. openProject(fileName);
  2147. }
  2148. void MainForm::fileRecent1()
  2149. {
  2150. QString recentFile=fileRecent1Action->statusTip();
  2151. if (compiling || savePrompt())
  2152. return;
  2153. openProject(recentFile);
  2154. }
  2155. void MainForm::fileRecent2()
  2156. {
  2157. QString recentFile=fileRecent2Action->statusTip();
  2158. if (compiling || savePrompt())
  2159. return;
  2160. openProject(recentFile);
  2161. }
  2162. void MainForm::fileRecent3()
  2163. {
  2164. QString recentFile=fileRecent3Action->statusTip();
  2165. if (compiling || savePrompt())
  2166. return;
  2167. openProject(recentFile);
  2168. }
  2169. void MainForm::fileRecent4()
  2170. {
  2171. QString recentFile=fileRecent4Action->statusTip();
  2172. if (compiling || savePrompt())
  2173. return;
  2174. openProject(recentFile);
  2175. }
  2176. int MainForm::fileSavePrompt(Q3ListViewItem *fileItem)
  2177. {
  2178. int result;
  2179. ListViewFile *theFile=static_cast<ListViewFile *>(fileItem);
  2180. if (!theFile->kateView) return 0;
  2181. while (theFile->kateView->document()->isModified()) { // "while" in case saving fails!
  2182. result=KMessageBox::questionYesNoCancel(this,QString("The file \'%1\' has been modified. Do you want to save the changes?").arg(theFile->text(0)),QString::null,KStandardGuiItem::save(),KStandardGuiItem::discard());
  2183. if (result==KMessageBox::Yes)
  2184. fileSave_save(fileItem);
  2185. else if (result==KMessageBox::No)
  2186. return 0;
  2187. else
  2188. return 1;
  2189. }
  2190. return 0;
  2191. }
  2192. //returns 1 if the current project data should not be cleared out, 0 if it can be cleared out.
  2193. int MainForm::savePrompt(void)
  2194. {
  2195. int result;
  2196. while (projectIsDirty) {
  2197. result=KMessageBox::questionYesNoCancel(this,"The current project has been modified. Do you want to save the changes?",QString::null,KStandardGuiItem::save(),KStandardGuiItem::discard());
  2198. if (result==KMessageBox::Yes)
  2199. fileSave();
  2200. else if (result==KMessageBox::No)
  2201. return 0;
  2202. else
  2203. return 1;
  2204. }
  2205. Q3ListViewItem *item=rootListItem->firstChild(),*next;
  2206. while (item)
  2207. {
  2208. if (IS_FOLDER(item))
  2209. {
  2210. next=item->firstChild();
  2211. if (next)
  2212. {
  2213. item=next;
  2214. continue;
  2215. }
  2216. }
  2217. if (IS_FILE(item))
  2218. {
  2219. if (fileSavePrompt(item))
  2220. return 1;
  2221. }
  2222. next=item->nextSibling();
  2223. while (!next)
  2224. {
  2225. next=item->parent();
  2226. if (next==rootListItem||!next)
  2227. {
  2228. return 0;
  2229. }
  2230. item=next;
  2231. next=item->nextSibling();
  2232. }
  2233. item=next;
  2234. }
  2235. return 0;
  2236. }
  2237. void MainForm::removeTrailingSpacesFromView(void *view)
  2238. {
  2239. if (!preferences.removeTrailingSpaces) return;
  2240. KTextEditor::View *kateView=reinterpret_cast<KTextEditor::View *>(view);
  2241. KTextEditor::Document *doc=kateView->document();
  2242. doc->startEditing();
  2243. int numLines=doc->lines();
  2244. for (int i=0; i<numLines; i++) {
  2245. QString line=doc->line(i);
  2246. int whitespace=line.find(QRegExp("\\s+$"));
  2247. if (whitespace>=0) doc->removeText(KTextEditor::Range(i,whitespace,i,line.length()));
  2248. }
  2249. doc->endEditing();
  2250. }
  2251. void MainForm::fileSave_save(Q3ListViewItem *theItem)
  2252. {
  2253. if (!IS_FILE(theItem))
  2254. return;
  2255. CATEGORY_OF(category,theItem);
  2256. if (!IS_EDITABLE_CATEGORY(category))
  2257. return;
  2258. ListViewFile *theFile=static_cast<ListViewFile *>(theItem);
  2259. if (!theFile->fileName.isEmpty() && theFile->fileName[0]!='/') {
  2260. fileSave_saveAs(theFile);
  2261. }
  2262. else {
  2263. KDirWatch::self()->removeFile(theFile->fileName);
  2264. if (!theFile->kateView->document()->save()) {
  2265. KMessageBox::error(this,QString("Can't save to \'%1\'").arg(theFile->text(0)));
  2266. KDirWatch::self()->addFile(theFile->fileName);
  2267. }
  2268. else {
  2269. KDirWatch::self()->addFile(theFile->fileName);
  2270. theFile->isNew=FALSE;
  2271. if (theFile->kateView) {
  2272. removeTrailingSpacesFromView(theFile->kateView);
  2273. theFile->kateView->document()->setModified(FALSE);
  2274. }
  2275. projectIsDirty=TRUE;
  2276. projectNeedsRelink=TRUE;
  2277. }
  2278. }
  2279. }
  2280. void MainForm::fileSave_saveAs(Q3ListViewItem *theItem)
  2281. {
  2282. if (!IS_FILE(theItem))
  2283. return;
  2284. CATEGORY_OF(category,theItem);
  2285. QString saveFileName=SGetFileName(KFileDialog::Saving,
  2286. category==hFilesListItem?TIGCC_H_Filter TIGCCAllFilter:
  2287. category==cFilesListItem?TIGCC_C_Filter TIGCCAllFilter:
  2288. category==sFilesListItem?TIGCC_S_Filter TIGCCAllFilter:
  2289. category==asmFilesListItem?TIGCC_ASM_Filter TIGCCAllFilter:
  2290. category==qllFilesListItem?TIGCC_QLL_Filter TIGCCAllFilter:
  2291. category==oFilesListItem?TIGCC_O_Filter TIGCCAllFilter:
  2292. category==aFilesListItem?TIGCC_A_Filter TIGCCAllFilter:
  2293. category==txtFilesListItem?TIGCC_TXT_Filter TIGCCAllFilter:
  2294. TIGCCAllFilter
  2295. ,"Save Source File",this);
  2296. ListViewFile *theFile=static_cast<ListViewFile *>(theItem);
  2297. if (saveFileName.isEmpty()
  2298. || (!IS_EDITABLE_CATEGORY(category)
  2299. && !saveFileName.compare(theFile->fileName)))
  2300. return;
  2301. if (saveFileName.compare(theFile->fileName)
  2302. && !checkFileName(saveFileName,extractAllFileNames())) {
  2303. KMessageBox::error(this,"The name you chose conflicts with that of another file.");
  2304. return;
  2305. }
  2306. if (!theFile->fileName.isEmpty() && theFile->fileName[0]=='/')
  2307. KDirWatch::self()->removeFile(theFile->fileName);
  2308. mkdir_multi(saveFileName);
  2309. if (IS_EDITABLE_CATEGORY(category)
  2310. ?!theFile->kateView->document()->saveAs(saveFileName)
  2311. :copyFile(theFile->fileName,saveFileName)) {
  2312. KMessageBox::error(this,QString("Can't save to \'%1\'").arg(saveFileName));
  2313. if (IS_EDITABLE_CATEGORY(category) && !theFile->fileName.isEmpty() && theFile->fileName[0]=='/')
  2314. KDirWatch::self()->addFile(theFile->fileName);
  2315. } else {
  2316. theFile->fileName=saveFileName;
  2317. if (IS_EDITABLE_CATEGORY(category)) {
  2318. KDirWatch::self()->addFile(saveFileName);
  2319. removeTrailingSpacesFromView(theFile->kateView);
  2320. theFile->kateView->document()->setModified(FALSE);
  2321. }
  2322. theFile->isNew=FALSE;
  2323. updateRightStatusLabel();
  2324. projectIsDirty=TRUE;
  2325. projectNeedsRelink=TRUE;
  2326. }
  2327. }
  2328. //loadList also saves the file contents
  2329. void MainForm::fileSave_loadList(Q3ListViewItem *category,void *fileListV,const QString &base_dir,void *dir_new,QString *open_file)
  2330. {
  2331. if (!category)
  2332. return;
  2333. TPRFileList *fileList=(TPRFileList*)fileListV;
  2334. KUrl *new_dir=(KUrl*)dir_new;
  2335. KUrl tmpPath;
  2336. Q3ListViewItem *item=category->firstChild();
  2337. Q3ListViewItem *next;
  2338. QString folderSpec=QString::null;
  2339. int o;
  2340. while (item)
  2341. {
  2342. if (IS_FILE(item))
  2343. {
  2344. ListViewFile *theFile=static_cast<ListViewFile *>(item);
  2345. QString absPath=theFile->fileName;
  2346. QString relPath=KUrl::relativePath(base_dir,absPath);
  2347. if (relPath.startsWith("./"))
  2348. {
  2349. relPath=relPath.mid(2);
  2350. }
  2351. else if (relPath.startsWith("../"))
  2352. {
  2353. relPath=absPath;
  2354. }
  2355. tmpPath=*new_dir;
  2356. kurlNewFileName(tmpPath,relPath);
  2357. if (!theFile->fileName.isEmpty() && theFile->fileName[0]=='/')
  2358. KDirWatch::self()->removeFile(theFile->fileName);
  2359. if (tmpPath.path().compare(theFile->fileName)
  2360. || (IS_EDITABLE_CATEGORY(category)
  2361. && (theFile->kateView->document()->isModified() || theFile->isNew))) {
  2362. mkdir_multi(tmpPath.path());
  2363. if (IS_EDITABLE_CATEGORY(category)
  2364. ?!theFile->kateView->document()->saveAs(tmpPath.path())
  2365. :copyFile(theFile->fileName,tmpPath.path())) {
  2366. KMessageBox::error(this,QString("Can't save to \'%1\'").arg(tmpPath.path()));
  2367. if (IS_EDITABLE_CATEGORY(category) && !theFile->fileName.isEmpty() && theFile->fileName[0]=='/')
  2368. KDirWatch::self()->addFile(theFile->fileName);
  2369. } else {
  2370. QString saveFileName=tmpPath.path();
  2371. theFile->fileName=saveFileName;
  2372. if (IS_EDITABLE_CATEGORY(category)) {
  2373. KDirWatch::self()->addFile(theFile->fileName);
  2374. removeTrailingSpacesFromView(theFile->kateView);
  2375. theFile->kateView->document()->setModified(FALSE);
  2376. }
  2377. theFile->isNew=FALSE;
  2378. projectIsDirty=TRUE; // in case saving the project fails
  2379. projectNeedsRelink=TRUE;
  2380. }
  2381. }
  2382. fileList->path << relPath;
  2383. fileList->folder << folderSpec;
  2384. if (item==currentListItem)
  2385. *open_file=theFile->fileName;
  2386. }
  2387. else if (IS_FOLDER(item))
  2388. {
  2389. next=item->firstChild();
  2390. if (next)
  2391. {
  2392. if (folderSpec.isEmpty())
  2393. folderSpec=item->text(0);
  2394. else
  2395. {
  2396. folderSpec+='\\';
  2397. folderSpec+=item->text(0);
  2398. }
  2399. item=next;
  2400. continue;
  2401. }
  2402. }
  2403. fsll_seeknext:
  2404. next=item->nextSibling();
  2405. if (!next)
  2406. {
  2407. next=item->parent();
  2408. if (next==category||!next)
  2409. break;
  2410. item=next;
  2411. o=folderSpec.findRev('\\');
  2412. if (o>=0)
  2413. folderSpec.truncate(o);
  2414. else
  2415. folderSpec.truncate(0);
  2416. goto fsll_seeknext;
  2417. }
  2418. item=next;
  2419. }
  2420. }
  2421. void MainForm::fileSave_fromto(const QString &lastProj,const QString &nextProj)
  2422. {
  2423. TPRDataStruct TPRData;
  2424. QString open_file;
  2425. KUrl base_dir_k(lastProj);
  2426. base_dir_k.setFileName("");
  2427. QString base_dir=base_dir_k.path();
  2428. KUrl new_dir(nextProj);
  2429. fileSave_loadList(hFilesListItem,&TPRData.h_files,base_dir,&new_dir,&open_file);
  2430. fileSave_loadList(cFilesListItem,&TPRData.c_files,base_dir,&new_dir,&open_file);
  2431. fileSave_loadList(qllFilesListItem,&TPRData.quill_files,base_dir,&new_dir,&open_file);
  2432. fileSave_loadList(sFilesListItem,&TPRData.s_files,base_dir,&new_dir,&open_file);
  2433. fileSave_loadList(asmFilesListItem,&TPRData.asm_files,base_dir,&new_dir,&open_file);
  2434. fileSave_loadList(oFilesListItem,&TPRData.o_files,base_dir,&new_dir,&open_file);
  2435. fileSave_loadList(aFilesListItem,&TPRData.a_files,base_dir,&new_dir,&open_file);
  2436. fileSave_loadList(txtFilesListItem,&TPRData.txt_files,base_dir,&new_dir,&open_file);
  2437. fileSave_loadList(othFilesListItem,&TPRData.oth_files,base_dir,&new_dir,&open_file);
  2438. if (projectFileName.isEmpty() && rootListItem->text(0)=="Project1")
  2439. fileTreeItemRenamed(rootListItem,QFileInfo(nextProj).baseName(),0);
  2440. TPRData.prj_name=rootListItem->text(0);
  2441. TPRData.open_file=open_file;
  2442. TPRData.settings=settings;
  2443. TPRData.libopts=libopts;
  2444. if (saveTPR(nextProj,&TPRData)) {
  2445. KMessageBox::error(this,QString("Can't save to \'%1\'").arg(nextProj));
  2446. updateRightStatusLabel();
  2447. return;
  2448. } else {
  2449. projectFileName=nextProj;
  2450. projectIsDirty=FALSE;
  2451. addRecent(nextProj);
  2452. }
  2453. updateRightStatusLabel();
  2454. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  2455. if (sourceFile->kateView->document()->isModified())
  2456. sourceFile->fileSave();
  2457. }
  2458. }
  2459. bool MainForm::fileSave()
  2460. {
  2461. if (projectFileName.isEmpty())
  2462. return fileSaveAs();
  2463. else {
  2464. fileSave_fromto(projectFileName,projectFileName);
  2465. return TRUE;
  2466. }
  2467. }
  2468. bool MainForm::fileSaveAs()
  2469. {
  2470. QString fileName=SGetFileName(KFileDialog::Saving,TIGCC_TPR_Filter TIGCCAllFilter,"Save Project",this);
  2471. if (fileName.isEmpty())
  2472. return FALSE;
  2473. fileSave_fromto(projectFileName.isEmpty()?fileName:projectFileName,fileName);
  2474. return TRUE;
  2475. }
  2476. void MainForm::filePrint()
  2477. {
  2478. if (CURRENT_VIEW) CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Print))->trigger();
  2479. }
  2480. void MainForm::filePrintQuickly()
  2481. {
  2482. // This still shows the print dialog, but then KDE 3.5 Kate did that too
  2483. // despite having 2 nominally different APIs (print and printDialog).
  2484. if (CURRENT_VIEW) CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Print))->trigger();
  2485. }
  2486. void MainForm::filePreferences()
  2487. {
  2488. if (showPreferencesDialog(this,!!asmFilesListItem,!!qllFilesListItem)
  2489. ==QDialog::Accepted) {
  2490. // Apply the KatePart preferences and treeview icons.
  2491. Q3ListViewItemIterator it(fileTree);
  2492. Q3ListViewItem *item;
  2493. // Kate seems really insisting on making it a pain to update syntax highlighting settings.
  2494. for (item=it.current();item;item=(++it).current()) {
  2495. if (IS_FILE(item)) {
  2496. KTextEditor::View *kateView=static_cast<ListViewFile *>(item)->kateView;
  2497. if (kateView) {
  2498. kateView->document()->setHighlightingMode("None");
  2499. }
  2500. }
  2501. }
  2502. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  2503. sourceFile->kateView->document()->setHighlightingMode("None");
  2504. }
  2505. KParts::Factory *factory=(KParts::Factory *)
  2506. KLibLoader::self()->factory("katepart");
  2507. if (!factory) qFatal("Failed to load KatePart");
  2508. KTextEditor::Document *doc=(KTextEditor::Document *)
  2509. factory->createPart(0,this,"KTextEditor::Document");
  2510. doc->setHighlightingMode("Asm6502"); // Don't ask...
  2511. doc->setHighlightingMode("None");
  2512. KTextEditor::Editor *editor=doc->editor();
  2513. int numConfigPages=editor->configPages();
  2514. for (int i=0; i<numConfigPages; i++) {
  2515. if (editor->configPageName(i)=="Fonts & Colors") {
  2516. KTextEditor::ConfigPage *configPage=editor->configPage(i,this);
  2517. configPage->apply();
  2518. delete configPage;
  2519. break;
  2520. }
  2521. }
  2522. delete doc;
  2523. it=Q3ListViewItemIterator(fileTree);
  2524. for (item=it.current();item;item=(++it).current()) {
  2525. if (item == rootListItem) {
  2526. item->setPixmap(0,SYSICON("system-run","tpr.png"));
  2527. } else if (IS_FOLDER(item)) {
  2528. // Bluecurve's "folder-open" isn't actually more open than "folder".
  2529. item->setPixmap(0,(item==currentListItem)?SYSICON(KIconTheme::current()=="Bluecurve"?"folder-accept":"folder-open","folder2.png")
  2530. :SYSICON("folder","folder1.png"));
  2531. } else if (IS_FILE(item)) {
  2532. CATEGORY_OF(category,item);
  2533. KTextEditor::View *kateView=static_cast<ListViewFile *>(item)->kateView;
  2534. if (kateView) {
  2535. QString fileText=kateView->document()->text();
  2536. CATEGORY_OF(category,item);
  2537. if (preferences.removeTrailingSpaces) {
  2538. sendCommand(kateView,"set-remove-trailing-space 1");
  2539. sendCommand(kateView,"set-remove-trailing-space-save 1");
  2540. } else {
  2541. sendCommand(kateView,"set-remove-trailing-space 0");
  2542. sendCommand(kateView,"set-remove-trailing-space-save 0");
  2543. }
  2544. setTabWidth(kateView,
  2545. (category==sFilesListItem||category==asmFilesListItem||((category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&(fileText[0]=='|'||fileText[0]==';'))))?preferences.tabWidthAsm:
  2546. (category==cFilesListItem||category==qllFilesListItem||category==hFilesListItem)?preferences.tabWidthC:
  2547. 8
  2548. );
  2549. // Kate seems really insisting on making it a pain to update syntax highlighting settings.
  2550. kateView->document()->setHighlightingMode(
  2551. (category==qllFilesListItem?
  2552. QLL_HL_MODE:
  2553. (category==sFilesListItem||(category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]=='|'))?
  2554. S_HL_MODE:
  2555. (category==asmFilesListItem||(category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]==';'))?
  2556. ASM_HL_MODE:
  2557. (category==cFilesListItem||category==hFilesListItem)?
  2558. C_HL_MODE:
  2559. "None"));
  2560. }
  2561. item->setPixmap(0,
  2562. category==cFilesListItem||category==qllFilesListItem?SYSICON("text-x-csrc","filec.png"):
  2563. category==hFilesListItem?SYSICON("text-x-chdr","fileh.png"):
  2564. category==sFilesListItem||category==asmFilesListItem?SYSICON("text-x-hex","files.png"):
  2565. category==txtFilesListItem?SYSICON("text-plain","filet.png"):
  2566. category==oFilesListItem||category==aFilesListItem?SYSICON("application-x-object","fileo.png"):
  2567. SYSICON("unknown","filex.png"));
  2568. } else qWarning("Internal error: What's this item?");
  2569. }
  2570. KTextEditor::View *currView=CURRENT_VIEW;
  2571. if (currView) {
  2572. // Force redrawing to get the tab width right, repaint() is ignored for some reason.
  2573. currView->hide();
  2574. currView->show();
  2575. }
  2576. // Apply the icon preferences.
  2577. if (preferences.useSystemIcons) {
  2578. // Set the preferred icon size so system toolbar icons don't get annoying
  2579. // padding.
  2580. int toolbarIconSize=KIconLoader().currentSize(KIconLoader::MainToolbar);
  2581. setIconSize(QSize(toolbarIconSize,toolbarIconSize));
  2582. fileNewAction->setIcon(KIcon("document-new"));
  2583. fileNewMenu->menuAction()->setIcon(KIcon("document-new"));
  2584. fileOpenAction->setIcon(KIcon("document-open"));
  2585. fileSaveAllAction->setIcon(KIcon("document-save"));
  2586. filePrintAction->setIcon(KIcon("document-print"));
  2587. filePrintQuicklyAction->setIcon(KIcon("document-print"));
  2588. editClearAction->setIcon(KIcon("edit-delete"));
  2589. editCutAction->setIcon(KIcon("edit-cut"));
  2590. editCopyAction->setIcon(KIcon("edit-copy"));
  2591. editPasteAction->setIcon(KIcon("edit-paste"));
  2592. projectAddFilesAction->setIcon(KIcon("list-add"));
  2593. projectCompileAction->setIcon(KIcon("run-build-file"));
  2594. projectMakeAction->setIcon(KIcon("run-build"));
  2595. projectBuildAction->setIcon(KIcon("view-refresh"));
  2596. helpContentsAction->setIcon(KIcon("help-contents"));
  2597. helpDocumentationAction->setIcon(KIcon("help-contents"));
  2598. helpSearchAction->setIcon(KIcon("system-search"));
  2599. findFindAction->setIcon(KIcon("edit-find"));
  2600. findReplaceAction->setIcon(KIcon("edit-find-replace"));
  2601. helpIndexAction->setIcon(KIcon("view-list-text"));
  2602. editUndoAction->setIcon(KIcon("edit-undo"));
  2603. editRedoAction->setIcon(KIcon("edit-redo"));
  2604. findFunctionsAction->setIcon(KIcon("view-list-tree"));
  2605. editIncreaseIndentAction->setIcon(KIcon("format-indent-more"));
  2606. editDecreaseIndentAction->setIcon(KIcon("format-indent-less"));
  2607. projectStopCompilationAction->setIcon(KIcon("process-stop"));
  2608. projectForceQuitAction->setIcon(KIcon("dialog-cancel"));
  2609. helpNewsAction->setIcon(KIcon("view-pim-news"));
  2610. debugRunAction->setIcon(KIcon("media-playback-start"));
  2611. debugPauseAction->setIcon(KIcon("media-playback-pause"));
  2612. toolsConfigureAction->setIcon(KIcon("configure"));
  2613. debugResetAction->setIcon(KIcon("media-playback-stop"));
  2614. } else {
  2615. setIconSize(QSize(20,20));
  2616. fileNewAction->setIcon(QIcon(QPixmap(":/images/00.png")));
  2617. fileNewMenu->menuAction()->setIcon(QIcon(QPixmap(":/images/00.png")));
  2618. fileOpenAction->setIcon(QIcon(QPixmap(":/images/01.png")));
  2619. fileSaveAllAction->setIcon(QIcon(QPixmap(":/images/02.png")));
  2620. filePrintAction->setIcon(QIcon(QPixmap(":/images/03.png")));
  2621. filePrintQuicklyAction->setIcon(QIcon(QPixmap(":/images/03.png")));
  2622. editClearAction->setIcon(QIcon(QPixmap(":/images/04.png")));
  2623. editCutAction->setIcon(QIcon(QPixmap(":/images/05.png")));
  2624. editCopyAction->setIcon(QIcon(QPixmap(":/images/06.png")));
  2625. editPasteAction->setIcon(QIcon(QPixmap(":/images/07.png")));
  2626. projectAddFilesAction->setIcon(QIcon(QPixmap(":/images/08.png")));
  2627. projectCompileAction->setIcon(QIcon(QPixmap(":/images/09.png")));
  2628. projectMakeAction->setIcon(QIcon(QPixmap(":/images/10.png")));
  2629. projectBuildAction->setIcon(QIcon(QPixmap(":/images/11.png")));
  2630. helpContentsAction->setIcon(QIcon(QPixmap(":/images/12.png")));
  2631. helpDocumentationAction->setIcon(QIcon(QPixmap(":/images/12.png")));
  2632. helpSearchAction->setIcon(QIcon(QPixmap(":/images/13.png")));
  2633. findFindAction->setIcon(QIcon(QPixmap(":/images/13.png")));
  2634. findReplaceAction->setIcon(QIcon(QPixmap(":/images/14.png")));
  2635. helpIndexAction->setIcon(QIcon(QPixmap(":/images/15.png")));
  2636. editUndoAction->setIcon(QIcon(QPixmap(":/images/16.png")));
  2637. editRedoAction->setIcon(QIcon(QPixmap(":/images/17.png")));
  2638. findFunctionsAction->setIcon(QIcon(QPixmap(":/images/18.png")));
  2639. editIncreaseIndentAction->setIcon(QIcon(QPixmap(":/images/19.png")));
  2640. editDecreaseIndentAction->setIcon(QIcon(QPixmap(":/images/20.png")));
  2641. projectStopCompilationAction->setIcon(QIcon(QPixmap(":/images/21.png")));
  2642. projectForceQuitAction->setIcon(QIcon(QPixmap(":/images/22.png")));
  2643. helpNewsAction->setIcon(QIcon(QPixmap(":/images/23.png")));
  2644. debugRunAction->setIcon(QIcon(QPixmap(":/images/24.png")));
  2645. debugPauseAction->setIcon(QIcon(QPixmap(":/images/25.png")));
  2646. toolsConfigureAction->setIcon(QIcon(QPixmap(":/images/26.png")));
  2647. debugResetAction->setIcon(QIcon(QPixmap(":/images/27.png")));
  2648. }
  2649. it=Q3ListViewItemIterator(errorList->errorListView);
  2650. for (item=it.current();item;item=(++it).current()) {
  2651. switch(item->rtti()) {
  2652. case etError:
  2653. item->setPixmap(0,SYSICON("dialog-error","error.png"));
  2654. break;
  2655. case etWarning:
  2656. item->setPixmap(0,SYSICON("dialog-warning","warning.png"));
  2657. break;
  2658. default:
  2659. item->setPixmap(0,SYSICON("dialog-information","info.png"));
  2660. break;
  2661. }
  2662. }
  2663. // Apply the preferences to the source file windows.
  2664. foreach (SourceFileWindow *sourceFile, sourceFiles) sourceFile->applyPreferences();
  2665. // Apply the preferences to the debug menu.
  2666. debugPauseAction->setEnabled(!compiling&&preferences.linkTarget==LT_TIEMU);
  2667. debugResetAction->setEnabled(!compiling&&preferences.linkTarget==LT_TIEMU);
  2668. bool runnable=!settings.archive&&!settings.flash_os&&preferences.linkTarget!=LT_NONE;
  2669. menuBar()->setItemVisible(5,runnable); //debugMenu
  2670. debugRunAction->setVisible(runnable);
  2671. debugPauseAction->setVisible(runnable);
  2672. }
  2673. }
  2674. void MainForm::editUndo()
  2675. {
  2676. if (CURRENT_VIEW)
  2677. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Undo))->trigger();
  2678. }
  2679. void MainForm::editRedo()
  2680. {
  2681. if (CURRENT_VIEW)
  2682. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Redo))->trigger();
  2683. }
  2684. void MainForm::editClear()
  2685. {
  2686. if (CURRENT_VIEW)
  2687. CURRENT_VIEW->removeSelectionText();
  2688. }
  2689. void MainForm::editCut()
  2690. {
  2691. if (CURRENT_VIEW)
  2692. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Cut))->trigger();
  2693. }
  2694. void MainForm::editCopy()
  2695. {
  2696. if (CURRENT_VIEW)
  2697. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Copy))->trigger();
  2698. }
  2699. void MainForm::editPaste()
  2700. {
  2701. if (CURRENT_VIEW)
  2702. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::PasteText))->trigger();
  2703. }
  2704. void MainForm::editSelectAll()
  2705. {
  2706. if (CURRENT_VIEW)
  2707. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::SelectAll))->trigger();
  2708. }
  2709. void MainForm::editIncreaseIndent()
  2710. {
  2711. if (CURRENT_VIEW)
  2712. CURRENT_VIEW->action("tools_indent")->trigger();
  2713. }
  2714. void MainForm::editDecreaseIndent()
  2715. {
  2716. if (CURRENT_VIEW)
  2717. CURRENT_VIEW->action("tools_unindent")->trigger();
  2718. }
  2719. class NonModalFindDialog : public KFindDialog {
  2720. public:
  2721. explicit NonModalFindDialog(QWidget *parent=0, long options=0,
  2722. const QStringList &findStrings=QStringList(), bool hasSelection=false)
  2723. : KFindDialog(parent,options,findStrings,hasSelection)
  2724. {
  2725. setModal(false);
  2726. }
  2727. // Override accept() not to close the dialog.
  2728. virtual void accept(void)
  2729. {
  2730. setResult(QDialog::Accepted);
  2731. }
  2732. };
  2733. void MainForm::findFind()
  2734. {
  2735. if (kfinddialog)
  2736. ACTIVATE_WINDOW(kfinddialog->winId());
  2737. else {
  2738. // Never set hasSelection because finding in selection doesn't really make
  2739. // sense with my non-modal find dialog setup.
  2740. kfinddialog=new NonModalFindDialog(this,KFind::FromCursor,findHistory);
  2741. connect(kfinddialog, SIGNAL(okClicked()), this, SLOT(findFind_next()));
  2742. connect(kfinddialog, SIGNAL(cancelClicked()), this, SLOT(findFind_stop()));
  2743. kfinddialog->show();
  2744. }
  2745. }
  2746. void MainForm::findFind_next()
  2747. {
  2748. // Use a local KFind object. The search will need to be restarted next time
  2749. // this function is called because of the non-modality of the find dialog.
  2750. KFind *kfind=new KFind(kfinddialog->pattern(),kfinddialog->options(),this,kfinddialog);
  2751. // Initialize.
  2752. bool findBackwards=!!(kfinddialog->options()&KFind::FindBackwards);
  2753. int findCurrentCol;
  2754. kfind=new KFind(kfinddialog->pattern(),kfinddialog->options(),this,kfinddialog);
  2755. kfind->closeFindNextDialog(); // don't use this, a non-modal KFindDialog is used instead
  2756. connect(kfind,SIGNAL(highlight(const QString &,int,int)),
  2757. this,SLOT(findFind_highlight(const QString &,int,int)));
  2758. // Make sure we have a valid currentListItem.
  2759. if (!currentListItem) fileTreeClicked(rootListItem);
  2760. findCurrentDocument=currentListItem;
  2761. if (CURRENT_VIEW) {
  2762. if (kfinddialog->options()&KFind::FromCursor) {
  2763. if (CURRENT_VIEW->selection()) {
  2764. if (findBackwards) {
  2765. CURRENT_VIEW->selectionRange().start().position(findCurrentLine,findCurrentCol);
  2766. if ((--findCurrentCol)==-1) {
  2767. if (!findCurrentLine) goto skip_data;
  2768. findCurrentLine--;
  2769. }
  2770. } else {
  2771. CURRENT_VIEW->selectionRange().end().position(findCurrentLine,findCurrentCol);
  2772. }
  2773. } else {
  2774. CURRENT_VIEW->cursorPosition().position(findCurrentLine,findCurrentCol);
  2775. }
  2776. } else {
  2777. findCurrentLine=findBackwards?(CURRENT_VIEW->document()->lines()-1):0;
  2778. findCurrentCol=-1;
  2779. }
  2780. kfind->setData(CURRENT_VIEW->document()->line(findCurrentLine),findCurrentCol);
  2781. } else findCurrentLine=0;
  2782. skip_data:;
  2783. // Now find the next occurrence.
  2784. KFind::Result result;
  2785. KTextEditor::View *currView=CURRENT_VIEW;
  2786. // We never have a currBuffer here, the current list item is always either
  2787. // non-editable or instantiated.
  2788. QStringList currBuffer;
  2789. int currNumLines=0;
  2790. if (CURRENT_VIEW) currNumLines=CURRENT_VIEW->document()->lines();
  2791. do {
  2792. if (kfind->needData()) {
  2793. if (findBackwards?!findCurrentLine:(findCurrentLine>=currNumLines)) {
  2794. if (findBackwards) {
  2795. // Traverse the file tree in order backwards, restart from the end if
  2796. // the first file was reached. Stop at currentListItem.
  2797. if (findCurrentDocument) {
  2798. Q3ListViewItemIterator lvit(fileTree);
  2799. Q3PtrList<Q3ListViewItem> lst;
  2800. Q3ListViewItem *item;
  2801. for (item=lvit.current();item&&item!=findCurrentDocument;
  2802. item=(++lvit).current()) {
  2803. lst.prepend(item);
  2804. }
  2805. Q3PtrListIterator<Q3ListViewItem> it(lst);
  2806. for (findCurrentDocument=it.current();
  2807. findCurrentDocument&&findCurrentDocument!=currentListItem;
  2808. findCurrentDocument=++it) {
  2809. if (IS_FILE(findCurrentDocument)) {
  2810. CATEGORY_OF(category,findCurrentDocument);
  2811. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  2812. }
  2813. }
  2814. if (findCurrentDocument) goto not_found;
  2815. }
  2816. Q3ListViewItemIterator lvit(currentListItem);
  2817. Q3PtrList<Q3ListViewItem> lst;
  2818. Q3ListViewItem *item;
  2819. for (item=(++lvit).current();item;item=(++lvit).current()) {
  2820. lst.prepend(item);
  2821. }
  2822. Q3PtrListIterator<Q3ListViewItem> it(lst);
  2823. for (findCurrentDocument=it.current();findCurrentDocument;
  2824. findCurrentDocument=++it) {
  2825. if (IS_FILE(findCurrentDocument)) {
  2826. CATEGORY_OF(category,findCurrentDocument);
  2827. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  2828. }
  2829. }
  2830. goto not_found;
  2831. } else {
  2832. // Traverse the file tree in order, restart from the beginning if
  2833. // the last file was reached. Stop at currentListItem.
  2834. if (findCurrentDocument) {
  2835. Q3ListViewItemIterator it(findCurrentDocument);
  2836. for (findCurrentDocument=(++it).current();
  2837. findCurrentDocument&&findCurrentDocument!=currentListItem;
  2838. findCurrentDocument=(++it).current()) {
  2839. if (IS_FILE(findCurrentDocument)) {
  2840. CATEGORY_OF(category,findCurrentDocument);
  2841. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  2842. }
  2843. }
  2844. if (findCurrentDocument) goto not_found;
  2845. }
  2846. {
  2847. Q3ListViewItemIterator it(fileTree);
  2848. for (findCurrentDocument=it.current();
  2849. findCurrentDocument&&findCurrentDocument!=currentListItem;
  2850. findCurrentDocument=(++it).current()) {
  2851. if (IS_FILE(findCurrentDocument)) {
  2852. CATEGORY_OF(category,findCurrentDocument);
  2853. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  2854. }
  2855. }
  2856. }
  2857. not_found:
  2858. // No find in all files. Try currentListItem again because it hasn't
  2859. // been fully searched yet.
  2860. if (IS_FILE(currentListItem)) {
  2861. // currentListItem is always either instantiated or not editable
  2862. currView=static_cast<ListViewFile *>(currentListItem)->kateView;
  2863. if (currView) {
  2864. currNumLines=currView->document()->lines();
  2865. findCurrentLine=findBackwards?currNumLines-1:0;
  2866. do {
  2867. if (kfind->needData()) {
  2868. if (findBackwards?!findCurrentLine:(findCurrentLine>=currNumLines))
  2869. goto not_found_current;
  2870. if (findBackwards) findCurrentLine--; else findCurrentLine++;
  2871. kfind->setData(currView->document()->line(findCurrentLine));
  2872. }
  2873. result=kfind->find();
  2874. } while (result==KFind::NoMatch);
  2875. break;
  2876. }
  2877. }
  2878. not_found_current:
  2879. KMessageBox::error(this,QString("Text \'%1\' not found").arg(kfinddialog->pattern()));
  2880. delete kfind;
  2881. return;
  2882. file_found:
  2883. currView=static_cast<ListViewFile *>(findCurrentDocument)->kateView;
  2884. currNumLines=currView->document()->lines();
  2885. findCurrentLine=findBackwards?currNumLines-1:0;
  2886. }
  2887. } else if (findBackwards) findCurrentLine--; else findCurrentLine++;
  2888. if (currView)
  2889. kfind->setData(currView->document()->line(findCurrentLine));
  2890. else
  2891. kfind->setData(currBuffer[findCurrentLine]);
  2892. }
  2893. result=kfind->find();
  2894. } while (result==KFind::NoMatch);
  2895. delete kfind;
  2896. }
  2897. void MainForm::findFind_highlight(const QString &text __attribute__((unused)), int matchingindex, int matchedlength)
  2898. {
  2899. if (currentListItem!=findCurrentDocument) fileTreeClicked(findCurrentDocument);
  2900. if (!CURRENT_VIEW) qFatal("CURRENT_VIEW should be set here!");
  2901. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(findCurrentLine,matchingindex+matchedlength));
  2902. CURRENT_VIEW->setSelection(KTextEditor::Range(findCurrentLine,matchingindex,
  2903. findCurrentLine,matchingindex+matchedlength));
  2904. }
  2905. void MainForm::findFind_stop()
  2906. {
  2907. if (kfinddialog) {
  2908. findHistory=kfinddialog->findHistory();
  2909. kfinddialog->deleteLater();
  2910. }
  2911. kfinddialog=static_cast<KFindDialog *>(NULL);
  2912. }
  2913. void MainForm::findReplace()
  2914. {
  2915. if (kreplace) {
  2916. KDialog *replaceNextDialog=kreplace->replaceNextDialog();
  2917. if (replaceNextDialog)
  2918. ACTIVATE_WINDOW(replaceNextDialog->winId());
  2919. return;
  2920. }
  2921. KReplaceDialog kreplacedialog(this,((CURRENT_VIEW&&CURRENT_VIEW->selection()
  2922. &&!CURRENT_VIEW->selectionRange().onSingleLine())?
  2923. KFind::SelectedText:0)|KFind::FromCursor,
  2924. findHistory,replacementHistory,
  2925. CURRENT_VIEW&&CURRENT_VIEW->selection());
  2926. if (kreplacedialog.exec()!=QDialog::Accepted)
  2927. return;
  2928. findHistory=kreplacedialog.findHistory();
  2929. replacementHistory=kreplacedialog.replacementHistory();
  2930. kreplace=new KReplaceWithSelection(kreplacedialog.pattern(),kreplacedialog.replacement(),
  2931. kreplacedialog.options(),this);
  2932. // Connect signals to code which handles highlighting of found text, and
  2933. // on-the-fly replacement.
  2934. connect(kreplace,SIGNAL(highlight(const QString &,int,int)),
  2935. this,SLOT(findReplace_highlight(const QString &,int,int)));
  2936. // Connect findNext signal - called when pressing the button in the dialog.
  2937. connect(kreplace,SIGNAL(findNext()),this,SLOT(findReplace_next()));
  2938. // Connect replace signal - called when doing a replacement.
  2939. connect(kreplace,SIGNAL(replace(const QString &,int,int,int)),
  2940. this,SLOT(findReplace_replace(const QString &,int,int,int)));
  2941. // Connect dialogClosed signal - called when closing the Replace Next dialog.
  2942. connect(kreplace,SIGNAL(dialogClosed()),this,SLOT(findReplace_stop()));
  2943. // Initialize.
  2944. bool findBackwards=!!(kreplace->options()&KFind::FindBackwards);
  2945. int replaceCurrentCol;
  2946. // Make sure we have a valid currentListItem.
  2947. if (!currentListItem) fileTreeClicked(rootListItem);
  2948. replaceCurrentDocument=currentListItem;
  2949. if (CURRENT_VIEW) {
  2950. if (kreplace->options()&KFind::SelectedText) {
  2951. kreplace->setSelection(CURRENT_VIEW->selectionRange());
  2952. if (findBackwards) {
  2953. replaceCurrentLine=kreplace->selEndLine();
  2954. replaceCurrentCol=kreplace->selEndCol();
  2955. } else {
  2956. replaceCurrentLine=kreplace->selStartLine();
  2957. replaceCurrentCol=kreplace->selStartCol();
  2958. }
  2959. kreplace->setOptions(kreplace->options()&~KFind::FromCursor);
  2960. } else if (kreplace->options()&KFind::FromCursor) {
  2961. if (CURRENT_VIEW->selection()) {
  2962. if (findBackwards) {
  2963. CURRENT_VIEW->selectionRange().start().position(replaceCurrentLine,
  2964. replaceCurrentCol);
  2965. if ((--replaceCurrentCol)==-1) {
  2966. if (!replaceCurrentLine) goto skip_data;
  2967. replaceCurrentLine--;
  2968. }
  2969. } else {
  2970. CURRENT_VIEW->selectionRange().end().position(replaceCurrentLine,
  2971. replaceCurrentCol);
  2972. }
  2973. } else {
  2974. CURRENT_VIEW->cursorPosition().position(replaceCurrentLine,replaceCurrentCol);
  2975. // Don't prompt for restarting if we actually searched the entire document.
  2976. if (findBackwards?(replaceCurrentLine==(CURRENT_VIEW->document()->lines()-1)
  2977. && replaceCurrentCol==(CURRENT_VIEW->document()->lineLength(replaceCurrentLine)))
  2978. :(!replaceCurrentLine&&!replaceCurrentCol))
  2979. kreplace->setOptions(kreplace->options()&~KFind::FromCursor);
  2980. }
  2981. } else {
  2982. replaceCurrentLine=findBackwards?(CURRENT_VIEW->document()->lines()-1):0;
  2983. replaceCurrentCol=-1;
  2984. }
  2985. kreplace->setData(CURRENT_VIEW->document()->line(replaceCurrentLine),replaceCurrentCol);
  2986. }
  2987. skip_data:
  2988. // Now find the next occurrence.
  2989. findReplace_next(TRUE);
  2990. }
  2991. void MainForm::findReplace_next()
  2992. {
  2993. findReplace_next(FALSE);
  2994. }
  2995. void MainForm::findReplace_next(bool firstTime)
  2996. {
  2997. // Replace All only works on the current file. Also, if we have a selection,
  2998. // we only want to work on the file containing the selection.
  2999. bool global=(kreplace->options()&KReplaceDialog::PromptOnReplace)&&!kreplace->haveSelection();
  3000. bool findBackwards=!!(kreplace->options()&KFind::FindBackwards);
  3001. // Reinitialize.
  3002. if (!firstTime) {
  3003. int replaceCurrentCol;
  3004. // Make sure we have a valid currentListItem.
  3005. if (!currentListItem) fileTreeClicked(rootListItem);
  3006. replaceCurrentDocument=currentListItem;
  3007. if (CURRENT_VIEW) {
  3008. // Non-first-time always continues from cursor.
  3009. if (CURRENT_VIEW->selection()) {
  3010. if (findBackwards) {
  3011. CURRENT_VIEW->selectionRange().start().position(replaceCurrentLine,
  3012. replaceCurrentCol);
  3013. if ((--replaceCurrentCol)==-1) {
  3014. if (!replaceCurrentLine) goto skip_data;
  3015. replaceCurrentLine--;
  3016. }
  3017. } else {
  3018. CURRENT_VIEW->selectionRange().end().position(replaceCurrentLine,
  3019. replaceCurrentCol);
  3020. }
  3021. } else {
  3022. CURRENT_VIEW->cursorPosition().position(replaceCurrentLine,replaceCurrentCol);
  3023. }
  3024. kreplace->setData(CURRENT_VIEW->document()->line(replaceCurrentLine),replaceCurrentCol);
  3025. } else replaceCurrentLine=0;
  3026. }
  3027. skip_data:;
  3028. // Now find the next occurrence.
  3029. KFind::Result result;
  3030. KTextEditor::View *currView=CURRENT_VIEW;
  3031. // We never have a currBuffer here, the current list item is always either
  3032. // non-editable or instantiated.
  3033. QStringList currBuffer;
  3034. int currNumLines=0;
  3035. if (CURRENT_VIEW) currNumLines=CURRENT_VIEW->document()->lines();
  3036. do {
  3037. if (kreplace->needData()) {
  3038. if (global) {
  3039. if (findBackwards?!replaceCurrentLine:(replaceCurrentLine>=currNumLines)) {
  3040. if (findBackwards) {
  3041. // Traverse the file tree in order backwards, restart from the end if
  3042. // the first file was reached. Stop at currentListItem.
  3043. if (replaceCurrentDocument) {
  3044. Q3ListViewItemIterator lvit(fileTree);
  3045. Q3PtrList<Q3ListViewItem> lst;
  3046. Q3ListViewItem *item;
  3047. for (item=lvit.current();item&&item!=replaceCurrentDocument;
  3048. item=(++lvit).current()) {
  3049. lst.prepend(item);
  3050. }
  3051. Q3PtrListIterator<Q3ListViewItem> it(lst);
  3052. for (replaceCurrentDocument=it.current();
  3053. replaceCurrentDocument&&replaceCurrentDocument!=currentListItem;
  3054. replaceCurrentDocument=++it) {
  3055. if (IS_FILE(replaceCurrentDocument)) {
  3056. CATEGORY_OF(category,replaceCurrentDocument);
  3057. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  3058. }
  3059. }
  3060. if (replaceCurrentDocument) goto not_found;
  3061. }
  3062. Q3ListViewItemIterator lvit(currentListItem);
  3063. Q3PtrList<Q3ListViewItem> lst;
  3064. Q3ListViewItem *item;
  3065. for (item=(++lvit).current();item;item=(++lvit).current()) {
  3066. lst.prepend(item);
  3067. }
  3068. Q3PtrListIterator<Q3ListViewItem> it(lst);
  3069. for (replaceCurrentDocument=it.current();replaceCurrentDocument;
  3070. replaceCurrentDocument=++it) {
  3071. if (IS_FILE(replaceCurrentDocument)) {
  3072. CATEGORY_OF(category,replaceCurrentDocument);
  3073. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  3074. }
  3075. }
  3076. goto not_found;
  3077. } else {
  3078. // Traverse the file tree in order, restart from the beginning if
  3079. // the last file was reached. Stop at currentListItem.
  3080. if (replaceCurrentDocument) {
  3081. Q3ListViewItemIterator it(replaceCurrentDocument);
  3082. for (replaceCurrentDocument=(++it).current();
  3083. replaceCurrentDocument&&replaceCurrentDocument!=currentListItem;
  3084. replaceCurrentDocument=(++it).current()) {
  3085. if (IS_FILE(replaceCurrentDocument)) {
  3086. CATEGORY_OF(category,replaceCurrentDocument);
  3087. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  3088. }
  3089. }
  3090. if (replaceCurrentDocument) goto not_found;
  3091. }
  3092. {
  3093. Q3ListViewItemIterator it(fileTree);
  3094. for (replaceCurrentDocument=it.current();
  3095. replaceCurrentDocument&&replaceCurrentDocument!=currentListItem;
  3096. replaceCurrentDocument=(++it).current()) {
  3097. if (IS_FILE(replaceCurrentDocument)) {
  3098. CATEGORY_OF(category,replaceCurrentDocument);
  3099. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  3100. }
  3101. }
  3102. }
  3103. not_found:
  3104. // No find in all files. Try currentListItem again because it hasn't
  3105. // been fully searched yet.
  3106. if (IS_FILE(currentListItem)) {
  3107. // currentListItem is always either instantiated or not editable
  3108. currView=static_cast<ListViewFile *>(currentListItem)->kateView;
  3109. if (currView) {
  3110. currNumLines=currView->document()->lines();
  3111. replaceCurrentLine=findBackwards?currNumLines-1:0;
  3112. do {
  3113. if (kreplace->needData()) {
  3114. if (findBackwards?!replaceCurrentLine:(replaceCurrentLine>=currNumLines))
  3115. goto not_found_current;
  3116. if (findBackwards) replaceCurrentLine--; else replaceCurrentLine++;
  3117. kreplace->setData(currView->document()->line(replaceCurrentLine));
  3118. }
  3119. result=kreplace->replace();
  3120. } while (result==KFind::NoMatch);
  3121. break;
  3122. }
  3123. }
  3124. not_found_current:
  3125. kreplace->displayFinalDialog();
  3126. findReplace_stop();
  3127. return;
  3128. file_found:
  3129. currView=static_cast<ListViewFile *>(replaceCurrentDocument)->kateView;
  3130. currNumLines=currView->document()->lines();
  3131. replaceCurrentLine=findBackwards?currNumLines-1:0;
  3132. }
  3133. } else if (findBackwards) replaceCurrentLine--; else replaceCurrentLine++;
  3134. if (currView)
  3135. kreplace->setData(currView->document()->line(replaceCurrentLine));
  3136. else
  3137. kreplace->setData(currBuffer[replaceCurrentLine]);
  3138. } else { // if not global
  3139. if (kreplace->haveSelection()
  3140. ?(findBackwards?(replaceCurrentLine<=kreplace->selStartLine())
  3141. :(replaceCurrentLine>=kreplace->selEndLine()))
  3142. :(findBackwards?!replaceCurrentLine:(replaceCurrentLine>=currNumLines))) {
  3143. // It makes no sense to prompt for restarting if we aren't actually
  3144. // searching anywhere.
  3145. if (CURRENT_VIEW) {
  3146. if (kreplace->shouldRestart()) {
  3147. // Drop "From cursor" and "Selected text" options.
  3148. kreplace->setOptions(kreplace->options()&~(KFind::FromCursor
  3149. |KFind::SelectedText));
  3150. kreplace->invalidateSelection();
  3151. // Reinitialize.
  3152. replaceCurrentLine=findBackwards?(CURRENT_VIEW->document()->lines()-1):0;
  3153. kreplace->setData(CURRENT_VIEW->document()->line(replaceCurrentLine));
  3154. // Start again as if it was the first time.
  3155. findReplace_next(TRUE);
  3156. return;
  3157. } else {
  3158. findReplace_stop();
  3159. return;
  3160. }
  3161. } else goto not_found_current;
  3162. } else if (findBackwards) replaceCurrentLine--; else replaceCurrentLine++;
  3163. if (currView)
  3164. kreplace->setData(currView->document()->line(replaceCurrentLine));
  3165. else
  3166. kreplace->setData(currBuffer[replaceCurrentLine]);
  3167. }
  3168. }
  3169. result=kreplace->replace();
  3170. } while (result==KFind::NoMatch);
  3171. }
  3172. void MainForm::findReplace_highlight(const QString &text __attribute__((unused)), int matchingindex, int matchedlength)
  3173. {
  3174. if (currentListItem!=replaceCurrentDocument) fileTreeClicked(replaceCurrentDocument);
  3175. if (!CURRENT_VIEW) qFatal("CURRENT_VIEW should be set here!");
  3176. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(replaceCurrentLine,matchingindex+matchedlength));
  3177. CURRENT_VIEW->setSelection(KTextEditor::Range(replaceCurrentLine,matchingindex,
  3178. replaceCurrentLine,matchingindex+matchedlength));
  3179. }
  3180. void MainForm::findReplace_replace(const QString &text, int replacementIndex, int replacedLength, int matchedLength)
  3181. {
  3182. if (currentListItem!=replaceCurrentDocument) fileTreeClicked(replaceCurrentDocument);
  3183. if (!CURRENT_VIEW) qFatal("CURRENT_VIEW should be set here!");
  3184. bool update=!!(kreplace->options()&KReplaceDialog::PromptOnReplace);
  3185. bool haveSelection=kreplace->haveSelection();
  3186. // The initializations are redundant, but g++ doesn't understand this, and the
  3187. // self-initialization trick doesn't work either (-Wno-init-self is ignored).
  3188. int selStartLine=0, selStartCol=0, selEndLine=0, selEndCol=0;
  3189. if (haveSelection) {
  3190. selStartLine=kreplace->selStartLine();
  3191. selStartCol=kreplace->selStartCol();
  3192. selEndLine=kreplace->selEndLine();
  3193. selEndCol=kreplace->selEndCol();
  3194. }
  3195. CURRENT_VIEW->document()->startEditing();
  3196. CURRENT_VIEW->document()->insertText(KTextEditor::Cursor(replaceCurrentLine,replacementIndex),
  3197. text.mid(replacementIndex,replacedLength));
  3198. // We can't put the cursor back now because this breaks editBegin/editEnd.
  3199. int line,col;
  3200. CURRENT_VIEW->cursorPosition().position(line,col);
  3201. bool updateCursor=(line==replaceCurrentLine && col==replacementIndex+replacedLength);
  3202. CURRENT_VIEW->document()->removeText(KTextEditor::Range(replaceCurrentLine,replacementIndex+replacedLength,
  3203. replaceCurrentLine,replacementIndex+replacedLength+matchedLength));
  3204. CURRENT_VIEW->document()->endEditing();
  3205. if (updateCursor)
  3206. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(replaceCurrentLine,replacementIndex));
  3207. if (update) {
  3208. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(replaceCurrentLine,replacementIndex+replacedLength));
  3209. CURRENT_VIEW->setSelection(KTextEditor::Range(replaceCurrentLine,replacementIndex,
  3210. replaceCurrentLine,replacementIndex+replacedLength));
  3211. CURRENT_VIEW->repaint();
  3212. }
  3213. if (haveSelection) {
  3214. // Restore selection, updating coordinates if necessary.
  3215. kreplace->setSelection(selStartLine,selStartCol,selEndLine,
  3216. (replaceCurrentLine==selEndLine)
  3217. ?(selEndCol+replacedLength-matchedLength)
  3218. :selEndCol);
  3219. }
  3220. }
  3221. void MainForm::findReplace_stop()
  3222. {
  3223. if (kreplace) kreplace->deleteLater();
  3224. kreplace=static_cast<KReplaceWithSelection *>(NULL);
  3225. }
  3226. static SourceFileFunctions sourceFileFunctions;
  3227. static FunctionDialog *functionDialog;
  3228. void MainForm::findFunctions()
  3229. {
  3230. if (CURRENT_VIEW) {
  3231. functionDialog=new FunctionDialog(this);
  3232. connect(functionDialog->functionListBox,SIGNAL(highlighted(int)),
  3233. this,SLOT(findFunctions_functionListBox_highlighted(int)));
  3234. connect(functionDialog->functionListBox,SIGNAL(selected(int)),
  3235. this,SLOT(findFunctions_functionListBox_selected(int)));
  3236. connect(functionDialog->prototypeButton,SIGNAL(clicked()),
  3237. this,SLOT(findFunctions_prototypeButton_clicked()));
  3238. connect(functionDialog->implementationButton,SIGNAL(clicked()),
  3239. this,SLOT(findFunctions_implementationButton_clicked()));
  3240. functionDialog->functionListBox->clear();
  3241. CATEGORY_OF(category,currentListItem);
  3242. sourceFileFunctions=getFunctions(CURRENT_VIEW->document()->text(),
  3243. category==asmFilesListItem||category==sFilesListItem);
  3244. for (SourceFileFunctions::Iterator it=sourceFileFunctions.begin();
  3245. it!=sourceFileFunctions.end(); ++it)
  3246. functionDialog->functionListBox->insertItem((*it).name);
  3247. functionDialog->exec();
  3248. delete functionDialog;
  3249. }
  3250. }
  3251. void MainForm::findFunctions_functionListBox_highlighted(int index)
  3252. {
  3253. if (index>=0) {
  3254. functionDialog->prototypeButton->setEnabled(
  3255. sourceFileFunctions[index].prototypeLine>=0);
  3256. functionDialog->implementationButton->setEnabled(
  3257. sourceFileFunctions[index].implementationLine>=0);
  3258. } else {
  3259. functionDialog->prototypeButton->setEnabled(FALSE);
  3260. functionDialog->implementationButton->setEnabled(FALSE);
  3261. }
  3262. }
  3263. void MainForm::findFunctions_functionListBox_selected(int index)
  3264. {
  3265. if (index>=0) {
  3266. int line=sourceFileFunctions[index].implementationLine>=0
  3267. ?sourceFileFunctions[index].implementationLine
  3268. :sourceFileFunctions[index].prototypeLine;
  3269. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(line,0));
  3270. functionDialog->accept();
  3271. }
  3272. }
  3273. void MainForm::findFunctions_prototypeButton_clicked()
  3274. {
  3275. int index=functionDialog->functionListBox->currentItem();
  3276. if (index>=0 && sourceFileFunctions[index].prototypeLine>=0) {
  3277. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(
  3278. sourceFileFunctions[index].prototypeLine,0));
  3279. functionDialog->accept();
  3280. }
  3281. }
  3282. void MainForm::findFunctions_implementationButton_clicked()
  3283. {
  3284. int index=functionDialog->functionListBox->currentItem();
  3285. if (index>=0 && sourceFileFunctions[index].implementationLine>=0) {
  3286. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(
  3287. sourceFileFunctions[index].implementationLine,0));
  3288. functionDialog->accept();
  3289. }
  3290. }
  3291. void MainForm::findFunctionsPopup_aboutToShow()
  3292. {
  3293. findFunctionsPopup->clear();
  3294. if (CURRENT_VIEW) {
  3295. CATEGORY_OF(category,currentListItem);
  3296. sourceFileFunctions=getFunctions(CURRENT_VIEW->document()->text(),
  3297. category==asmFilesListItem||category==sFilesListItem);
  3298. int idx=0;
  3299. for (SourceFileFunctions::Iterator it=sourceFileFunctions.begin();
  3300. it!=sourceFileFunctions.end(); ++it,++idx)
  3301. findFunctionsPopup->insertItem((*it).name,idx);
  3302. }
  3303. }
  3304. void MainForm::findFunctionsPopup_aboutToHide()
  3305. {
  3306. QTimer::singleShot(0,this,SLOT(findFunctionsPopup_aboutToHide_async()));
  3307. }
  3308. void MainForm::findFunctionsPopup_aboutToHide_async()
  3309. {
  3310. findFunctionsPopup->clear();
  3311. }
  3312. void MainForm::findFunctionsPopup_activated(int id)
  3313. {
  3314. if (CURRENT_VIEW) {
  3315. int line=sourceFileFunctions[id].implementationLine>=0
  3316. ?sourceFileFunctions[id].implementationLine
  3317. :sourceFileFunctions[id].prototypeLine;
  3318. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(line,0));
  3319. }
  3320. }
  3321. void MainForm::findAndOpenFile(const QString &fileName, void *category)
  3322. {
  3323. // Look for the source file with the given name.
  3324. QString fileNameNoPath=QFileInfo(fileName).fileName();
  3325. bool inProject;
  3326. void *sourceFile;
  3327. if (findSourceFile(inProject,sourceFile,fileNameNoPath)) {
  3328. if (inProject)
  3329. fileTreeClicked(reinterpret_cast<ListViewFile *>(sourceFile));
  3330. else
  3331. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3332. } else {
  3333. // Not found. Try to open it instead.
  3334. // Don't do this if the name ends with ".tpr" because that would cause
  3335. // openProject to close the current project and load the new one instead.
  3336. if (!fileName.endsWith(".tpr",FALSE)) {
  3337. QString fileNameFull=QFileInfo(projectFileName).dir().filePath(fileName);
  3338. if (getPathType(fileNameFull)==PATH_FILE) {
  3339. openProject(fileNameFull);
  3340. if (findSourceFile(inProject,sourceFile,fileNameFull) && !inProject)
  3341. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3342. } else {
  3343. Q3ListViewItem *cat=reinterpret_cast<Q3ListViewItem *>(category);
  3344. QString includeDir=(cat==asmFilesListItem)?"asm":
  3345. (cat==sFilesListItem)?"s":"c";
  3346. fileNameFull=QDir(QString("%1/include/%2/").arg(tigcc_base)
  3347. .arg(includeDir)).filePath(fileName);
  3348. if (getPathType(fileNameFull)==PATH_FILE) {
  3349. openProject(fileNameFull);
  3350. if (findSourceFile(inProject,sourceFile,fileNameFull) && !inProject)
  3351. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3352. } else {
  3353. KMessageBox::error(this,QString("File \'%1\' not found.").arg(fileName),
  3354. "Search Failed");
  3355. }
  3356. }
  3357. }
  3358. }
  3359. }
  3360. void MainForm::findOpenFileAtCursor()
  3361. {
  3362. if (CURRENT_VIEW && IS_FILE(currentListItem)) {
  3363. int line,col,i;
  3364. CURRENT_VIEW->cursorPosition().position(line,col);
  3365. QString textLine=CURRENT_VIEW->document()->line(line);
  3366. int l=textLine.length();
  3367. bool quotesInLine=textLine.contains("\"");
  3368. QString fileName;
  3369. for (i=col;i>=0;i--) {
  3370. QChar c=textLine[i];
  3371. if (!((quotesInLine && c==' ') || (c>='A' && c<='Z') || (c>='a' && c<='z')
  3372. || (c>='0' && c<='9') || QString("_-./\\:").contains(c)))
  3373. break;
  3374. fileName.prepend(c);
  3375. }
  3376. for (i=col+1;i<l;i++) {
  3377. QChar c=textLine[i];
  3378. if (!((quotesInLine && c==' ') || (c>='A' && c<='Z') || (c>='a' && c<='z')
  3379. || (c>='0' && c<='9') || QString("_-./\\:").contains(c)))
  3380. break;
  3381. fileName.append(c);
  3382. }
  3383. CATEGORY_OF(category,currentListItem);
  3384. findAndOpenFile(fileName,category);
  3385. }
  3386. }
  3387. void MainForm::openHeader(const QString &fileName, bool systemHeader,
  3388. int lineno)
  3389. {
  3390. if (systemHeader) {
  3391. // Don't do this if the name ends with ".tpr" because that would cause
  3392. // openProject to close the current project and load the new one instead.
  3393. if (!fileName.endsWith(".tpr",FALSE)) {
  3394. bool inProject;
  3395. void *sourceFile;
  3396. QString fileNameFull=QDir(QString("%1/include/c/").arg(tigcc_base))
  3397. .filePath(fileName);
  3398. if (findSourceFile(inProject,sourceFile,fileNameFull)) {
  3399. if (inProject) {
  3400. fileTreeClicked(reinterpret_cast<ListViewFile *>(sourceFile));
  3401. if (reinterpret_cast<ListViewFile *>(sourceFile)->kateView)
  3402. reinterpret_cast<ListViewFile *>(sourceFile)->kateView->setCursorPosition(KTextEditor::Cursor(lineno,0));
  3403. } else {
  3404. reinterpret_cast<SourceFileWindow *>(sourceFile)->kateView->setCursorPosition(KTextEditor::Cursor(lineno,0));
  3405. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3406. }
  3407. } else {
  3408. if (getPathType(fileNameFull)==PATH_FILE) {
  3409. openProject(fileNameFull);
  3410. if (findSourceFile(inProject,sourceFile,fileNameFull) && !inProject) {
  3411. reinterpret_cast<SourceFileWindow *>(sourceFile)->kateView->setCursorPosition(KTextEditor::Cursor(lineno,0));
  3412. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3413. }
  3414. } else {
  3415. KMessageBox::error(this,QString("File \'%1\' not found.").arg(fileName),
  3416. "Search Failed");
  3417. }
  3418. }
  3419. }
  3420. } else {
  3421. QString name=fileName;
  3422. int pos;
  3423. Q3ListViewItem *item=hFilesListItem;
  3424. while ((pos=name.find('/'))>=0) {
  3425. QString folder=name.left(pos);
  3426. name.remove(0,pos+1);
  3427. for (item=item->firstChild();item;item=item->nextSibling()) {
  3428. if (IS_FOLDER(item)) {
  3429. if (item->text(0)==folder) break;
  3430. }
  3431. }
  3432. if (!item) return;
  3433. }
  3434. for (item=item->firstChild();item;item=item->nextSibling()) {
  3435. if (IS_FILE(item)) {
  3436. ListViewFile *fileItem=static_cast<ListViewFile *>(item);
  3437. if (QFileInfo(fileItem->fileName).fileName()==name) {
  3438. fileTreeClicked(item);
  3439. if (fileItem->kateView)
  3440. fileItem->kateView->setCursorPosition(KTextEditor::Cursor(lineno,0));
  3441. return;
  3442. }
  3443. }
  3444. }
  3445. }
  3446. }
  3447. void MainForm::findFindSymbolDeclaration()
  3448. {
  3449. if (IS_FILE(currentListItem) && CURRENT_VIEW) {
  3450. QString fileText=CURRENT_VIEW->document()->text();
  3451. CATEGORY_OF(category,currentListItem);
  3452. // "Find symbol declaration" only operates on C files.
  3453. if (category==cFilesListItem || category==qllFilesListItem
  3454. || (category==hFilesListItem && !fileText.isEmpty()
  3455. && fileText[0]!='|' && fileText[0]!=';')) {
  3456. QString fileName=pathInProject(currentListItem);
  3457. QString symbolFile;
  3458. unsigned symbolLine;
  3459. bool systemHeader;
  3460. int line,col,i;
  3461. CURRENT_VIEW->cursorPosition().position(line,col);
  3462. QString textLine=CURRENT_VIEW->document()->line(line);
  3463. QString wordUnderCursor;
  3464. for (i=col-1;i>=0;i--) {
  3465. QChar c=textLine[i];
  3466. if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')
  3467. || c=='_' || c=='$' || c=='#')
  3468. wordUnderCursor.prepend(c);
  3469. }
  3470. int len=textLine.length();
  3471. for (i=col;i<len;i++) {
  3472. QChar c=textLine[i];
  3473. if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')
  3474. || c=='_' || c=='$' || c=='#')
  3475. wordUnderCursor.append(c);
  3476. }
  3477. if (findSymbolInFile(wordUnderCursor,fileText,fileName,this,symbolFile,
  3478. symbolLine,systemHeader)
  3479. && !symbolFile.isNull()) {
  3480. if (symbolFile==fileName)
  3481. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(symbolLine,0));
  3482. else
  3483. openHeader(symbolFile,systemHeader,symbolLine);
  3484. }
  3485. }
  3486. }
  3487. }
  3488. //returns 1 on success
  3489. int MainForm::projectAddFiles_oneFile(const QString &fileName)
  3490. {
  3491. Q3ListViewItem *category=othFilesListItem;
  3492. QString suffix,caption;
  3493. int p;
  3494. p=fileName.findRev('/');
  3495. if (p<0) p=-1;
  3496. caption=fileName.mid(p+1);
  3497. p=caption.findRev('.');
  3498. if (p>=0) {
  3499. suffix=caption.mid(p+1);
  3500. caption.truncate(p);
  3501. }
  3502. if (!checkFileName(fileName,extractAllFileNames())) {
  3503. KMessageBox::error(this,QString("The file \'%1\' is already included in the project.").arg(caption));
  3504. return 0;
  3505. }
  3506. if (!suffix.compare("h"))
  3507. category=hFilesListItem;
  3508. else if (!suffix.compare("c"))
  3509. category=cFilesListItem;
  3510. else if (!suffix.compare("s"))
  3511. category=sFilesListItem;
  3512. else if (!suffix.compare("asm"))
  3513. category=asmFilesListItem;
  3514. else if (!suffix.compare("qll"))
  3515. category=qllFilesListItem;
  3516. else if (!suffix.compare("o"))
  3517. category=oFilesListItem;
  3518. else if (!suffix.compare("a"))
  3519. category=aFilesListItem;
  3520. else if (!suffix.compare("txt"))
  3521. category=txtFilesListItem;
  3522. if (category && category==qllFilesListItem && qllFileCount) {
  3523. KMessageBox::error(this,"There may be only one Quill source file in each project.","Quill Error");
  3524. return 0;
  3525. }
  3526. if (!category)
  3527. category=othFilesListItem;
  3528. if (openFile(category,category,caption,fileName))
  3529. return 1;
  3530. return 0;
  3531. }
  3532. void MainForm::projectAddFiles()
  3533. {
  3534. unsigned long i,e;
  3535. int projectChanged=0;
  3536. if (compiling) return;
  3537. QStringList result=SGetFileName_Multiple(findFilter(TIGCCAddFilesFilter),"Add Files",this);
  3538. e=result.count();
  3539. for (i=0;i<e;i++) {
  3540. if (projectAddFiles_oneFile(result[i]))
  3541. projectChanged=TRUE;
  3542. }
  3543. if (projectChanged) {
  3544. projectIsDirty=TRUE;
  3545. projectNeedsRelink=TRUE;
  3546. }
  3547. }
  3548. static bool stopCompilingFlag, errorsCompilingFlag;
  3549. static QString compileStats;
  3550. static QDateTime newestHeaderTimestamp;
  3551. static QStringList objectFiles;
  3552. static QStringList deletableObjectFiles;
  3553. static QStringList deletableAsmFiles;
  3554. static KProcess *process;
  3555. QString MainForm::writeTempSourceFile(void *srcFile, bool inProject)
  3556. {
  3557. const QString *origFileName;
  3558. Q3ListViewItem *category;
  3559. QString fileName;
  3560. QString fileText;
  3561. LineStartList *pLineStartList=0;
  3562. if (inProject) {
  3563. ListViewFile *sourceFile=reinterpret_cast<ListViewFile *>(srcFile);
  3564. origFileName=&(sourceFile->fileName);
  3565. CATEGORY_OF(cat,sourceFile);
  3566. category=cat;
  3567. QString folder;
  3568. Q3ListViewItem *item=sourceFile->parent();
  3569. while (!IS_CATEGORY(item)) {
  3570. folder.prepend('/');
  3571. folder.prepend(item->text(0));
  3572. item=item->parent();
  3573. }
  3574. QString ext;
  3575. // Some categories need fixed extensions.
  3576. if (category==cFilesListItem) {
  3577. ext=".c";
  3578. } else if (category==sFilesListItem) {
  3579. ext=".s";
  3580. } else if (category==asmFilesListItem) {
  3581. ext=".asm";
  3582. } else if (category==qllFilesListItem) {
  3583. ext=".qll";
  3584. } else if (category==oFilesListItem) {
  3585. ext=".o";
  3586. } else if (category==aFilesListItem) {
  3587. ext=".a";
  3588. } else {
  3589. // For others (header files in particular), we need to keep whatever
  3590. // extension the user supplied.
  3591. int dotPos=origFileName->findRev('.');
  3592. int slashPos=origFileName->findRev('/');
  3593. if (dotPos>slashPos) ext=origFileName->mid(dotPos);
  3594. }
  3595. fileName=QString("%1/%2%3%4").arg(tempdir).arg(folder)
  3596. .arg(sourceFile->text(0)).arg(ext);
  3597. if (IS_EDITABLE_CATEGORY(category)) {
  3598. fileText=sourceFile->kateView->document()->text();
  3599. pLineStartList=&(sourceFile->lineStartList);
  3600. } else {
  3601. if (copyFile(origFileName->ascii(),fileName.ascii())) {
  3602. KMessageBox::error(this,"Failed to copy file to temporary directory.");
  3603. stopCompilingFlag=TRUE;
  3604. }
  3605. return fileName;
  3606. }
  3607. } else {
  3608. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  3609. origFileName=&(sourceFile->fileName);
  3610. category=reinterpret_cast<Q3ListViewItem *>(sourceFile->category);
  3611. fileName=QString("%1%2").arg(tempdir)
  3612. .arg(origFileName->mid(origFileName->findRev('/')));
  3613. fileText=sourceFile->kateView->document()->text();
  3614. pLineStartList=&(sourceFile->lineStartList);
  3615. }
  3616. if (saveAndSplitFileText(fileName.ascii(),fileText,(category==cFilesListItem),
  3617. (category==cFilesListItem||category==qllFilesListItem),
  3618. (category==sFilesListItem),*origFileName,pLineStartList)) {
  3619. KMessageBox::error(this,"Failed to write source file to temporary directory.");
  3620. stopCompilingFlag=TRUE;
  3621. }
  3622. return fileName;
  3623. }
  3624. void MainForm::startCompiling()
  3625. {
  3626. if (preferences.autoSave) {
  3627. if (!fileSave()) {
  3628. stopCompilingFlag=TRUE;
  3629. return;
  3630. }
  3631. } else {
  3632. foreach (SourceFileWindow *sourceFile, sourceFiles) sourceFile->fileSave();
  3633. }
  3634. fileNewMenu->menuAction()->setEnabled(FALSE);
  3635. fileNewAction->setEnabled(FALSE);
  3636. fileOpenAction->setEnabled(FALSE);
  3637. fileRecent1Action->setEnabled(FALSE);
  3638. fileRecent2Action->setEnabled(FALSE);
  3639. fileRecent3Action->setEnabled(FALSE);
  3640. fileRecent4Action->setEnabled(FALSE);
  3641. fileExitAction->setEnabled(FALSE);
  3642. projectAddFilesAction->setEnabled(FALSE);
  3643. projectCompileAction->setVisible(FALSE);
  3644. projectMakeAction->setVisible(FALSE);
  3645. projectBuildAction->setVisible(FALSE);
  3646. projectCompileAction->setEnabled(FALSE);
  3647. shortcuts[15]->setEnabled(FALSE);
  3648. projectMakeAction->setEnabled(FALSE);
  3649. shortcuts[16]->setEnabled(FALSE);
  3650. projectBuildAction->setEnabled(FALSE);
  3651. projectStopCompilationAction->setEnabled(TRUE);
  3652. projectForceQuitAction->setEnabled(TRUE);
  3653. projectStopCompilationAction->setVisible(TRUE);
  3654. projectForceQuitAction->setVisible(TRUE);
  3655. debugRunAction->setEnabled(FALSE);
  3656. debugPauseAction->setEnabled(FALSE);
  3657. debugResetAction->setEnabled(FALSE);
  3658. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  3659. sourceFile->fileAddToProjectAction->setEnabled(FALSE);
  3660. sourceFile->fileCompileAction->setEnabled(FALSE);
  3661. }
  3662. compiling=TRUE;
  3663. stopCompilingFlag=FALSE;
  3664. errorsCompilingFlag=FALSE;
  3665. newestHeaderTimestamp=QDateTime();
  3666. objectFiles.clear();
  3667. deletableObjectFiles.clear();
  3668. deletableAsmFiles.clear();
  3669. errorList->errorListView->clear();
  3670. programOutput=QString::null;
  3671. compileStats=QString::null;
  3672. projectProgramOutputAction->setEnabled(FALSE);
  3673. process=static_cast<KProcess *>(NULL);
  3674. // Write all the headers and incbin files to the temporary directory.
  3675. Q3ListViewItemIterator lvit(hFilesListItem);
  3676. Q3ListViewItem *item;
  3677. for (item=(++lvit).current();item&&!IS_CATEGORY(item);
  3678. item=(++lvit).current()) {
  3679. if (IS_FILE(item)) {
  3680. if (static_cast<ListViewFile *>(item)->modifiedSinceLastCompile)
  3681. headersModified=TRUE;
  3682. if (!headersModified) {
  3683. QDateTime headerTimestamp=QFileInfo(static_cast<ListViewFile *>(item)->fileName).lastModified();
  3684. if (!newestHeaderTimestamp.isValid()
  3685. || (headerTimestamp.isValid()
  3686. && headerTimestamp>newestHeaderTimestamp))
  3687. newestHeaderTimestamp=headerTimestamp;
  3688. }
  3689. writeTempSourceFile(static_cast<ListViewFile *>(item),TRUE);
  3690. if (stopCompilingFlag) return;
  3691. }
  3692. }
  3693. lvit=Q3ListViewItemIterator(othFilesListItem);
  3694. for (item=(++lvit).current();item&&!IS_CATEGORY(item);
  3695. item=(++lvit).current()) {
  3696. if (IS_FILE(item)) {
  3697. if (!headersModified) {
  3698. QDateTime headerTimestamp=QFileInfo(static_cast<ListViewFile *>(item)->fileName).lastModified();
  3699. if (!newestHeaderTimestamp.isValid()
  3700. || (headerTimestamp.isValid()
  3701. && headerTimestamp>newestHeaderTimestamp))
  3702. newestHeaderTimestamp=headerTimestamp;
  3703. }
  3704. writeTempSourceFile(static_cast<ListViewFile *>(item),TRUE);
  3705. if (stopCompilingFlag) return;
  3706. }
  3707. }
  3708. }
  3709. void MainForm::stopCompiling()
  3710. {
  3711. clear_temp_dir();
  3712. stopCompilingFlag=FALSE;
  3713. errorsCompilingFlag=FALSE;
  3714. compiling=FALSE;
  3715. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  3716. sourceFile->fileAddToProjectAction->setEnabled(TRUE);
  3717. sourceFile->fileCompileAction->setEnabled(TRUE);
  3718. sourceFile->fileCloseAction->setEnabled(TRUE);
  3719. }
  3720. debugRunAction->setEnabled(TRUE);
  3721. debugPauseAction->setEnabled(preferences.linkTarget==LT_TIEMU);
  3722. debugResetAction->setEnabled(preferences.linkTarget==LT_TIEMU);
  3723. projectStopCompilationAction->setVisible(FALSE);
  3724. projectForceQuitAction->setVisible(FALSE);
  3725. projectStopCompilationAction->setEnabled(FALSE);
  3726. projectForceQuitAction->setEnabled(FALSE);
  3727. projectCompileAction->setEnabled(TRUE);
  3728. shortcuts[15]->setEnabled(TRUE);
  3729. projectMakeAction->setEnabled(TRUE);
  3730. shortcuts[16]->setEnabled(TRUE);
  3731. projectBuildAction->setEnabled(TRUE);
  3732. projectCompileAction->setVisible(TRUE);
  3733. projectMakeAction->setVisible(TRUE);
  3734. projectBuildAction->setVisible(TRUE);
  3735. projectAddFilesAction->setEnabled(TRUE);
  3736. fileExitAction->setEnabled(TRUE);
  3737. fileRecent1Action->setEnabled(TRUE);
  3738. fileRecent2Action->setEnabled(TRUE);
  3739. fileRecent3Action->setEnabled(TRUE);
  3740. fileRecent4Action->setEnabled(TRUE);
  3741. fileOpenAction->setEnabled(TRUE);
  3742. fileNewAction->setEnabled(TRUE);
  3743. fileNewMenu->menuAction()->setEnabled(TRUE);
  3744. statusBar()->clear();
  3745. }
  3746. static QString errorFunction;
  3747. static bool errorFlag;
  3748. static unsigned ldTigccStatPhase=0;
  3749. void MainForm::process_finished()
  3750. {
  3751. // If we're in a modal dialog, let it complete or exiting the event loop will
  3752. // crash.
  3753. if (QCoreApplication::loopLevel()>2) {
  3754. QTimer::singleShot(100,this,SLOT(process_finished()));
  3755. return;
  3756. }
  3757. errorFunction=QString::null;
  3758. ldTigccStatPhase=0;
  3759. QCoreApplication::exit_loop();
  3760. }
  3761. void MainForm::process_readyRead()
  3762. {
  3763. static int a68kErrorLine=0; // A68k errors are split onto several lines.
  3764. static int errorLine, errorColumn;
  3765. static QString errorFile;
  3766. while (process->canReadLine()) {
  3767. QString line=process->readLine();
  3768. line.chop(1); // zap newline
  3769. // ld-tigcc doesn't currently know the difference between host charset and
  3770. // calculator charset, so the variable name won't display properly if it
  3771. // contains non-ASCII characters. Fix that up.
  3772. if (ldTigccStatPhase==1
  3773. && line.trimmed().startsWith("Program Variable Name:",FALSE)) {
  3774. int pos=line.find(':');
  3775. while (line[++pos]==' ');
  3776. line.truncate(pos);
  3777. if (!rootListItem->text(0).contains('\\')) line.append("main\\");
  3778. line.append(rootListItem->text(0));
  3779. }
  3780. programOutput.append(line);
  3781. programOutput.append('\n');
  3782. projectProgramOutputAction->setEnabled(TRUE);
  3783. if (line.isEmpty()) continue;
  3784. // Parse the error message
  3785. switch (ldTigccStatPhase) {
  3786. default: // should not happen
  3787. ldTigccStatPhase=0;
  3788. case 0:
  3789. switch (a68kErrorLine) {
  3790. default: // should not happen
  3791. a68kErrorLine=0;
  3792. case 0:
  3793. errorLine=-1;
  3794. errorColumn=-1;
  3795. errorFile=QString::null;
  3796. case 1:
  3797. if (line.contains(QRegExp(" line [0-9]+$",FALSE))) {
  3798. if (line.contains("(user macro)",FALSE))
  3799. errorColumn=0;
  3800. else if (errorFile.isEmpty()) {
  3801. errorFile=QFileInfo(line.left(line.findRev(" line ",-1,FALSE)))
  3802. .fileName();
  3803. errorLine=line.mid(line.findRev(' ')+1).toInt()-1;
  3804. }
  3805. errorFunction=QString::null;
  3806. a68kErrorLine=1;
  3807. } else if (a68kErrorLine==1) {
  3808. // This line contains only a copy of the source line, skip it.
  3809. a68kErrorLine=2;
  3810. } else {
  3811. if (line.contains("Fatal errors - assembly aborted",FALSE)) break;
  3812. // Not an A68k error, so parse it as a standard *nix-style error.
  3813. // Normalize characters and strip whitespace
  3814. line=line.trimmed();
  3815. line.replace('`','\''); // backtick
  3816. line.replace(QChar(0xb4),'\''); // forward apostrophe
  3817. line.replace('\"','\''); // quote
  3818. if (line.contains("assembler messages:",FALSE)
  3819. || line.startsWith("from ",FALSE)
  3820. || (!preferences.allowImplicitDeclaration
  3821. && (line.contains("previous implicit declaration",FALSE)
  3822. || line.contains("previously implicitly declared",FALSE))))
  3823. break;
  3824. // ld-tigcc statistics start here, don't display them as errors.
  3825. if (line.toLower()=="target calculators:") {
  3826. ldTigccStatPhase=1;
  3827. break;
  3828. }
  3829. if (line.startsWith("in file",FALSE))
  3830. errorFunction=QString::null;
  3831. else {
  3832. // The regex also supports Windows file names, in case KTIGCC ever
  3833. // encounters them. Hopefully nobody will try giving it MacOS <=9
  3834. // file names.
  3835. int pos=line.find(QRegExp(":(?![/\\\\])"));
  3836. if (pos>=0) errorFile=line.left(pos);
  3837. if (errorFile.isEmpty()) {
  3838. if (!line.endsWith("."))
  3839. line.append('.');
  3840. errorFlag=TRUE;
  3841. new ErrorListItem(this,line.startsWith("please fill out ",FALSE)?
  3842. etInfo:etError,QString::null,QString::null,line,
  3843. errorLine,errorColumn);
  3844. } else {
  3845. QString errorMessage;
  3846. if (errorFile.toLower()=="error"||errorFile.toLower()=="warning") {
  3847. errorFile=QString::null;
  3848. errorMessage=line;
  3849. } else {
  3850. errorFile=QFileInfo(errorFile).fileName();
  3851. errorMessage=line.mid(pos+1);
  3852. }
  3853. if (!errorMessage.isEmpty() && errorMessage[0]>='0'
  3854. && errorMessage[0]<='9') {
  3855. pos=errorMessage.find(':');
  3856. if (pos>=0) {
  3857. bool ok;
  3858. errorLine=errorMessage.left(pos).toInt(&ok)-1;
  3859. if (ok) {
  3860. errorMessage.remove(0,pos+1);
  3861. if (!errorMessage.isEmpty() && errorMessage[0]>='0'
  3862. && errorMessage[0]<='9') {
  3863. pos=errorMessage.find(':');
  3864. if (pos>=0) {
  3865. errorColumn=errorMessage.left(pos).toInt(&ok)-1;
  3866. if (ok) errorMessage.remove(0,pos+1);
  3867. }
  3868. }
  3869. }
  3870. }
  3871. errorMessage=errorMessage.trimmed();
  3872. ErrorTypes errorType=etError;
  3873. if (errorMessage.startsWith("warning:",FALSE)) {
  3874. errorMessage.remove(0,8);
  3875. errorMessage=errorMessage.trimmed();
  3876. errorType=etWarning;
  3877. } else if (errorMessage.startsWith("error:",FALSE)) {
  3878. errorMessage.remove(0,6);
  3879. errorMessage=errorMessage.trimmed();
  3880. }
  3881. if (errorMessage.startsWith("#warning ",FALSE)) {
  3882. errorMessage.remove(0,9);
  3883. errorType=etWarning;
  3884. } else if (errorMessage.startsWith("#error ",FALSE))
  3885. errorMessage.remove(0,7);
  3886. if (errorMessage.startsWith("previous declaration of ",FALSE)
  3887. || errorMessage.startsWith("possible real start of ",FALSE)
  3888. || errorMessage.startsWith("unused variable ",FALSE)
  3889. || errorMessage.startsWith("unused parameter ",FALSE)
  3890. || errorMessage.contains("previously declared here",FALSE)
  3891. || errorMessage.contains("location of the previous definition",FALSE))
  3892. errorType=etInfo;
  3893. if (!preferences.allowImplicitDeclaration)
  3894. errorMessage.replace(QRegExp("^implicit declaration of ",FALSE),
  3895. "Undefined reference to ");
  3896. if (!errorMessage.endsWith("."))
  3897. errorMessage.append('.');
  3898. if (errorType==etError) errorFlag=TRUE;
  3899. new ErrorListItem(this,errorType,errorFile,errorFunction,
  3900. errorMessage,errorLine,errorColumn);
  3901. } else {
  3902. if (errorMessage.startsWith(" in function \'",FALSE)
  3903. && errorMessage.count('\'')>1) {
  3904. errorFunction=errorMessage.mid(14,errorMessage.find('\'',14)-14);
  3905. } else if (errorMessage.startsWith(" at top level",FALSE)) {
  3906. errorFunction=QString::null;
  3907. } else {
  3908. ErrorTypes errorType=etError;
  3909. if (errorMessage.startsWith("warning:",FALSE)) {
  3910. errorMessage.remove(0,8);
  3911. errorMessage=errorMessage.trimmed();
  3912. errorType=etWarning;
  3913. } else if (errorMessage.startsWith("error:",FALSE)) {
  3914. errorMessage.remove(0,6);
  3915. errorMessage=errorMessage.trimmed();
  3916. }
  3917. if (!errorMessage.endsWith("."))
  3918. errorMessage.append('.');
  3919. if (errorType==etError) errorFlag=TRUE;
  3920. new ErrorListItem(this,errorType,errorFile,QString::null,
  3921. errorMessage,errorLine,errorColumn);
  3922. }
  3923. }
  3924. }
  3925. }
  3926. }
  3927. break;
  3928. case 2:
  3929. if (line.contains(QRegExp("^\\s*\\^"))) {
  3930. int caretPos=line.find('^');
  3931. if (errorLine>=0 && errorColumn<0)
  3932. errorColumn=caretPos-1; // there's an extra tab at the beginning
  3933. QString errorMessage=line.mid(caretPos+2);
  3934. if (!errorMessage.endsWith("."))
  3935. errorMessage.append('.');
  3936. errorFlag=TRUE;
  3937. new ErrorListItem(this,etError,errorFile,QString::null,errorMessage,
  3938. errorLine,errorColumn);
  3939. }
  3940. a68kErrorLine=0;
  3941. break;
  3942. }
  3943. break;
  3944. case 1:
  3945. line=line.trimmed();
  3946. // The next line is the first one to display in the dialog. (TIGCC IDE
  3947. // does the same.)
  3948. if (line.startsWith("Program Variable Name:",FALSE))
  3949. ldTigccStatPhase=2;
  3950. break;
  3951. case 2:
  3952. compileStats.append(line.simplified());
  3953. compileStats.append('\n');
  3954. break;
  3955. }
  3956. }
  3957. if (errorFlag) {
  3958. errorsCompilingFlag=TRUE;
  3959. if (preferences.stopAtFirstError) stopCompilingFlag=TRUE;
  3960. }
  3961. }
  3962. void MainForm::process_readyRead_recordOnly()
  3963. {
  3964. QString line;
  3965. while (process->canReadLine()) {
  3966. programOutput.append(process->readLine());
  3967. projectProgramOutputAction->setEnabled(TRUE);
  3968. }
  3969. }
  3970. void MainForm::compileFile(void *srcFile, bool inProject, bool force)
  3971. {
  3972. Q3ListViewItem *category;
  3973. const QString *origFileName;
  3974. bool modified=FALSE;
  3975. QString shortFileName;
  3976. if (stopCompilingFlag) return;
  3977. errorFlag=FALSE;
  3978. if (inProject) {
  3979. ListViewFile *sourceFile=reinterpret_cast<ListViewFile *>(srcFile);
  3980. CATEGORY_OF(cat,sourceFile);
  3981. category=cat;
  3982. origFileName=&(sourceFile->fileName);
  3983. if (sourceFile->modifiedSinceLastCompile)
  3984. modified=TRUE;
  3985. shortFileName=sourceFile->text(0);
  3986. } else {
  3987. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  3988. category=reinterpret_cast<Q3ListViewItem *>(sourceFile->category);
  3989. origFileName=&(sourceFile->fileName);
  3990. if (sourceFile->kateView->document()->isModified())
  3991. modified=TRUE;
  3992. shortFileName=sourceFile->fileName;
  3993. }
  3994. if (category==cFilesListItem || category==sFilesListItem
  3995. || category==asmFilesListItem || category==qllFilesListItem) {
  3996. QString objectFile=*origFileName;
  3997. int dotPos=origFileName->findRev('.');
  3998. int slashPos=origFileName->findRev('/');
  3999. if (dotPos>slashPos) objectFile.truncate(dotPos);
  4000. // Compute correct file names for unsaved files.
  4001. if (!objectFile.isEmpty() && objectFile[0]!='/') {
  4002. if (inProject) {
  4003. ListViewFile *sourceFile=reinterpret_cast<ListViewFile *>(srcFile);
  4004. Q3ListViewItem *item=sourceFile->parent();
  4005. while (!IS_CATEGORY(item)) {
  4006. objectFile.prepend('/');
  4007. objectFile.prepend(item->text(0));
  4008. item=item->parent();
  4009. }
  4010. }
  4011. if (!projectFileName.isEmpty()) {
  4012. objectFile.prepend('/');
  4013. objectFile.prepend(QFileInfo(projectFileName).absolutePath());
  4014. }
  4015. }
  4016. QString asmFile=objectFile;
  4017. objectFile.append(".o");
  4018. deletableObjectFiles.append(objectFile);
  4019. objectFiles.append(objectFile);
  4020. asmFile.append(".s");
  4021. mkdir_multi(objectFile);
  4022. if (category==cFilesListItem || category==qllFilesListItem)
  4023. deletableAsmFiles.append(asmFile);
  4024. // Figure out whether to recompile the file.
  4025. if (!force && !modified && !headersModified) {
  4026. QFileInfo objectFileInfo(objectFile);
  4027. if (objectFileInfo.exists()) {
  4028. QDateTime timestamp=objectFileInfo.lastModified();
  4029. if (timestamp.isValid() && (!newestHeaderTimestamp.isValid()
  4030. || timestamp>=newestHeaderTimestamp)) {
  4031. QDateTime sourceTimestamp=QFileInfo(*origFileName).lastModified();
  4032. if (sourceTimestamp.isValid() && timestamp>=sourceTimestamp) {
  4033. return;
  4034. }
  4035. }
  4036. }
  4037. }
  4038. if (category==sFilesListItem||category==asmFilesListItem)
  4039. statusBar()->message(QString("Assembling File \'%1\'...").arg(shortFileName));
  4040. else
  4041. statusBar()->message(QString("Compiling File \'%1\'...").arg(shortFileName));
  4042. projectNeedsRelink=TRUE;
  4043. QString fileName=writeTempSourceFile(srcFile,inProject);
  4044. if (stopCompilingFlag) return;
  4045. QString tempObjectFile=fileName;
  4046. dotPos=fileName.findRev('.');
  4047. slashPos=fileName.findRev('/');
  4048. if (dotPos>slashPos) tempObjectFile.truncate(dotPos);
  4049. QString tempAsmFile=tempObjectFile;
  4050. tempObjectFile.append(".o");
  4051. tempAsmFile.append(".s");
  4052. QString fileDir=QFileInfo(fileName).absolutePath();
  4053. QDir qdir;
  4054. if (category==asmFilesListItem) {
  4055. // Assemble A68k file
  4056. KShell::Errors err;
  4057. QStringList args=KShell::splitArgs(settings.a68k_switches,
  4058. KShell::TildeExpand|KShell::AbortOnMeta,
  4059. &err);
  4060. if (err) {
  4061. new ErrorListItem(this,etError,QString::null,QString::null,
  4062. "Invalid A68k assembler command line options.",-1,-1);
  4063. stopCompilingFlag=TRUE;
  4064. }
  4065. if (!stopCompilingFlag) {
  4066. process=new KProcess();
  4067. process->setOutputChannelMode(KProcess::MergedChannels);
  4068. process->setWorkingDirectory(fileDir);
  4069. *process<<(QString("%1/bin/a68k").arg(tigcc_base))
  4070. <<fileName<<(QString("-o%1").arg(tempObjectFile))
  4071. <<(QString("-i%1/include/asm/").arg(tigcc_base))<<"-q"<<args;
  4072. if (settings.cut_ranges||settings.archive)
  4073. *process<<"-a"; // all relocs
  4074. if (settings.optimize_returns||settings.archive)
  4075. *process<<"-d"; // keep locals
  4076. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4077. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4078. process->start();
  4079. // We need to block here, but events still need to be handled. The most
  4080. // effective way to do this is to enter the event loop recursively,
  4081. // even though it is not recommended by Qt.
  4082. QCoreApplication::enter_loop();
  4083. // This will be reached only after exitLoop() is called.
  4084. delete process;
  4085. process=static_cast<KProcess *>(NULL);
  4086. }
  4087. } else {
  4088. bool deleteTempAsmFile=FALSE;
  4089. QString fileNameToAssemble;
  4090. if (category==sFilesListItem) {
  4091. fileNameToAssemble=fileName;
  4092. } else /* C or Quill */ {
  4093. // Compile C/Quill file to assembly
  4094. KShell::Errors err;
  4095. QStringList args=KShell::splitArgs(settings.cc_switches,
  4096. KShell::TildeExpand|KShell::AbortOnMeta,
  4097. &err);
  4098. if (err) {
  4099. new ErrorListItem(this,etError,QString::null,QString::null,
  4100. "Invalid C compiler command line options.",-1,-1);
  4101. stopCompilingFlag=TRUE;
  4102. }
  4103. if (!stopCompilingFlag) {
  4104. process=new KProcess();
  4105. process->setOutputChannelMode(KProcess::MergedChannels);
  4106. process->setWorkingDirectory(fileDir);
  4107. *process<<(QString("%1/bin/gcc").arg(tigcc_base))
  4108. <<"-S"<<"-I"<<fileDir
  4109. <<"-B"<<(QString("%1/bin/").arg(tigcc_base))<<"-I-"
  4110. <<"-I"<<(QString("%1/include/c").arg(tigcc_base))<<args;
  4111. if (category==qllFilesListItem) { // Quill needs special switches.
  4112. *process<<"-I"<<(QString("%1/include/quill").arg(tigcc_base))
  4113. <<"-include"<<quill_drv;
  4114. }
  4115. if (settings.use_data_var)
  4116. *process<<"-mno-merge-sections";
  4117. if (!preferences.allowImplicitDeclaration)
  4118. *process<<"-Werror-implicit-function-declaration";
  4119. if (settings.debug_info)
  4120. *process<<"-gdwarf-2"<<"-g3"<<"-fasynchronous-unwind-tables";
  4121. if (settings.fargo)
  4122. *process<<"-DFARGO";
  4123. else if (settings.flash_os)
  4124. *process<<"-DFLASH_OS";
  4125. else if (!settings.archive) { // This leaves only regular programs.
  4126. *process<<process_libopts();
  4127. }
  4128. *process<<fileName<<"-o"<<tempAsmFile;
  4129. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4130. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4131. process->start();
  4132. // We need to block here, but events still need to be handled. The most
  4133. // effective way to do this is to enter the event loop recursively,
  4134. // even though it is not recommended by Qt.
  4135. QCoreApplication::enter_loop();
  4136. // This will be reached only after exitLoop() is called.
  4137. delete process;
  4138. process=static_cast<KProcess *>(NULL);
  4139. }
  4140. if (!stopCompilingFlag && qdir.exists(tempAsmFile)) {
  4141. // Run patcher.
  4142. process=new KProcess();
  4143. process->setOutputChannelMode(KProcess::MergedChannels);
  4144. process->setWorkingDirectory(fileDir);
  4145. *process<<(QString("%1/bin/patcher").arg(tigcc_base))
  4146. <<tempAsmFile<<"-o"<<tempAsmFile;
  4147. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4148. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4149. process->start();
  4150. // We need to block here, but events still need to be handled. The most
  4151. // effective way to do this is to enter the event loop recursively,
  4152. // even though it is not recommended by Qt.
  4153. QCoreApplication::enter_loop();
  4154. // This will be reached only after exitLoop() is called.
  4155. delete process;
  4156. process=static_cast<KProcess *>(NULL);
  4157. }
  4158. if (qdir.exists(tempAsmFile)) {
  4159. if (!stopCompilingFlag) {
  4160. fileNameToAssemble=tempAsmFile;
  4161. qdir.remove(asmFile);
  4162. if (copyFile(tempAsmFile.ascii(),asmFile.ascii())) {
  4163. new ErrorListItem(this,etError,QString::null,QString::null,
  4164. "Failed to copy assembly file from temporary directory.",
  4165. -1,-1);
  4166. stopCompilingFlag=TRUE;
  4167. }
  4168. }
  4169. deleteTempAsmFile=TRUE;
  4170. } else {
  4171. errorFlag=TRUE;
  4172. errorsCompilingFlag=TRUE;
  4173. if (preferences.stopAtFirstError) stopCompilingFlag=TRUE;
  4174. }
  4175. }
  4176. // Assemble GNU as file
  4177. if (!stopCompilingFlag && !fileNameToAssemble.isNull()) {
  4178. KShell::Errors err;
  4179. QStringList args=KShell::splitArgs(settings.as_switches,
  4180. KShell::TildeExpand|KShell::AbortOnMeta,
  4181. &err);
  4182. if (err) {
  4183. new ErrorListItem(this,etError,QString::null,QString::null,
  4184. "Invalid GNU assembler command line options.",-1,-1);
  4185. stopCompilingFlag=TRUE;
  4186. }
  4187. if (!stopCompilingFlag) {
  4188. process=new KProcess();
  4189. process->setOutputChannelMode(KProcess::MergedChannels);
  4190. process->setWorkingDirectory(fileDir);
  4191. *process<<(QString("%1/bin/as").arg(tigcc_base))
  4192. <<"-I"<<fileDir<<"-mc68000"
  4193. <<"-I"<<(QString("%1/include/s").arg(tigcc_base))<<args;
  4194. if (settings.cut_ranges||settings.archive)
  4195. *process<<"--all-relocs";
  4196. if (settings.optimize_returns||settings.archive)
  4197. *process<<"--keep-locals";
  4198. if (settings.debug_info)
  4199. *process<<"--gdwarf2";
  4200. *process<<fileNameToAssemble<<"-o"<<tempObjectFile;
  4201. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4202. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4203. process->start();
  4204. // We need to block here, but events still need to be handled. The most
  4205. // effective way to do this is to enter the event loop recursively,
  4206. // even though it is not recommended by Qt.
  4207. QCoreApplication::enter_loop();
  4208. // This will be reached only after exitLoop() is called.
  4209. delete process;
  4210. process=static_cast<KProcess *>(NULL);
  4211. }
  4212. }
  4213. if (deleteTempAsmFile) qdir.remove(tempAsmFile);
  4214. }
  4215. qdir.remove(fileName);
  4216. if (qdir.exists(tempObjectFile)) {
  4217. qdir.remove(objectFile);
  4218. if (copyFile(tempObjectFile.ascii(),objectFile.ascii())) {
  4219. new ErrorListItem(this,etError,QString::null,QString::null,
  4220. "Failed to copy object file from temporary directory.",
  4221. -1,-1);
  4222. stopCompilingFlag=TRUE;
  4223. }
  4224. qdir.remove(tempObjectFile);
  4225. } else {
  4226. errorFlag=TRUE;
  4227. errorsCompilingFlag=TRUE;
  4228. if (preferences.stopAtFirstError) stopCompilingFlag=TRUE;
  4229. }
  4230. } else if (category==oFilesListItem || category==aFilesListItem) {
  4231. objectFiles.append(*origFileName);
  4232. } // else do nothing (ignore all other categories)
  4233. if (inProject && !errorFlag && !stopCompilingFlag)
  4234. reinterpret_cast<ListViewFile *>(srcFile)->modifiedSinceLastCompile=FALSE;
  4235. }
  4236. void MainForm::compileProject(bool forceAll)
  4237. {
  4238. Q3ListViewItemIterator lvit(fileTree);
  4239. Q3ListViewItem *item;
  4240. for (item=lvit.current(); item&&!stopCompilingFlag; item=(++lvit).current()) {
  4241. if (IS_FILE(item))
  4242. compileFile(static_cast<ListViewFile *>(item),TRUE,forceAll);
  4243. }
  4244. if (!errorsCompilingFlag && !stopCompilingFlag) headersModified=FALSE;
  4245. }
  4246. void MainForm::linkProject()
  4247. {
  4248. errorFlag=FALSE;
  4249. QString projectBaseName=projectFileName;
  4250. if (projectBaseName.endsWith(".tpr",FALSE))
  4251. projectBaseName.truncate(projectBaseName.length()-4);
  4252. QString projectDir=QFileInfo(projectFileName).absolutePath();
  4253. statusBar()->message(QString("Linking Project \'%1\'...")
  4254. .arg(QFileInfo(projectFileName).baseName()));
  4255. if (settings.archive) {
  4256. // Link static library using ar-tigcc.
  4257. process=new KProcess();
  4258. process->setOutputChannelMode(KProcess::MergedChannels);
  4259. process->setWorkingDirectory(projectDir);
  4260. *process<<(QString("%1/bin/ar-tigcc").arg(tigcc_base))
  4261. <<"-o"<<(projectBaseName+".a")<<"--no-names"<<objectFiles;
  4262. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4263. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4264. process->start();
  4265. // We need to block here, but events still need to be handled. The most
  4266. // effective way to do this is to enter the event loop recursively,
  4267. // even though it is not recommended by Qt.
  4268. QCoreApplication::enter_loop();
  4269. // This will be reached only after exitLoop() is called.
  4270. delete process;
  4271. process=static_cast<KProcess *>(NULL);
  4272. if (errorsCompilingFlag || stopCompilingFlag) return;
  4273. QFileInfo fileInfo(projectBaseName+".a");
  4274. if (fileInfo.exists())
  4275. compileStats=QString("Archive Size: %1 Bytes\n").arg(fileInfo.size());
  4276. else
  4277. errorsCompilingFlag=TRUE;
  4278. } else {
  4279. // Link executable using ld-tigcc.
  4280. QByteArray packName;
  4281. QString pstarterName; // urlencoded
  4282. QStringList linkerOptions=process_settings(rootListItem->text(0),
  4283. projectBaseName,
  4284. pstarterName,packName);
  4285. process=new KProcess();
  4286. process->setOutputChannelMode(KProcess::MergedChannels);
  4287. process->setWorkingDirectory(projectDir);
  4288. *process<<(QString("%1/bin/ld-tigcc").arg(tigcc_base))
  4289. <<"-v"<<linkerOptions<<objectFiles;
  4290. if (settings.std_lib)
  4291. *process<<QString(settings.flash_os?"%1/lib/flashos.a"
  4292. :(settings.fargo?"%1/lib/fargo.a"
  4293. :"%1/lib/tigcc.a"))
  4294. .arg(tigcc_base);
  4295. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4296. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4297. process->start();
  4298. // We need to block here, but events still need to be handled. The most
  4299. // effective way to do this is to enter the event loop recursively,
  4300. // even though it is not recommended by Qt.
  4301. QCoreApplication::enter_loop();
  4302. // This will be reached only after exitLoop() is called.
  4303. delete process;
  4304. process=static_cast<KProcess *>(NULL);
  4305. if (errorsCompilingFlag || stopCompilingFlag) return;
  4306. if (settings.pack) {
  4307. if (errorsCompilingFlag || stopCompilingFlag) return;
  4308. statusBar()->message("Creating launcher...");
  4309. const int numTargets=3;
  4310. static const char binexts[numTargets][5]={".z89",".z9x",".zv2"};
  4311. static const char exts[numTargets][5]={".89z",".9xz",".v2z"};
  4312. static const char cbinexts[numTargets][5]={".y89",".y9x",".yv2"};
  4313. static const char cexts[numTargets][5]={".89y",".9xy",".v2y"};
  4314. bool targeted[numTargets];
  4315. for (int target=0; target<numTargets; target++) {
  4316. targeted[target]=QFileInfo(projectBaseName
  4317. +(settings.outputbin?cbinexts[target]:cexts[target])).exists();
  4318. }
  4319. // Prepare the pstarter.
  4320. QString pstarterBaseName=QString("%1/pstarter").arg(tempdir);
  4321. if (insertName(QString("%1/lib/pstarter.o").arg(tigcc_base),
  4322. pstarterBaseName+".o",packName)) {
  4323. new ErrorListItem(this,etError,QString::null,QString::null,
  4324. "Failed to copy pstarter.o to temporary directory.",
  4325. -1,-1);
  4326. errorsCompilingFlag=TRUE;
  4327. }
  4328. if (errorsCompilingFlag || stopCompilingFlag) return;
  4329. // Link the pstarter with ld-tigcc.
  4330. process=new KProcess();
  4331. process->setOutputChannelMode(KProcess::MergedChannels);
  4332. process->setWorkingDirectory(projectDir);
  4333. *process<<(QString("%1/bin/ld-tigcc").arg(tigcc_base))
  4334. <<"-o"<<pstarterBaseName<<"-n"<<pstarterName
  4335. <<(pstarterBaseName+".o");
  4336. if (settings.outputbin) *process<<"--outputbin";
  4337. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4338. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4339. process->start();
  4340. // We need to block here, but events still need to be handled. The most
  4341. // effective way to do this is to enter the event loop recursively,
  4342. // even though it is not recommended by Qt.
  4343. QCoreApplication::enter_loop();
  4344. // This will be reached only after exitLoop() is called.
  4345. delete process;
  4346. process=static_cast<KProcess *>(NULL);
  4347. if (errorsCompilingFlag || stopCompilingFlag) return;
  4348. // Now copy those pstarters actually requested.
  4349. for (int target=0; target<numTargets; target++) {
  4350. if (targeted[target]) {
  4351. if (copyFile(pstarterBaseName+(settings.outputbin?binexts[target]:exts[target]),
  4352. projectBaseName+(settings.outputbin?binexts[target]:exts[target]))) {
  4353. new ErrorListItem(this,etError,QString::null,QString::null,
  4354. "Failed to copy pstarter from temporary directory.",
  4355. -1,-1);
  4356. errorsCompilingFlag=TRUE;
  4357. }
  4358. if (errorsCompilingFlag || stopCompilingFlag) return;
  4359. }
  4360. }
  4361. // Remove any leftover "-titanium" launchers if the TI-89 is targeted.
  4362. if (*targeted) {
  4363. QDir qdir;
  4364. qdir.remove(projectBaseName+"-titanium.89z");
  4365. qdir.remove(projectBaseName+"-Titanium.89z");
  4366. }
  4367. }
  4368. }
  4369. if (errorsCompilingFlag || stopCompilingFlag) return;
  4370. if (!settings.post_build.isEmpty()) {
  4371. // Post-build processing.
  4372. statusBar()->message("Calling User-Defined Program...");
  4373. QString postBuild=settings.post_build;
  4374. // Remove double quotes for TIGCC IDE compatibility. Single quotes will be
  4375. // added instead.
  4376. postBuild.replace("\"($TI89FILE)\"","($TI89FILE)",FALSE);
  4377. postBuild.replace("\"($TI89TIFILE)\"","($TI89TIFILE)",FALSE);
  4378. postBuild.replace("\"($TI92PLUSFILE)\"","($TI92PLUSFILE)",FALSE);
  4379. postBuild.replace("\"($V200FILE)\"","($V200FILE)",FALSE);
  4380. postBuild.replace("\"($TI92FILE)\"","($TI92FILE)",FALSE);
  4381. postBuild.replace("($TI89FILE)",
  4382. KShell::quoteArg(libopts.use_ti89?projectBaseName+(
  4383. settings.archive?".a":settings.flash_os?"-89.tib":
  4384. settings.pack?(settings.outputbin?".y89":".89y"):
  4385. settings.outputbin?".z89":".89z"
  4386. ):""),FALSE);
  4387. postBuild.replace("($TI89TIFILE)",
  4388. KShell::quoteArg(libopts.use_ti89?projectBaseName+(
  4389. settings.archive?".a":settings.flash_os?"-89ti.tib":
  4390. settings.pack?(settings.outputbin?".y89":".89y"):
  4391. settings.outputbin?".z89":".89z"
  4392. ):""),FALSE);
  4393. postBuild.replace("($TI92PLUSFILE)",
  4394. KShell::quoteArg(libopts.use_ti92p?projectBaseName+(
  4395. settings.archive?".a":settings.flash_os?"-9x.tib":
  4396. settings.pack?(settings.outputbin?".y9x":".9xy"):
  4397. settings.outputbin?".z9x":".9xz"
  4398. ):""),FALSE);
  4399. postBuild.replace("($V200FILE)",
  4400. KShell::quoteArg(libopts.use_v200?projectBaseName+(
  4401. settings.archive?".a":settings.flash_os?"-v2.tib":
  4402. settings.pack?(settings.outputbin?".yv2":".v2y"):
  4403. settings.outputbin?".zv2":".v2z"
  4404. ):""),FALSE);
  4405. postBuild.replace("($TI92FILE)",
  4406. KShell::quoteArg(settings.fargo?projectBaseName+(
  4407. settings.outputbin?".p92":".92p"
  4408. ):""),FALSE);
  4409. KShell::Errors err;
  4410. QStringList args=KShell::splitArgs(postBuild,
  4411. KShell::TildeExpand|KShell::AbortOnMeta,
  4412. &err);
  4413. if (err) {
  4414. new ErrorListItem(this,etError,QString::null,QString::null,
  4415. "Invalid post-build command line.",-1,-1);
  4416. errorsCompilingFlag=TRUE;
  4417. }
  4418. if (errorsCompilingFlag || stopCompilingFlag) return;
  4419. process=new KProcess();
  4420. process->setOutputChannelMode(KProcess::MergedChannels);
  4421. process->setWorkingDirectory(projectDir);
  4422. *process<<args;
  4423. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4424. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead_recordOnly()));
  4425. process->start();
  4426. // We need to block here, but events still need to be handled. The most
  4427. // effective way to do this is to enter the event loop recursively,
  4428. // even though it is not recommended by Qt.
  4429. QCoreApplication::enter_loop();
  4430. // This will be reached only after exitLoop() is called.
  4431. delete process;
  4432. process=static_cast<KProcess *>(NULL);
  4433. if (errorsCompilingFlag || stopCompilingFlag) return;
  4434. }
  4435. // Delete object and/or assembly files.
  4436. QDir qdir;
  4437. if (preferences.deleteObjFiles) {
  4438. for (QStringList::Iterator it=deletableObjectFiles.begin();
  4439. it!=deletableObjectFiles.end(); ++it) {
  4440. qdir.remove(*it);
  4441. }
  4442. }
  4443. if (preferences.deleteAsmFiles) {
  4444. for (QStringList::Iterator it=deletableAsmFiles.begin();
  4445. it!=deletableAsmFiles.end(); ++it) {
  4446. qdir.remove(*it);
  4447. }
  4448. }
  4449. projectNeedsRelink=FALSE;
  4450. }
  4451. void MainForm::showStats()
  4452. {
  4453. // KMessageBox also takes plain text, but it interprets \n as paragraph breaks
  4454. // and always renders them as \n\n, no matter whether there is actually just
  4455. // one, two or more than two \n characters. Thus the
  4456. // Qt::convertFromPlainText. Sadly, that replaces the spaces with character
  4457. // #160 (&nbsp;) which doesn't display properly in KMessageBox, so fix it up.
  4458. if (KMessageBox::questionYesNo(this,Qt::convertFromPlainText(
  4459. QString("The project has been compiled successfully.\n\n%1\n"
  4460. "Do you want to open the project folder?").arg(compileStats))
  4461. .replace(QChar(160)," "),
  4462. "Compilation Successful")==KMessageBox::Yes) {
  4463. KUrl projectDir(projectFileName);
  4464. projectDir.setFileName("");
  4465. KRun::runUrl(projectDir,"inode/directory",this);
  4466. }
  4467. }
  4468. void MainForm::projectCompile()
  4469. {
  4470. if (compiling) return;
  4471. startCompiling();
  4472. compileProject(FALSE);
  4473. stopCompiling();
  4474. }
  4475. void MainForm::projectMake()
  4476. {
  4477. if (compiling) return;
  4478. // Can't link a project without saving it first.
  4479. if (projectFileName.isEmpty()) {
  4480. if (!fileSave() || projectFileName.isEmpty()) return;
  4481. }
  4482. startCompiling();
  4483. compileProject(FALSE);
  4484. if (!errorsCompilingFlag && !stopCompilingFlag) linkProject();
  4485. bool success=(!errorsCompilingFlag && !stopCompilingFlag);
  4486. stopCompiling();
  4487. if (success && preferences.successMessage)
  4488. showStats();
  4489. }
  4490. void MainForm::projectBuild()
  4491. {
  4492. if (compiling) return;
  4493. // Can't link a project without saving it first.
  4494. if (projectFileName.isEmpty()) {
  4495. if (!fileSave() || projectFileName.isEmpty()) return;
  4496. }
  4497. startCompiling();
  4498. compileProject(TRUE);
  4499. if (!errorsCompilingFlag && !stopCompilingFlag) linkProject();
  4500. bool success=(!errorsCompilingFlag && !stopCompilingFlag);
  4501. stopCompiling();
  4502. if (success && preferences.successMessage)
  4503. showStats();
  4504. }
  4505. void MainForm::compileSourceFile(void *srcFile)
  4506. {
  4507. if (compiling) return;
  4508. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  4509. sourceFile->fileCloseAction->setEnabled(FALSE);
  4510. startCompiling();
  4511. compileFile(sourceFile,FALSE,TRUE);
  4512. stopCompiling();
  4513. }
  4514. void MainForm::projectStopCompilation()
  4515. {
  4516. if (!compiling) return;
  4517. stopCompilingFlag=TRUE;
  4518. projectStopCompilationAction->setEnabled(FALSE);
  4519. }
  4520. void MainForm::projectForceQuit()
  4521. {
  4522. if (!compiling) return;
  4523. stopCompilingFlag=TRUE;
  4524. if (process && process->state()!=QProcess::NotRunning) {
  4525. process->terminate();
  4526. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,100);
  4527. if (process && process->state()!=QProcess::NotRunning)
  4528. process->kill();
  4529. }
  4530. }
  4531. void MainForm::projectErrorsAndWarnings(bool on)
  4532. {
  4533. static bool lock=FALSE;
  4534. if (!lock) {
  4535. lock=TRUE;
  4536. if (!projectErrorsAndWarningsAction->isEnabled()) on=FALSE;
  4537. projectErrorsAndWarningsAction->setOn(on);
  4538. if (on)
  4539. errorListDock->show();
  4540. else
  4541. errorListDock->hide();
  4542. lock=FALSE;
  4543. }
  4544. }
  4545. void MainForm::projectProgramOutput()
  4546. {
  4547. ProgramOutput programOutputDialog;
  4548. programOutputDialog.textBrowser->setText(programOutput);
  4549. programOutputDialog.exec();
  4550. }
  4551. void MainForm::projectOptions()
  4552. {
  4553. ProjectOptions *projectoptions=new ProjectOptions(this);
  4554. projectoptions->exec();
  4555. if (projectoptions->result()==QDialog::Accepted) {
  4556. projectIsDirty=TRUE;
  4557. projectNeedsRelink=TRUE;
  4558. headersModified=TRUE; // force complete rebuild
  4559. }
  4560. delete(projectoptions);
  4561. bool runnable=!settings.archive&&!settings.flash_os&&preferences.linkTarget!=LT_NONE;
  4562. menuBar()->setItemVisible(5,runnable); //debugMenu
  4563. debugRunAction->setVisible(runnable);
  4564. debugPauseAction->setVisible(runnable);
  4565. }
  4566. bool MainForm::tiemuInstance(TiEmuDBus *&instance)
  4567. {
  4568. QDBusConnection connection=QDBusConnection::sessionBus();
  4569. if (!connection.isConnected()) {
  4570. KMessageBox::error(this,"Can\'t attach to D-Bus.");
  4571. instance=NULL;
  4572. return FALSE;
  4573. }
  4574. instance=new TiEmuDBus("org.ticalc.lpg.tiemu.TiEmuDBus",
  4575. "/org/ticalc/lpg/tiemu/TiEmuDBus",connection,this);
  4576. if (!instance->isValid()) {
  4577. delete instance;
  4578. instance=NULL;
  4579. }
  4580. return TRUE;
  4581. }
  4582. // Same values as TIGCC, except for CALCULATOR_INVALID.
  4583. enum CalculatorModels {CALCULATOR_TI89, CALCULATOR_TI92P, CALCULATOR_TI92,
  4584. CALCULATOR_V200, CALCULATOR_INVALID=-1};
  4585. QString MainForm::tilibsErrorMessage(int err)
  4586. {
  4587. if (!err) return "No error. (This is a bug, please report.)";
  4588. char *msg=0;
  4589. if ((err=ticables_error_get(err,&msg))
  4590. && (err=tifiles_error_get(err,&msg))
  4591. && (err=ticalcs_error_get(err,&msg)))
  4592. return "Invalid error code. (This is a bug, please report.)";
  4593. QString ret=msg;
  4594. g_free(msg);
  4595. return ret;
  4596. }
  4597. void MainForm::debugRun()
  4598. {
  4599. if (compiling) return;
  4600. // Can't link a project without saving it first.
  4601. if (projectFileName.isEmpty()) {
  4602. if (!fileSave() || projectFileName.isEmpty()) return;
  4603. }
  4604. startCompiling();
  4605. compileProject(FALSE);
  4606. if (!errorsCompilingFlag && !stopCompilingFlag && projectNeedsRelink)
  4607. linkProject();
  4608. bool success=(!errorsCompilingFlag && !stopCompilingFlag);
  4609. stopCompiling();
  4610. QString projectBaseName=projectFileName;
  4611. if (projectBaseName.endsWith(".tpr",FALSE))
  4612. projectBaseName.truncate(projectBaseName.length()-4);
  4613. if (success && (QFileInfo(projectBaseName+".89z").exists()
  4614. || QFileInfo(projectBaseName+".9xz").exists()
  4615. || QFileInfo(projectBaseName+".v2z").exists()
  4616. || QFileInfo(projectBaseName+".92p").exists())) {
  4617. QStringList files;
  4618. if (settings.fargo)
  4619. files.append(projectBaseName+".92p");
  4620. else {
  4621. files.append(projectBaseName+".89z");
  4622. if (settings.pack) files.append(projectBaseName+".89y");
  4623. if (settings.use_data_var) files.append(projectBaseName+"-data.89y");
  4624. }
  4625. if (files.isEmpty()) return;
  4626. // Detect model of linked calculator.
  4627. CalculatorModels model=CALCULATOR_INVALID;
  4628. TiEmuDBus *tiemuDBus=0;
  4629. CableHandle *cable=0;
  4630. CalcHandle *calc=0;
  4631. switch (preferences.linkTarget) {
  4632. case LT_TIEMU:
  4633. {
  4634. // Fire up TiEmu if it isn't running yet.
  4635. if (!tiemuInstance(tiemuDBus)) return;
  4636. if (!tiemuDBus) {
  4637. if (!KRun::runCommand("tiemu", this)) {
  4638. KMessageBox::error(this,"Can't run TiEmu.");
  4639. return;
  4640. }
  4641. do {
  4642. usleep(100000);
  4643. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,100);
  4644. if (!tiemuInstance(tiemuDBus)) return;
  4645. } while (!tiemuDBus);
  4646. }
  4647. // Wait for TiEmu to get ready.
  4648. bool ready=false;
  4649. do {
  4650. usleep(100000);
  4651. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,100);
  4652. QDBusReply<bool> reply=tiemuDBus->ready_for_transfers();
  4653. if (!reply.isValid()) {
  4654. KMessageBox::error(this,"D-Bus function call failed.");
  4655. delete tiemuDBus;
  4656. return;
  4657. }
  4658. ready=reply.value();
  4659. } while (!ready);
  4660. // Now obtain the model from TiEmu.
  4661. QDBusReply<int> reply=tiemuDBus->emulated_calc_type();
  4662. int tiemuCalcType;
  4663. if (!reply.isValid() || !(tiemuCalcType=reply.value())) {
  4664. KMessageBox::error(this,"D-Bus function call failed.");
  4665. delete tiemuDBus;
  4666. return;
  4667. }
  4668. switch (tiemuCalcType) {
  4669. case TIEMU_CALC_TI89:
  4670. case TIEMU_CALC_TI89t:
  4671. model=CALCULATOR_TI89;
  4672. break;
  4673. case TIEMU_CALC_TI92p:
  4674. model=CALCULATOR_TI92P;
  4675. break;
  4676. case TIEMU_CALC_V200:
  4677. model=CALCULATOR_V200;
  4678. break;
  4679. case TIEMU_CALC_TI92:
  4680. model=CALCULATOR_TI92;
  4681. break;
  4682. default:
  4683. KMessageBox::error(this,"Unsupported calculator model.");
  4684. return;
  4685. }
  4686. }
  4687. break;
  4688. case LT_REALCALC:
  4689. {
  4690. // Probe for the connected model.
  4691. CalcModel tilibsCalcModel=CALC_NONE;
  4692. int err;
  4693. if ((err=ticalcs_probe(preferences.linkCable,preferences.linkPort,
  4694. &tilibsCalcModel,TRUE))) {
  4695. KMessageBox::error(this,tilibsErrorMessage(err));
  4696. return;
  4697. }
  4698. switch (tilibsCalcModel) {
  4699. case CALC_TI89:
  4700. case CALC_TI89T:
  4701. case CALC_TI89T_USB:
  4702. model=CALCULATOR_TI89;
  4703. break;
  4704. case CALC_TI92P:
  4705. model=CALCULATOR_TI92P;
  4706. break;
  4707. case CALC_V200:
  4708. model=CALCULATOR_V200;
  4709. break;
  4710. case CALC_TI92:
  4711. model=CALCULATOR_TI92;
  4712. break;
  4713. default:
  4714. KMessageBox::error(this,"Unsupported calculator model.");
  4715. return;
  4716. }
  4717. // Allocate handle for the cable.
  4718. cable=ticables_handle_new(preferences.linkCable,preferences.linkPort);
  4719. if (!cable) {
  4720. KMessageBox::error(this,"Failed to allocate cable handle.");
  4721. return;
  4722. }
  4723. // Allocate handle for the calculator.
  4724. calc=ticalcs_handle_new(tilibsCalcModel);
  4725. if (!calc) {
  4726. KMessageBox::error(this,"Failed to allocate calculator handle.");
  4727. ticables_handle_del(cable);
  4728. return;
  4729. }
  4730. // Attach the calculator handle to the cable handle.
  4731. if ((err=ticalcs_cable_attach(calc,cable))) {
  4732. KMessageBox::error(this,tilibsErrorMessage(err));
  4733. ticalcs_handle_del(calc);
  4734. ticables_handle_del(cable);
  4735. return;
  4736. }
  4737. }
  4738. break;
  4739. default:
  4740. qWarning("Bug: debugRun called with no link target.");
  4741. return;
  4742. }
  4743. // Select the correct files for the model.
  4744. if (model!=CALCULATOR_TI92 && settings.fargo) {
  4745. KMessageBox::error(this,"Can't send Fargo program to a TI-89/89Ti/92+/V200.");
  4746. return;
  4747. }
  4748. if ((model==CALCULATOR_TI92 || model==CALCULATOR_INVALID) && !settings.fargo) {
  4749. KMessageBox::error(this,"Can't send AMS program to a TI-92.");
  4750. return;
  4751. }
  4752. for (QStringList::Iterator it=files.begin(); it!=files.end(); ++it) {
  4753. if (model==CALCULATOR_TI92P) (*it).replace(QRegExp("\\.89(?=.$)"),".9x");
  4754. else if (model==CALCULATOR_V200) (*it).replace(QRegExp("\\.89(?=.$)"),".v2");
  4755. if (!QFileInfo(*it).exists()) {
  4756. KMessageBox::error(this,"The program was not compiled for the linked calculator.");
  4757. return;
  4758. }
  4759. }
  4760. // Now send the files.
  4761. switch (preferences.linkTarget) {
  4762. case LT_TIEMU:
  4763. // Send the files.
  4764. if (settings.debug_info && !settings.pack
  4765. && QFileInfo(projectBaseName+".dbg").exists()) {
  4766. QString mainFile=files.first();
  4767. files.pop_front();
  4768. QDBusReply<bool> reply=tiemuDBus->debug_file(mainFile);
  4769. if (!reply.isValid() || !reply.value()) {
  4770. KMessageBox::error(this,"D-Bus function call failed.");
  4771. delete tiemuDBus;
  4772. return;
  4773. }
  4774. }
  4775. {
  4776. QDBusReply<bool> reply=tiemuDBus->send_files(files);
  4777. if (!reply.isValid() || !reply.value()) {
  4778. KMessageBox::error(this,"D-Bus function call failed.");
  4779. delete tiemuDBus;
  4780. return;
  4781. }
  4782. }
  4783. break;
  4784. case LT_REALCALC:
  4785. ticables_options_set_timeout(cable,DFLT_TIMEOUT<<2);
  4786. ticalcs_update_set(calc,&ticalcsUpdate);
  4787. for (QStringList::Iterator it=files.begin(); it!=files.end(); ++it) {
  4788. const char *file=*it;
  4789. int err;
  4790. // libticalcs2 does NO validation on the file, so better do it now.
  4791. if (!tifiles_file_is_single(file)
  4792. || !tifiles_calc_is_ti9x(tifiles_file_get_model(file))) {
  4793. KMessageBox::error(this,QString("File \'%1\' has an invalid format.").arg(file));
  4794. ticalcs_handle_del(calc);
  4795. ticables_handle_del(cable);
  4796. return;
  4797. }
  4798. // Send the file.
  4799. callbacksInit(this);
  4800. if ((err=ticalcs_calc_send_var2(calc,MODE_NORMAL,file))) {
  4801. bool cancelled=ticalcsUpdate.cancel;
  4802. callbacksCleanup();
  4803. if (!cancelled) KMessageBox::error(this,tilibsErrorMessage(err));
  4804. ticalcs_handle_del(calc);
  4805. ticables_handle_del(cable);
  4806. return;
  4807. }
  4808. callbacksCleanup();
  4809. }
  4810. break;
  4811. default:
  4812. qFatal("Bug: This code in debugRun should be unreachable!");
  4813. return;
  4814. }
  4815. // And finally run the program.
  4816. QString command=(QString("%1%2(%3)")
  4817. .arg(rootListItem->text(0).contains('\\')?"":"main\\")
  4818. .arg(rootListItem->text(0)).arg(settings.cmd_line));
  4819. switch (preferences.linkTarget) {
  4820. case LT_TIEMU:
  4821. {
  4822. // Execute the command.
  4823. QDBusReply<bool> reply=tiemuDBus->execute_command(command);
  4824. if (!reply.isValid() || !reply.value())
  4825. KMessageBox::error(this,"D-Bus function call failed.");
  4826. delete tiemuDBus;
  4827. }
  4828. break;
  4829. case LT_REALCALC:
  4830. {
  4831. int err;
  4832. // Convert the command to the calculator charset.
  4833. char *ti=ticonv_charset_utf16_to_ti(CALC_TI89,command.utf16());
  4834. // Send it character by character.
  4835. #define SEND_CHAR(c) \
  4836. if ((err=ticalcs_calc_send_key(calc,(c)))) { \
  4837. KMessageBox::error(this,tilibsErrorMessage(err)); \
  4838. g_free(ti); \
  4839. ticalcs_handle_del(calc); \
  4840. ticables_handle_del(cable); \
  4841. return; \
  4842. }
  4843. SEND_CHAR(264); // KEY_ESC
  4844. SEND_CHAR(264); // KEY_ESC
  4845. SEND_CHAR(model?8273:277); // KEY_HOME
  4846. SEND_CHAR(263); // KEY_CLEAR
  4847. SEND_CHAR(263); // KEY_CLEAR
  4848. for (unsigned char *p=reinterpret_cast<unsigned char *>(ti); *p; p++) {
  4849. SEND_CHAR(*p);
  4850. }
  4851. SEND_CHAR(13); // KEY_ENTER
  4852. #undef SEND_CHAR
  4853. g_free(ti);
  4854. }
  4855. ticalcs_handle_del(calc);
  4856. ticables_handle_del(cable);
  4857. break;
  4858. default:
  4859. qFatal("Bug: This code in debugRun should be unreachable!");
  4860. return;
  4861. }
  4862. }
  4863. }
  4864. void MainForm::debugPause()
  4865. {
  4866. // This is enabled only for LT_TIEMU. Run the TiEmu debugger.
  4867. TiEmuDBus *tiemuDBus;
  4868. if (!tiemuInstance(tiemuDBus) || !tiemuDBus) return;
  4869. if (!tiemuDBus->enter_debugger().isValid())
  4870. KMessageBox::error(this,"D-Bus function call failed.");
  4871. delete tiemuDBus;
  4872. }
  4873. void MainForm::debugReset()
  4874. {
  4875. // This is enabled only for LT_TIEMU. Reset TiEmu.
  4876. TiEmuDBus *tiemuDBus;
  4877. if (!tiemuInstance(tiemuDBus) || !tiemuDBus) return;
  4878. if (!tiemuDBus->reset_calc(FALSE).isValid())
  4879. KMessageBox::error(this,"D-Bus function call failed.");
  4880. delete tiemuDBus;
  4881. }
  4882. void MainForm::toolsConfigure()
  4883. {
  4884. ToolsDialog toolsDialog(this);
  4885. toolsDialog.exec();
  4886. if (toolsDialog.result()==QDialog::Accepted) {
  4887. KConfigGroup toolsConfig=pconfig->group("Tools");
  4888. unsigned toolCount=tools.count();
  4889. toolsConfig.writeEntry("Count",toolCount);
  4890. for (unsigned idx=0; idx<toolCount; idx++) {
  4891. KConfigGroup toolConfig=pconfig->group(QString("Tool %1").arg(idx));
  4892. Tool &tool=tools[idx];
  4893. toolConfig.writeEntry("Title",tool.title);
  4894. toolConfig.writeEntry("Command Line",tool.commandLine);
  4895. toolConfig.writeEntry("Working Directory",tool.workingDirectory);
  4896. toolConfig.writeEntry("Terminal",tool.runInTerminal);
  4897. }
  4898. pconfig->sync();
  4899. updateToolsMenu();
  4900. }
  4901. }
  4902. void MainForm::updateToolsMenu()
  4903. {
  4904. toolsMenu->clear();
  4905. toolsConfigureAction->addTo(toolsMenu);
  4906. unsigned toolCount=tools.count();
  4907. if (toolCount) toolsMenu->insertSeparator();
  4908. for (unsigned idx=0; idx<toolCount; idx++)
  4909. toolsMenu->insertItem(tools[idx].title,idx);
  4910. disconnect(toolsMenu,SIGNAL(highlighted(int)),0,0);
  4911. connect(toolsMenu,SIGNAL(highlighted(int)),
  4912. this,SLOT(toolsMenu_highlighted(int)));
  4913. disconnect(toolsMenu,SIGNAL(aboutToHide()),0,0);
  4914. connect(toolsMenu,SIGNAL(aboutToHide()),this,SLOT(toolsMenu_aboutToHide()));
  4915. }
  4916. void MainForm::toolsMenu_highlighted(int id)
  4917. {
  4918. if (id==toolsMenu->idAt(0))
  4919. statusBar()->message(toolsConfigureAction->statusTip());
  4920. else if (id!=toolsMenu->idAt(1))
  4921. statusBar()->message(tools[id].commandLine);
  4922. }
  4923. void MainForm::toolsMenu_activated(int id)
  4924. {
  4925. if (id!=toolsMenu->idAt(0) && id!=toolsMenu->idAt(1)) {
  4926. const Tool &tool=tools[id];
  4927. KProcess process(this);
  4928. KShell::Errors err;
  4929. QStringList args=KShell::splitArgs(tool.commandLine,
  4930. KShell::TildeExpand|KShell::AbortOnMeta,
  4931. &err);
  4932. if (err) {
  4933. KMessageBox::error(this,"Invalid command line.");
  4934. return;
  4935. }
  4936. if (tool.runInTerminal) {
  4937. KConfigGroup globalConfigGeneral(KGlobal::config(),"General");
  4938. QString terminal=globalConfigGeneral.readPathEntry("TerminalApplication",
  4939. "konsole");
  4940. if (terminal=="konsole")
  4941. terminal+=" -caption=%c";
  4942. QHash<QChar,QString> map;
  4943. map.insert('c',tool.title);
  4944. map.insert('i',"");
  4945. map.insert('m',"");
  4946. terminal=KMacroExpander::expandMacrosShellQuote(terminal,map);
  4947. if (terminal.isNull()) {
  4948. KMessageBox::error(this,"Invalid terminal specification.");
  4949. return;
  4950. }
  4951. QStringList termargs=KShell::splitArgs(terminal,
  4952. KShell::TildeExpand|KShell::AbortOnMeta,
  4953. &err);
  4954. if (err) {
  4955. KMessageBox::error(this,"Invalid terminal specification.");
  4956. return;
  4957. }
  4958. process << termargs << "-e" << "sh" << "-c"
  4959. << (tool.commandLine+" ; echo Press Return to close... ; read");
  4960. } else
  4961. process << args;
  4962. if (!tool.workingDirectory.isEmpty())
  4963. process.setWorkingDirectory(tool.workingDirectory);
  4964. if (!process.startDetached())
  4965. KMessageBox::error(this,QString("Can't run \'%1\'.").arg(tool.commandLine));
  4966. }
  4967. }
  4968. void MainForm::toolsMenu_aboutToHide()
  4969. {
  4970. statusBar()->clear();
  4971. }
  4972. void MainForm::helpDocumentation()
  4973. {
  4974. assistant->openAssistant();
  4975. }
  4976. void MainForm::helpContents()
  4977. {
  4978. force_qt_assistant_page(0);
  4979. assistant->openAssistant();
  4980. }
  4981. void MainForm::helpIndex()
  4982. {
  4983. force_qt_assistant_page(1);
  4984. assistant->openAssistant();
  4985. }
  4986. void MainForm::helpSearch()
  4987. {
  4988. force_qt_assistant_page(3);
  4989. assistant->openAssistant();
  4990. }
  4991. void MainForm::helpNews()
  4992. {
  4993. NewsDialog newsDialog(this);
  4994. newsDialog.loadNews();
  4995. newsDialog.exec();
  4996. }
  4997. void MainForm::helpAbout()
  4998. {
  4999. khelpmenu->aboutApplication();
  5000. }
  5001. void MainForm::updateSizes()
  5002. {
  5003. int leftSize=splitter->sizes().first();
  5004. int rightSize=splitter->sizes().last();
  5005. int totalSize=leftSize+rightSize;
  5006. int mySize=size().width();
  5007. leftStatusLabel->setMaximumWidth(leftSize*mySize/totalSize);
  5008. rightStatusLabel->setMaximumWidth(rightSize*mySize/totalSize-10>0?
  5009. rightSize*mySize/totalSize-10:0);
  5010. }
  5011. void MainForm::resizeEvent(QResizeEvent *event)
  5012. {
  5013. QMainWindow::resizeEvent(event);
  5014. if (event->size()==event->oldSize()) return;
  5015. updateSizes();
  5016. }
  5017. void MainForm::timerEvent(QTimerEvent *event)
  5018. {
  5019. static int lastSplitterPos=-1;
  5020. QMainWindow::timerEvent(event);
  5021. if (lastSplitterPos==splitter->sizes().first()) return;
  5022. lastSplitterPos=splitter->sizes().first();
  5023. updateSizes();
  5024. }
  5025. void MainForm::fileTreeClicked(Q3ListViewItem *item)
  5026. {
  5027. if (!item) return;
  5028. if (fileTree->selectedItem()!=item) {
  5029. fileTree->setSelected(item,TRUE);
  5030. fileTree->ensureItemVisible(item);
  5031. }
  5032. if (IS_FOLDER(currentListItem))
  5033. currentListItem->setPixmap(0,SYSICON("folder","folder1.png"));
  5034. if (IS_FILE(currentListItem)) {
  5035. CATEGORY_OF(category,currentListItem);
  5036. if (IS_EDITABLE_CATEGORY(category)) {
  5037. static_cast<ListViewFile *>(currentListItem)->kateView->hide();
  5038. widgetStack->removeWidget(static_cast<ListViewFile *>(currentListItem)->kateView);
  5039. widgetStack->raiseWidget(-1);
  5040. }
  5041. }
  5042. if (IS_FOLDER(item)) {
  5043. // Bluecurve's "folder-open" isn't actually more open than "folder".
  5044. item->setPixmap(0,SYSICON(KIconTheme::current()=="Bluecurve"?"folder-accept":"folder-open","folder2.png"));
  5045. fileNewFolderAction->setEnabled(TRUE);
  5046. filePrintAction->setEnabled(FALSE);
  5047. filePrintQuicklyAction->setEnabled(FALSE);
  5048. editUndoAction->setEnabled(FALSE);
  5049. editRedoAction->setEnabled(FALSE);
  5050. editClearAction->setEnabled(FALSE);
  5051. editCutAction->setEnabled(FALSE);
  5052. editCopyAction->setEnabled(FALSE);
  5053. editPasteAction->setEnabled(FALSE);
  5054. editSelectAllAction->setEnabled(FALSE);
  5055. editIncreaseIndentAction->setEnabled(FALSE);
  5056. editDecreaseIndentAction->setEnabled(FALSE);
  5057. findFunctionsAction->setEnabled(FALSE);
  5058. findOpenFileAtCursorAction->setEnabled(FALSE);
  5059. findFindSymbolDeclarationAction->setEnabled(FALSE);
  5060. shortcuts[0]->setEnabled(FALSE);
  5061. shortcuts[1]->setEnabled(FALSE);
  5062. shortcuts[2]->setEnabled(FALSE);
  5063. shortcuts[3]->setEnabled(FALSE);
  5064. shortcuts[4]->setEnabled(FALSE);
  5065. shortcuts[5]->setEnabled(FALSE);
  5066. shortcuts[6]->setEnabled(FALSE);
  5067. shortcuts[7]->setEnabled(FALSE);
  5068. shortcuts[8]->setEnabled(FALSE);
  5069. shortcuts[9]->setEnabled(FALSE);
  5070. shortcuts[10]->setEnabled(FALSE);
  5071. shortcuts[17]->setEnabled(FALSE);
  5072. } else if (IS_FILE(item)) {
  5073. fileNewFolderAction->setEnabled(TRUE);
  5074. CATEGORY_OF(category,item->parent());
  5075. if (IS_EDITABLE_CATEGORY(category)) {
  5076. KTextEditor::View *kateView=static_cast<ListViewFile *>(item)->kateView;
  5077. filePrintAction->setEnabled(TRUE);
  5078. filePrintQuicklyAction->setEnabled(TRUE);
  5079. widgetStack->addWidget(kateView);
  5080. kateView->show();
  5081. widgetStack->raiseWidget(kateView);
  5082. editUndoAction->setEnabled(kateView->action(KStandardAction::name(KStandardAction::Undo))->isEnabled());
  5083. editRedoAction->setEnabled(kateView->action(KStandardAction::name(KStandardAction::Redo))->isEnabled());
  5084. editClearAction->setEnabled(kateView->selection());
  5085. editCutAction->setEnabled(kateView->selection());
  5086. editCopyAction->setEnabled(kateView->selection());
  5087. editPasteAction->setEnabled(!clipboard->text().isNull());
  5088. editSelectAllAction->setEnabled(TRUE);
  5089. editIncreaseIndentAction->setEnabled(TRUE);
  5090. editDecreaseIndentAction->setEnabled(TRUE);
  5091. findFunctionsAction->setEnabled(category!=txtFilesListItem);
  5092. findOpenFileAtCursorAction->setEnabled(TRUE);
  5093. findFindSymbolDeclarationAction->setEnabled(TRUE);
  5094. shortcuts[0]->setEnabled(kateView->action(KStandardAction::name(KStandardAction::Undo))->isEnabled());
  5095. shortcuts[1]->setEnabled(kateView->action(KStandardAction::name(KStandardAction::Redo))->isEnabled());
  5096. shortcuts[2]->setEnabled(kateView->selection());
  5097. shortcuts[3]->setEnabled(kateView->selection());
  5098. shortcuts[4]->setEnabled(!clipboard->text().isNull());
  5099. shortcuts[5]->setEnabled(TRUE);
  5100. shortcuts[6]->setEnabled(TRUE);
  5101. shortcuts[7]->setEnabled(TRUE);
  5102. shortcuts[8]->setEnabled(TRUE);
  5103. shortcuts[9]->setEnabled(TRUE);
  5104. shortcuts[10]->setEnabled(TRUE);
  5105. shortcuts[17]->setEnabled(TRUE);
  5106. } else {
  5107. filePrintAction->setEnabled(FALSE);
  5108. filePrintQuicklyAction->setEnabled(FALSE);
  5109. editUndoAction->setEnabled(FALSE);
  5110. editRedoAction->setEnabled(FALSE);
  5111. editClearAction->setEnabled(FALSE);
  5112. editCutAction->setEnabled(FALSE);
  5113. editCopyAction->setEnabled(FALSE);
  5114. editPasteAction->setEnabled(FALSE);
  5115. editSelectAllAction->setEnabled(FALSE);
  5116. editIncreaseIndentAction->setEnabled(FALSE);
  5117. editDecreaseIndentAction->setEnabled(FALSE);
  5118. findFunctionsAction->setEnabled(FALSE);
  5119. findOpenFileAtCursorAction->setEnabled(FALSE);
  5120. findFindSymbolDeclarationAction->setEnabled(FALSE);
  5121. shortcuts[0]->setEnabled(FALSE);
  5122. shortcuts[1]->setEnabled(FALSE);
  5123. shortcuts[2]->setEnabled(FALSE);
  5124. shortcuts[3]->setEnabled(FALSE);
  5125. shortcuts[4]->setEnabled(FALSE);
  5126. shortcuts[5]->setEnabled(FALSE);
  5127. shortcuts[6]->setEnabled(FALSE);
  5128. shortcuts[7]->setEnabled(FALSE);
  5129. shortcuts[8]->setEnabled(FALSE);
  5130. shortcuts[9]->setEnabled(FALSE);
  5131. shortcuts[10]->setEnabled(FALSE);
  5132. shortcuts[17]->setEnabled(FALSE);
  5133. }
  5134. } else {
  5135. fileNewFolderAction->setEnabled(FALSE);
  5136. filePrintAction->setEnabled(FALSE);
  5137. filePrintQuicklyAction->setEnabled(FALSE);
  5138. editUndoAction->setEnabled(FALSE);
  5139. editRedoAction->setEnabled(FALSE);
  5140. editClearAction->setEnabled(FALSE);
  5141. editCutAction->setEnabled(FALSE);
  5142. editCopyAction->setEnabled(FALSE);
  5143. editPasteAction->setEnabled(FALSE);
  5144. editSelectAllAction->setEnabled(FALSE);
  5145. editIncreaseIndentAction->setEnabled(FALSE);
  5146. editDecreaseIndentAction->setEnabled(FALSE);
  5147. findFunctionsAction->setEnabled(FALSE);
  5148. findOpenFileAtCursorAction->setEnabled(FALSE);
  5149. findFindSymbolDeclarationAction->setEnabled(FALSE);
  5150. shortcuts[0]->setEnabled(FALSE);
  5151. shortcuts[1]->setEnabled(FALSE);
  5152. shortcuts[2]->setEnabled(FALSE);
  5153. shortcuts[3]->setEnabled(FALSE);
  5154. shortcuts[4]->setEnabled(FALSE);
  5155. shortcuts[5]->setEnabled(FALSE);
  5156. shortcuts[6]->setEnabled(FALSE);
  5157. shortcuts[7]->setEnabled(FALSE);
  5158. shortcuts[8]->setEnabled(FALSE);
  5159. shortcuts[9]->setEnabled(FALSE);
  5160. shortcuts[10]->setEnabled(FALSE);
  5161. shortcuts[17]->setEnabled(FALSE);
  5162. }
  5163. currentListItem=item;
  5164. updateLeftStatusLabel();
  5165. updateRightStatusLabel();
  5166. }
  5167. void MainForm::fileNewFolder()
  5168. {
  5169. if (compiling) return;
  5170. if (IS_FILE(currentListItem))
  5171. currentListItem=currentListItem->parent();
  5172. Q3ListViewItem *item=NULL, *next=currentListItem->firstChild();
  5173. for (; next; next=item->nextSibling())
  5174. {
  5175. item=next;
  5176. }
  5177. Q3ListViewItem *newFolder=item?new ListViewFolder(currentListItem,item)
  5178. :new ListViewFolder(currentListItem);
  5179. newFolder->setText(0,"NewFolder");
  5180. newFolder->setRenameEnabled(0,TRUE);
  5181. currentListItem->setOpen(TRUE);
  5182. fileTreeClicked(newFolder);
  5183. newFolder->startRename(0);
  5184. projectIsDirty=TRUE;
  5185. projectNeedsRelink=TRUE;
  5186. }
  5187. bool MainForm::removeItem(Q3ListViewItem *item)
  5188. {
  5189. if (IS_FOLDER(item) && !IS_CATEGORY(item)) {
  5190. Q3ListViewItem *child=item->firstChild();
  5191. while (child) {
  5192. Q3ListViewItem *nextChild=child->nextSibling();
  5193. if (!removeItem(child)) return FALSE;
  5194. child=nextChild;
  5195. }
  5196. delete item;
  5197. currentListItem=NULL;
  5198. fileTreeClicked(fileTree->currentItem());
  5199. projectIsDirty=TRUE;
  5200. projectNeedsRelink=TRUE;
  5201. return TRUE;
  5202. } else if (IS_FILE(item)) {
  5203. if (!fileSavePrompt(item)) {
  5204. delete item;
  5205. currentListItem=NULL;
  5206. fileTreeClicked(fileTree->currentItem());
  5207. projectIsDirty=TRUE;
  5208. projectNeedsRelink=TRUE;
  5209. return TRUE;
  5210. } else return FALSE;
  5211. } else return FALSE;
  5212. }
  5213. void MainForm::fileTreeContextMenuRequested(Q3ListViewItem *item,
  5214. const QPoint &pos,
  5215. int col __attribute__((unused)))
  5216. {
  5217. fileTreeClicked(item);
  5218. if (IS_FOLDER(item)) {
  5219. Q3PopupMenu menu;
  5220. menu.insertItem("New &Folder",0);
  5221. menu.insertItem("New F&ile",1);
  5222. if (compiling) {
  5223. menu.setItemEnabled(0,FALSE);
  5224. menu.setItemEnabled(1,FALSE);
  5225. }
  5226. CATEGORY_OF(category,item);
  5227. if (!IS_EDITABLE_CATEGORY(category))
  5228. menu.setItemEnabled(1,FALSE);
  5229. if (!IS_CATEGORY(item)) {
  5230. menu.insertSeparator();
  5231. menu.insertItem("&Remove",2);
  5232. if (compiling) menu.setItemEnabled(2,FALSE);
  5233. menu.insertItem("Re&name",3);
  5234. }
  5235. switch (menu.exec(pos)) {
  5236. case 0:
  5237. fileNewFolder();
  5238. break;
  5239. case 1:
  5240. newFile(item);
  5241. break;
  5242. case 2:
  5243. removeItem(item);
  5244. break;
  5245. case 3:
  5246. item->startRename(0);
  5247. }
  5248. } else if (IS_FILE(item)) {
  5249. Q3PopupMenu menu;
  5250. ListViewFile *theFile=static_cast<ListViewFile *>(item);
  5251. menu.insertItem("&Save",0);
  5252. CATEGORY_OF(category,item);
  5253. if (!IS_EDITABLE_CATEGORY(category))
  5254. menu.setItemEnabled(0,FALSE);
  5255. menu.insertItem("Save &As...",1);
  5256. menu.insertSeparator();
  5257. menu.insertItem("&Compile",2);
  5258. if (compiling || category==txtFilesListItem
  5259. || !IS_EDITABLE_CATEGORY(category))
  5260. menu.setItemEnabled(2,FALSE);
  5261. menu.insertSeparator();
  5262. menu.insertItem("&Remove",3);
  5263. menu.insertItem("&Delete",4);
  5264. if (compiling) {
  5265. menu.setItemEnabled(3,FALSE);
  5266. menu.setItemEnabled(4,FALSE);
  5267. }
  5268. if (theFile->isNew)
  5269. menu.setItemEnabled(4,FALSE);
  5270. menu.insertSeparator();
  5271. menu.insertItem("Re&name",5);
  5272. switch (menu.exec(pos)) {
  5273. case 0:
  5274. fileSave_save(item);
  5275. break;
  5276. case 1:
  5277. fileSave_saveAs(item);
  5278. break;
  5279. case 2:
  5280. if (compiling) return;
  5281. startCompiling();
  5282. compileFile(theFile,TRUE,TRUE);
  5283. stopCompiling();
  5284. break;
  5285. case 3:
  5286. removeItem(item);
  5287. break;
  5288. case 4:
  5289. if (KMessageBox::questionYesNo(this,
  5290. "Are you sure you want to delete this source file? "
  5291. "You cannot undo this operation.","Confirm Deletion")
  5292. ==KMessageBox::Yes) {
  5293. QString fileName=theFile->fileName;
  5294. KDirWatch::self()->removeFile(fileName);
  5295. if (QDir().remove(fileName)) {
  5296. delete item;
  5297. currentListItem=NULL;
  5298. fileTreeClicked(fileTree->currentItem());
  5299. projectIsDirty=TRUE;
  5300. projectNeedsRelink=TRUE;
  5301. } else {
  5302. KMessageBox::error(this,
  5303. QString("Error deleting file \'%1\'").arg(fileName));
  5304. if (IS_EDITABLE_CATEGORY(category) && !fileName.isEmpty() && fileName[0]=='/')
  5305. KDirWatch::self()->addFile(fileName);
  5306. }
  5307. }
  5308. break;
  5309. case 5:
  5310. item->startRename(0);
  5311. }
  5312. }
  5313. }
  5314. QStringList MainForm::extractAllFileNames(void)
  5315. {
  5316. Q3ListViewItem *item=rootListItem->firstChild(),*next;
  5317. QStringList allFiles;
  5318. while (item)
  5319. {
  5320. if (IS_FOLDER(item))
  5321. {
  5322. next=item->firstChild();
  5323. if (next)
  5324. {
  5325. item=next;
  5326. continue;
  5327. }
  5328. }
  5329. if (IS_FILE(item))
  5330. {
  5331. allFiles << (static_cast<ListViewFile *>(item)->fileName);
  5332. }
  5333. next=item->nextSibling();
  5334. while (!next)
  5335. {
  5336. next=item->parent();
  5337. if (next==rootListItem||!next)
  5338. {
  5339. return allFiles;
  5340. }
  5341. item=next;
  5342. next=item->nextSibling();
  5343. }
  5344. item=next;
  5345. }
  5346. return allFiles;
  5347. }
  5348. //you put in parent, and it gives you the rest, but you must have a place to put it all.
  5349. void MainForm::extractFileTreeInfo(Q3ListViewItem *parent,Q3ListViewItem **p_category,QString *p_folderPath)
  5350. {
  5351. Q3ListViewItem *item,*next;
  5352. QString tmp=QString::null;
  5353. int o;
  5354. CATEGORY_OF(category,parent);
  5355. *p_category=category;
  5356. item=category->firstChild();
  5357. while (item)
  5358. {
  5359. if (item==parent)
  5360. {
  5361. if (!tmp.isEmpty())
  5362. tmp+='/';
  5363. tmp+=item->text(0);
  5364. *p_folderPath=tmp;
  5365. }
  5366. if (IS_FOLDER(item))
  5367. {
  5368. next=item->firstChild();
  5369. if (next)
  5370. {
  5371. if (tmp.isEmpty())
  5372. tmp=item->text(0);
  5373. else
  5374. {
  5375. tmp+='/';
  5376. tmp+=item->text(0);
  5377. }
  5378. item=next;
  5379. continue;
  5380. }
  5381. }
  5382. mfnf_seeknext:
  5383. next=item->nextSibling();
  5384. if (!next)
  5385. {
  5386. next=item->parent();
  5387. if (next==category||!next)
  5388. break;
  5389. item=next;
  5390. o=tmp.findRev('/');
  5391. if (o>=0)
  5392. tmp.truncate(o);
  5393. else
  5394. tmp.truncate(0);
  5395. goto mfnf_seeknext;
  5396. }
  5397. item=next;
  5398. }
  5399. }
  5400. void MainForm::newFile(Q3ListViewItem *parent, QString text, const QPixmap &pixmap)
  5401. {
  5402. Q3ListViewItem *item=NULL, *next=parent->firstChild();
  5403. QString tmp,oldtmp,suffix,caption;
  5404. QStringList allFiles=extractAllFileNames();
  5405. Q3ListViewItem *category;
  5406. KUrl tmpK;
  5407. int tryNum;
  5408. for (; IS_FILE(next); next=item->nextSibling())
  5409. item=next;
  5410. extractFileTreeInfo(parent,&category,&tmp);
  5411. suffix="";
  5412. if (category==hFilesListItem)
  5413. suffix="h";
  5414. else if (category==cFilesListItem)
  5415. suffix="c";
  5416. else if (category==sFilesListItem)
  5417. suffix="s";
  5418. else if (category==asmFilesListItem)
  5419. suffix="asm";
  5420. else if (category==qllFilesListItem) {
  5421. if (qllFileCount) {
  5422. KMessageBox::error(this,"There may be only one Quill source file in each project.","Quill Error");
  5423. return;
  5424. }
  5425. suffix="qll";
  5426. } else if (category==oFilesListItem)
  5427. suffix="o";
  5428. else if (category==aFilesListItem)
  5429. suffix="a";
  5430. else if (category==txtFilesListItem)
  5431. suffix="txt";
  5432. suffix='.'+suffix;
  5433. if (!tmp.isEmpty())
  5434. tmp+='/';
  5435. tmp+="New File";
  5436. tmpK.setPath(projectFileName);
  5437. kurlNewFileName(tmpK,tmp);
  5438. tmp=tmpK.path();
  5439. if (projectFileName.isEmpty() && !tmp.isEmpty())
  5440. {
  5441. short o=0;
  5442. if (tmp[0]=='.')
  5443. o=1;
  5444. if (tmp[o]=='/')
  5445. tmp=tmp.mid(o+1);
  5446. }
  5447. caption="New File";
  5448. oldtmp=tmp+' ';
  5449. tmp+=suffix;
  5450. tryNum=1;
  5451. while (!checkFileName(tmp,allFiles))
  5452. {
  5453. tryNum++;
  5454. tmp=oldtmp+QString("%1").arg(tryNum)+suffix;
  5455. caption="New File "+QString("%1").arg(tryNum);
  5456. }
  5457. ListViewFile *newFile=item?new ListViewFile(parent,item)
  5458. :new ListViewFile(parent);
  5459. newFile->fileName=tmp;
  5460. if (IS_EDITABLE_CATEGORY(category) && !tmp.isEmpty() && tmp[0]=='/')
  5461. KDirWatch::self()->addFile(tmp);
  5462. newFile->setText(0,caption);
  5463. newFile->setPixmap(0,pixmap);
  5464. parent->setOpen(TRUE);
  5465. newFile->kateView=reinterpret_cast<KTextEditor::View *>(createView(QString::null,text,category));
  5466. fileTreeClicked(newFile);
  5467. projectIsDirty=TRUE;
  5468. projectNeedsRelink=TRUE;
  5469. newFile->startRename(0);
  5470. fileCount++;
  5471. COUNTER_FOR_CATEGORY(category)++;
  5472. updateLeftStatusLabel();
  5473. }
  5474. void MainForm::newFile( Q3ListViewItem *parent )
  5475. {
  5476. CATEGORY_OF(category,parent);
  5477. newFile(parent,category==txtFilesListItem?"":
  5478. ((category==hFilesListItem?"// Header File\n//":
  5479. category==cFilesListItem?"// C Source File\n//":
  5480. category==sFilesListItem?"| Assembly Source File\n|":
  5481. category==asmFilesListItem?"; Assembly Source File\n;":
  5482. category==qllFilesListItem?"// Quill Source File\n//":"???\n")
  5483. +QString(" Created ")
  5484. +QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n"+
  5485. QString(category==cFilesListItem?(cFileCount?
  5486. "\n#include <tigcclib.h>\n":
  5487. "\n// Delete or comment out the items you do not need.\n"
  5488. "#define COMMENT_STRING \"Place your comment here.\"\n"
  5489. "#define COMMENT_PROGRAM_NAME "
  5490. "\"Place your program name here.\"\n"
  5491. "#define COMMENT_VERSION_STRING "
  5492. "\"Place your version string here.\"\n"
  5493. "#define COMMENT_VERSION_NUMBER 0,0,0,0 "
  5494. "/* major, minor, revision, subrevision */\n"
  5495. "#define COMMENT_AUTHORS "
  5496. "\"Place your author name(s) here.\"\n"
  5497. "#define COMMENT_BW_ICON \\\n"
  5498. "\t{0b0000000000000000, \\\n"
  5499. "\t 0b0000000000000000, \\\n"
  5500. "\t 0b0000000000000000, \\\n"
  5501. "\t 0b0000000000000000, \\\n"
  5502. "\t 0b0000000000000000, \\\n"
  5503. "\t 0b0000000000000000, \\\n"
  5504. "\t 0b0000000000000000, \\\n"
  5505. "\t 0b0000000000000000, \\\n"
  5506. "\t 0b0000000000000000, \\\n"
  5507. "\t 0b0000000000000000, \\\n"
  5508. "\t 0b0000000000000000, \\\n"
  5509. "\t 0b0000000000000000, \\\n"
  5510. "\t 0b0000000000000000, \\\n"
  5511. "\t 0b0000000000000000, \\\n"
  5512. "\t 0b0000000000000000, \\\n"
  5513. "\t 0b0000000000000000}\n"
  5514. "#define COMMENT_GRAY_ICON \\\n"
  5515. "\t{0b0000000000000000, \\\n"
  5516. "\t 0b0000000000000000, \\\n"
  5517. "\t 0b0000000000000000, \\\n"
  5518. "\t 0b0000000000000000, \\\n"
  5519. "\t 0b0000000000000000, \\\n"
  5520. "\t 0b0000000000000000, \\\n"
  5521. "\t 0b0000000000000000, \\\n"
  5522. "\t 0b0000000000000000, \\\n"
  5523. "\t 0b0000000000000000, \\\n"
  5524. "\t 0b0000000000000000, \\\n"
  5525. "\t 0b0000000000000000, \\\n"
  5526. "\t 0b0000000000000000, \\\n"
  5527. "\t 0b0000000000000000, \\\n"
  5528. "\t 0b0000000000000000, \\\n"
  5529. "\t 0b0000000000000000, \\\n"
  5530. "\t 0b0000000000000000}, \\\n"
  5531. "\t{0b0000000000000000, \\\n"
  5532. "\t 0b0000000000000000, \\\n"
  5533. "\t 0b0000000000000000, \\\n"
  5534. "\t 0b0000000000000000, \\\n"
  5535. "\t 0b0000000000000000, \\\n"
  5536. "\t 0b0000000000000000, \\\n"
  5537. "\t 0b0000000000000000, \\\n"
  5538. "\t 0b0000000000000000, \\\n"
  5539. "\t 0b0000000000000000, \\\n"
  5540. "\t 0b0000000000000000, \\\n"
  5541. "\t 0b0000000000000000, \\\n"
  5542. "\t 0b0000000000000000, \\\n"
  5543. "\t 0b0000000000000000, \\\n"
  5544. "\t 0b0000000000000000, \\\n"
  5545. "\t 0b0000000000000000, \\\n"
  5546. "\t 0b0000000000000000}\n\n#include <tigcclib.h>\n\n"
  5547. "// Main Function\nvoid _main(void)\n{\n"
  5548. "\t// Place your code here.\n}\n"):"")),
  5549. category==cFilesListItem||category==qllFilesListItem
  5550. ?SYSICON("text-x-csrc","filec.png"):
  5551. category==hFilesListItem?SYSICON("text-x-chdr","fileh.png"):
  5552. category==sFilesListItem||category==asmFilesListItem
  5553. ?SYSICON("text-x-hex","files.png"):
  5554. category==txtFilesListItem?SYSICON("text-plain","filet.png"):SYSICON("unknown","filex.png"));
  5555. }
  5556. Q3ListViewItem *MainForm::resolveParent(Q3ListViewItem *category)
  5557. {
  5558. Q3ListViewItem *ret=currentListItem;
  5559. if (!IS_FILE(ret)&&!IS_FOLDER(ret))
  5560. return category;
  5561. if (IS_FILE(ret))
  5562. ret=ret->parent();
  5563. Q3ListViewItem *actualCategory=ret;
  5564. while (IS_FOLDER(actualCategory->parent())) actualCategory=actualCategory->parent();
  5565. if (actualCategory!=category)
  5566. return category;
  5567. return ret;
  5568. }
  5569. void MainForm::fileNewCHeader()
  5570. {
  5571. if (compiling) return;
  5572. newFile(resolveParent(hFilesListItem),"// Header File\n// Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("text-x-chdr","fileh.png"));
  5573. }
  5574. void MainForm::fileNewGNUAssemblyHeader()
  5575. {
  5576. if (compiling) return;
  5577. newFile(resolveParent(hFilesListItem),"| Header File\n| Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("text-x-chdr","fileh.png"));
  5578. }
  5579. void MainForm::fileNewA68kAssemblyHeader()
  5580. {
  5581. if (compiling) return;
  5582. newFile(resolveParent(hFilesListItem),"; Header File\n; Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("text-x-chdr","fileh.png"));
  5583. }
  5584. void MainForm::fileNewCSourceFile()
  5585. {
  5586. if (compiling) return;
  5587. newFile(resolveParent(cFilesListItem));
  5588. }
  5589. void MainForm::fileNewGNUAssemblySourceFile()
  5590. {
  5591. if (compiling) return;
  5592. newFile(resolveParent(sFilesListItem),"| Assembly Source File\n| Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("text-x-hex","files.png"));
  5593. }
  5594. void MainForm::fileNewA68kAssemblySourceFile()
  5595. {
  5596. if (compiling) return;
  5597. newFile(resolveParent(asmFilesListItem),"; Assembly Source File\n; Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("text-x-hex","files.png"));
  5598. }
  5599. void MainForm::fileNewQuillSourceFile()
  5600. {
  5601. if (compiling) return;
  5602. newFile(resolveParent(qllFilesListItem),"// Quill Source File\n// Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("text-x-csrc","filec.png"));
  5603. }
  5604. void MainForm::fileNewTextFile()
  5605. {
  5606. if (compiling) return;
  5607. newFile(resolveParent(txtFilesListItem),"",SYSICON("text-plain","filet.png"));
  5608. }
  5609. void MainForm::updateLeftStatusLabel()
  5610. {
  5611. QString text=QString::number(fileCount)+QString(" File")
  5612. +QString(fileCount!=1?"s":"")+QString(" Total");
  5613. if (IS_FOLDER(currentListItem)||IS_FILE(currentListItem)) {
  5614. CATEGORY_OF(category,currentListItem);
  5615. text+=QString(", ")+QString::number(COUNTER_FOR_CATEGORY(category))
  5616. +QString(" in Category");
  5617. }
  5618. leftStatusLabel->setText(text);
  5619. }
  5620. void MainForm::statusBar_messageChanged(const QString & message)
  5621. {
  5622. if (message.isNull())
  5623. // Make sure no labels which should be hidden are shown.
  5624. updateRightStatusLabel();
  5625. }
  5626. void MainForm::updateRightStatusLabel()
  5627. {
  5628. int leftSize=splitter->sizes().first();
  5629. int rightSize=splitter->sizes().last();
  5630. int totalSize=leftSize+rightSize;
  5631. int mySize=size().width();
  5632. int rightStatusSize=rightSize*mySize/totalSize-10>0?
  5633. rightSize*mySize/totalSize-10:0;
  5634. if (currentListItem==rootListItem) {
  5635. rowStatusLabel->hide();
  5636. colStatusLabel->hide();
  5637. charsStatusLabel->hide();
  5638. rightStatusLabel->setMaximumWidth(rightStatusSize);
  5639. rightStatusLabel->setText(projectFileName);
  5640. } else if (IS_FOLDER(currentListItem)) {
  5641. rowStatusLabel->hide();
  5642. colStatusLabel->hide();
  5643. charsStatusLabel->hide();
  5644. rightStatusLabel->setMaximumWidth(rightStatusSize);
  5645. rightStatusLabel->setText("");
  5646. } else if (IS_FILE(currentListItem)) {
  5647. CATEGORY_OF(category,currentListItem);
  5648. if (IS_EDITABLE_CATEGORY(category) && CURRENT_VIEW) {
  5649. int line, col;
  5650. CURRENT_VIEW->cursorPosition().position(line,col);
  5651. rowStatusLabel->show();
  5652. rowStatusLabel->setMaximumWidth(30);
  5653. rowStatusLabel->setText(QString("%1").arg(line+1));
  5654. colStatusLabel->show();
  5655. colStatusLabel->setMaximumWidth(30);
  5656. colStatusLabel->setText(QString("%1").arg(col+1));
  5657. charsStatusLabel->show();
  5658. charsStatusLabel->setMaximumWidth(100);
  5659. charsStatusLabel->setText(QString("%1 Characters").arg(CURRENT_VIEW->document()->text().length()));
  5660. rightStatusLabel->setMaximumWidth(rightStatusSize-160>0?rightStatusSize-160:0);
  5661. } else {
  5662. rowStatusLabel->hide();
  5663. colStatusLabel->hide();
  5664. charsStatusLabel->hide();
  5665. rightStatusLabel->setMaximumWidth(rightStatusSize);
  5666. }
  5667. rightStatusLabel->setText(static_cast<ListViewFile *>(currentListItem)->fileName);
  5668. }
  5669. }
  5670. void MainForm::current_view_cursorPositionChanged(KTextEditor::View *view, const KTextEditor::Cursor &newPosition)
  5671. {
  5672. if (CURRENT_VIEW==view && !disableViewEvents) {
  5673. int line, col;
  5674. newPosition.position(line,col);
  5675. rowStatusLabel->setText(QString("%1").arg(line+1));
  5676. colStatusLabel->setText(QString("%1").arg(col+1));
  5677. }
  5678. }
  5679. void MainForm::current_view_textChanged(KTextEditor::Document *document)
  5680. {
  5681. if (disableViewEvents) return;
  5682. if (CURRENT_VIEW && CURRENT_VIEW->document()==document) {
  5683. charsStatusLabel->setText(QString("%1 Characters").arg(CURRENT_VIEW->document()->text().length()));
  5684. if (IS_FILE(currentListItem)) {
  5685. static_cast<ListViewFile *>(currentListItem)->modifiedSinceLastCompile=TRUE;
  5686. QString fileName=pathInProject(currentListItem);
  5687. if (projectCompletion.contains(fileName))
  5688. projectCompletion[fileName].dirty=TRUE;
  5689. }
  5690. if (preferences.deleteOverwrittenErrors && IS_FILE(currentListItem)
  5691. && CURRENT_VIEW==static_cast<ListViewFile *>(currentListItem)->kateView) {
  5692. ListViewFile *lvFile=static_cast<ListViewFile *>(currentListItem);
  5693. Q3ListViewItemIterator lvit(errorList->errorListView);
  5694. ErrorListItem *errorItem;
  5695. while ((errorItem=static_cast<ErrorListItem *>(lvit.current()))) {
  5696. ++lvit;
  5697. if (errorItem->lvFile==lvFile && errorItem->cursor) {
  5698. int line,col;
  5699. errorItem->cursor->position(line,col);
  5700. int curline,curcol;
  5701. lvFile->kateView->cursorPosition().position(curline,curcol);
  5702. if (curline==line && curcol==col)
  5703. delete errorItem;
  5704. }
  5705. }
  5706. }
  5707. }
  5708. if (kreplace) kreplace->invalidateSelection();
  5709. }
  5710. void MainForm::current_view_undoChanged()
  5711. {
  5712. if (CURRENT_VIEW && !disableViewEvents) {
  5713. editUndoAction->setEnabled(CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Undo))->isEnabled());
  5714. editRedoAction->setEnabled(CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Redo))->isEnabled());
  5715. shortcuts[0]->setEnabled(CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Undo))->isEnabled());
  5716. shortcuts[1]->setEnabled(CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Redo))->isEnabled());
  5717. }
  5718. }
  5719. void MainForm::current_view_selectionChanged(KTextEditor::View *view)
  5720. {
  5721. if (CURRENT_VIEW==view && !disableViewEvents) {
  5722. editClearAction->setEnabled(view->selection());
  5723. editCutAction->setEnabled(view->selection());
  5724. editCopyAction->setEnabled(view->selection());
  5725. shortcuts[2]->setEnabled(view->selection());
  5726. shortcuts[3]->setEnabled(view->selection());
  5727. }
  5728. }
  5729. void MainForm::current_view_textInserted(KTextEditor::View *view, const KTextEditor::Cursor &position, const QString &text)
  5730. {
  5731. int line,col;
  5732. position.position(line,col);
  5733. if (preferences.autoBlocks && text=="{"
  5734. && col==view->document()->lineLength(line)-1) {
  5735. KTextEditor::Document *doc=view->document();
  5736. CATEGORY_OF(category,currentListItem);
  5737. QString firstLine=doc->line(0);
  5738. // Only for C files.
  5739. if (category==cFilesListItem||category==qllFilesListItem
  5740. || (category==hFilesListItem && !firstLine.isEmpty()
  5741. && firstLine[0]!='|' && firstLine[0]!=';')) {
  5742. QString indent=doc->line(line);
  5743. // Only if the line was all whitespace, otherwise wait for Enter to be
  5744. // pressed (prevents annoying the user while typing a string or something).
  5745. if (indent.contains(QRegExp("^\\s*\\{$"))) {
  5746. indent=indent.remove('{');
  5747. QString cursorLine=indent+"\t";
  5748. doc->startEditing();
  5749. doc->insertLine(line+1,cursorLine);
  5750. doc->insertLine(line+2,indent+"}");
  5751. doc->endEditing();
  5752. view->setCursorPosition(KTextEditor::Cursor(line+1,cursorLine.length()));
  5753. }
  5754. }
  5755. }
  5756. if (IS_FILE(currentListItem)
  5757. && view==static_cast<ListViewFile *>(currentListItem)->kateView
  5758. && text=="(") {
  5759. QString firstLine=view->document()->line(0);
  5760. CATEGORY_OF(category,currentListItem);
  5761. // Completion only operates on C files.
  5762. if (category==cFilesListItem || category==qllFilesListItem
  5763. || (category==hFilesListItem && !firstLine.isEmpty()
  5764. && firstLine[0]!='|' && firstLine[0]!=';')) {
  5765. new ArgHintPopup(view,pathInProject(currentListItem),this);
  5766. }
  5767. }
  5768. }
  5769. void MainForm::current_view_newLineHook()
  5770. {
  5771. int line,col;
  5772. CURRENT_VIEW->cursorPosition().position(line,col);
  5773. KTextEditor::Document *doc=CURRENT_VIEW->document();
  5774. if (preferences.autoBlocks && line && doc->line(line-1).endsWith("{")) {
  5775. CATEGORY_OF(category,currentListItem);
  5776. QString firstLine=doc->line(0);
  5777. // Only for C files.
  5778. if (category==cFilesListItem || category==qllFilesListItem
  5779. || (category==hFilesListItem && !firstLine.isEmpty()
  5780. && firstLine[0]!='|' && firstLine[0]!=';')) {
  5781. QString indent=doc->line(line-1);
  5782. // Remove everything starting from the first non-whitespace character.
  5783. indent=indent.remove(QRegExp("(?!\\s).*$"));
  5784. QString cursorLine=indent+"\t";
  5785. doc->startEditing();
  5786. doc->removeText(KTextEditor::Range(line,0,line,col));
  5787. doc->insertLine(line,cursorLine);
  5788. doc->insertText(KTextEditor::Cursor(line+1,0),indent+"}");
  5789. doc->endEditing();
  5790. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(line,cursorLine.length()));
  5791. }
  5792. }
  5793. }
  5794. void MainForm::clipboard_dataChanged()
  5795. {
  5796. if (CURRENT_VIEW) {
  5797. editPasteAction->setEnabled(!clipboard->text().isNull());
  5798. shortcuts[4]->setEnabled(!clipboard->text().isNull());
  5799. }
  5800. }
  5801. void MainForm::fileTreeItemRenamed( Q3ListViewItem *item, const QString &newName, int col)
  5802. {
  5803. if (col)
  5804. return;
  5805. if (item==rootListItem) {
  5806. // validate name, fix if invalid
  5807. QVector<QChar> validInVarname;
  5808. #define V(i) validInVarname.append(QChar(i))
  5809. #define VR(m,n) for(unsigned i=m;i<=n;i++)V(i)
  5810. VR(48,57); // 0..9
  5811. VR(65,90); // A..Z
  5812. V(95); // _
  5813. VR(97,122); // a..z
  5814. V(181); // mu
  5815. VR(192,214); // À..Ö
  5816. VR(216,246); // Ø..ö
  5817. VR(248,255); // ø..ÿ
  5818. VR(0x3b1,0x3b6);V(0x3b8);V(0x3bb);V(0x3be);V(0x3c1);V(0x3c3);V(0x3c4);
  5819. V(0x3c6);V(0x3c8);V(0x3c9); // small Greek letters
  5820. V(0x393);V(0x394);V(0x3a0);V(0x3a3);V(0x3a9); // capital Greek letters
  5821. #undef VR
  5822. #undef V
  5823. bool hasFolder=false;
  5824. int i;
  5825. QString prjName=newName;
  5826. for (i=prjName.length();i>=0;i--) {
  5827. if (prjName[i]=='\\') {
  5828. if (hasFolder)
  5829. prjName.remove(i,1);
  5830. else
  5831. hasFolder=true;
  5832. } else if (!validInVarname.contains(prjName[i]))
  5833. prjName.remove(i,1);
  5834. }
  5835. if (!prjName.isEmpty() && prjName[0]=='\\') prjName.remove(0,1);
  5836. if (prjName.isEmpty()) prjName="Project1";
  5837. if ((prjName[0]>='0'&&prjName[0]<='9')||prjName[0]=='_')
  5838. prjName.prepend('X');
  5839. i=prjName.find('\\');
  5840. if (i>=0) {
  5841. if (i>8) {
  5842. prjName.remove(8,i-8);
  5843. i=8;
  5844. }
  5845. if ((prjName[i+1]>='0'&&prjName[i+1]<='9')||prjName[i+1]=='_')
  5846. prjName.insert(i+1,'X');
  5847. prjName.truncate(i+9);
  5848. if (prjName.length()==i+1) prjName.append("Project1");
  5849. } else prjName.truncate(8);
  5850. item->setText(0,prjName);
  5851. projectIsDirty=true;
  5852. projectNeedsRelink=TRUE;
  5853. return;
  5854. }
  5855. if (!IS_FILE(item))
  5856. return;
  5857. ListViewFile *theFile=static_cast<ListViewFile *>(item);
  5858. QString suffix;
  5859. QString oldLabel;
  5860. QString &fileNameRef=theFile->fileName;
  5861. QString oldFileName=fileNameRef;
  5862. QString newFileName=fileNameRef;
  5863. int o,s;
  5864. o=oldFileName.findRev('.');
  5865. s=oldFileName.findRev('/');
  5866. if (o>=0&&(s<0||o>s)) {
  5867. suffix=oldFileName.mid(o+1);
  5868. newFileName.truncate(o);
  5869. } else {
  5870. suffix=QString::null;
  5871. }
  5872. if (s>=0) {
  5873. oldLabel=newFileName.mid(s+1);
  5874. newFileName.truncate(s+1);
  5875. } else {
  5876. oldLabel=newFileName;
  5877. newFileName.truncate(0);
  5878. }
  5879. if (!oldLabel.compare(newName))
  5880. return; //no changes are needed, and we don't want it to complain about the file conflicting with itself!
  5881. newFileName+=newName;
  5882. newFileName+='.';
  5883. newFileName+=suffix;
  5884. if (checkFileName(newFileName,extractAllFileNames())) {
  5885. CATEGORY_OF(category,item);
  5886. if (IS_EDITABLE_CATEGORY(category)) {
  5887. if (!oldFileName.isEmpty() && oldFileName[0]=='/')
  5888. KDirWatch::self()->removeFile(oldFileName);
  5889. if (newFileName.isEmpty() || newFileName[0]!='/')
  5890. newFileName.prepend(QFileInfo(projectFileName).absolutePath()+"/");
  5891. mkdir_multi(newFileName);
  5892. if (!theFile->kateView->document()->saveAs(newFileName)) {
  5893. KMessageBox::error(this,"Failed to rename the file.");
  5894. theFile->setText(0,oldLabel);
  5895. if (!oldFileName.isEmpty() && oldFileName[0]=='/')
  5896. KDirWatch::self()->addFile(oldFileName);
  5897. } else {
  5898. if (!theFile->isNew && !oldFileName.isEmpty() && oldFileName[0]=='/')
  5899. QDir().remove(oldFileName);
  5900. fileNameRef=newFileName;
  5901. KDirWatch::self()->addFile(newFileName);
  5902. removeTrailingSpacesFromView(theFile->kateView);
  5903. theFile->kateView->document()->setModified(FALSE);
  5904. theFile->isNew=FALSE;
  5905. projectIsDirty=TRUE;
  5906. projectNeedsRelink=TRUE;
  5907. }
  5908. } else {
  5909. mkdir_multi(newFileName);
  5910. if (!moveFile(oldFileName,newFileName)) {
  5911. KMessageBox::error(this,"Failed to rename the file.");
  5912. theFile->setText(0,oldLabel);
  5913. } else {
  5914. fileNameRef=newFileName;
  5915. projectIsDirty=TRUE;
  5916. projectNeedsRelink=TRUE;
  5917. }
  5918. }
  5919. } else {
  5920. KMessageBox::error(this,"The name you chose conflicts with that of another file.");
  5921. theFile->setText(0,oldLabel);
  5922. }
  5923. updateRightStatusLabel();
  5924. }
  5925. void MainForm::closeEvent(QCloseEvent *e)
  5926. {
  5927. if (compiling || savePrompt())
  5928. e->ignore();
  5929. else {
  5930. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  5931. if (sourceFile->savePrompt()) {
  5932. e->ignore();
  5933. return;
  5934. }
  5935. }
  5936. clearProject();
  5937. e->accept();
  5938. }
  5939. }
  5940. void MainForm::KDirWatch_dirty(const QString &fileName)
  5941. {
  5942. Q3ListViewItem *item=rootListItem->firstChild(),*next;
  5943. QStringList allFiles;
  5944. while (item) {
  5945. if (IS_FOLDER(item)) {
  5946. next=item->firstChild();
  5947. if (next) {
  5948. item=next;
  5949. continue;
  5950. }
  5951. }
  5952. if (IS_FILE(item)) {
  5953. if (!fileName.compare(static_cast<ListViewFile *>(item)->fileName)) {
  5954. CATEGORY_OF(category,item);
  5955. if (!IS_EDITABLE_CATEGORY(category)) {
  5956. qWarning("KDirWatch_dirty called for non-editable file");
  5957. return;
  5958. }
  5959. if (KMessageBox::questionYesNo(this,
  5960. QString("The file \'%1\' has been changed by another program. "
  5961. "Do you want to reload it?").arg(fileName),"File Changed")
  5962. ==KMessageBox::Yes) {
  5963. static_cast<ListViewFile *>(item)->isNew=FALSE;
  5964. static_cast<ListViewFile *>(item)->kateView->document()->setModified(FALSE);
  5965. disableViewEvents=TRUE;
  5966. static_cast<ListViewFile *>(item)->kateView->document()->documentReload();
  5967. disableViewEvents=FALSE;
  5968. updateRightStatusLabel();
  5969. }
  5970. return;
  5971. }
  5972. }
  5973. next=item->nextSibling();
  5974. while (!next) {
  5975. next=item->parent();
  5976. if (next==rootListItem||!next) {
  5977. return;
  5978. }
  5979. item=next;
  5980. next=item->nextSibling();
  5981. }
  5982. item=next;
  5983. }
  5984. return;
  5985. }
  5986. QString MainForm::pathInProject(Q3ListViewItem *item)
  5987. {
  5988. QString path=QFileInfo(static_cast<ListViewFile *>(item)->fileName).fileName();
  5989. item=item->parent();
  5990. while (!IS_CATEGORY(item)) {
  5991. path.prepend('/');
  5992. path.prepend(item->text(0));
  5993. item=item->parent();
  5994. }
  5995. return path;
  5996. }
  5997. QString MainForm::textForHeader(const QString &fileName)
  5998. {
  5999. QString name=fileName;
  6000. int pos;
  6001. Q3ListViewItem *item=hFilesListItem;
  6002. while ((pos=name.find('/'))>=0) {
  6003. QString folder=name.left(pos);
  6004. name.remove(0,pos+1);
  6005. for (item=item->firstChild();item;item=item->nextSibling()) {
  6006. if (IS_FOLDER(item)) {
  6007. if (item->text(0)==folder) break;
  6008. }
  6009. }
  6010. if (!item) return QString::null;
  6011. }
  6012. for (item=item->firstChild();item;item=item->nextSibling()) {
  6013. if (IS_FILE(item)) {
  6014. ListViewFile *fileItem=static_cast<ListViewFile *>(item);
  6015. if (QFileInfo(fileItem->fileName).fileName()==name)
  6016. return fileItem->kateView->document()->text();
  6017. }
  6018. }
  6019. return QString::null;
  6020. }
  6021. void MainForm::languageChange()
  6022. {
  6023. retranslateUi(this);
  6024. }