mainform.cpp 238 KB

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