mainform.cpp 241 KB

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