mainform.cpp 241 KB

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