mainform.cpp 231 KB

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