FlatCAMApp.py 378 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. import threading
  14. from stat import S_IREAD, S_IRGRP, S_IROTH
  15. import subprocess
  16. import tkinter as tk
  17. from PyQt5 import QtPrintSupport
  18. import urllib.request, urllib.parse, urllib.error
  19. from contextlib import contextmanager
  20. import gc
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. # #######################################
  23. # # Imports part of FlatCAM ##
  24. # #######################################
  25. from ObjectCollection import *
  26. from FlatCAMObj import *
  27. from flatcamGUI.PlotCanvas import *
  28. from flatcamGUI.FlatCAMGUI import *
  29. from FlatCAMCommon import LoudDict
  30. from FlatCAMPostProc import load_postprocessors
  31. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  32. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  33. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  34. from FlatCAMProcess import *
  35. from FlatCAMWorkerStack import WorkerStack
  36. from flatcamGUI.VisPyVisuals import Color
  37. from vispy.gloo.util import _screenshot
  38. from vispy.io import write_png
  39. from flatcamTools import *
  40. from multiprocessing import Pool
  41. import tclCommands
  42. import gettext
  43. import FlatCAMTranslation as fcTranslate
  44. import builtins
  45. fcTranslate.apply_language('strings')
  46. if '_' not in builtins.__dict__:
  47. _ = gettext.gettext
  48. # #######################################
  49. # # App ##
  50. # #######################################
  51. class App(QtCore.QObject):
  52. """
  53. The main application class. The constructor starts the GUI.
  54. """
  55. # Get Cmd Line Options
  56. cmd_line_shellfile = ''
  57. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  58. try:
  59. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  60. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  61. except getopt.GetoptError:
  62. print(cmd_line_help)
  63. sys.exit(2)
  64. for opt, arg in cmd_line_options:
  65. if opt == '-h':
  66. print(cmd_line_help)
  67. sys.exit()
  68. elif opt == '--shellfile':
  69. cmd_line_shellfile = arg
  70. # Logging ##
  71. log = logging.getLogger('base')
  72. log.setLevel(logging.DEBUG)
  73. # log.setLevel(logging.WARNING)
  74. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  75. handler = logging.StreamHandler()
  76. handler.setFormatter(formatter)
  77. log.addHandler(handler)
  78. # Version
  79. version = 8.917
  80. version_date = "2019/05/22"
  81. beta = True
  82. # current date now
  83. date = str(datetime.today()).rpartition('.')[0]
  84. date = ''.join(c for c in date if c not in ':-')
  85. date = date.replace(' ', '_')
  86. # URL for update checks and statistics
  87. version_url = "http://flatcam.org/version"
  88. # App URL
  89. app_url = "http://flatcam.org"
  90. # Manual URL
  91. manual_url = "http://flatcam.org/manual/index.html"
  92. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  93. # this variable will hold the project status
  94. # if True it will mean that the project was modified and not saved
  95. should_we_save = False
  96. # flag is True if saving action has been triggered
  97. save_in_progress = False
  98. # #################
  99. # # Signals ##
  100. # #################
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. app_quit = QtCore.pyqtSignal()
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added or deleted from/to the collection
  132. object_status_changed = QtCore.pyqtSignal(object, str)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. self.main_thread = QtWidgets.QApplication.instance().thread()
  149. # ##################
  150. # ## OS-specific ###
  151. # ##################
  152. # Folder for user settings.
  153. if sys.platform == 'win32':
  154. from win32com.shell import shell, shellcon
  155. if platform.architecture()[0] == '32bit':
  156. App.log.debug("Win32!")
  157. else:
  158. App.log.debug("Win64!")
  159. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  160. self.os = 'windows'
  161. else: # Linux/Unix/MacOS
  162. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  163. self.os = 'unix'
  164. # ##############################
  165. # ## Setup folders and files ###
  166. # ##############################
  167. if not os.path.exists(self.data_path):
  168. os.makedirs(self.data_path)
  169. App.log.debug('Created data folder: ' + self.data_path)
  170. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  171. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  172. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  173. if not os.path.exists(self.postprocessorpaths):
  174. os.makedirs(self.postprocessorpaths)
  175. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  176. # create current_defaults.FlatConfig file if there is none
  177. try:
  178. f = open(self.data_path + '/current_defaults.FlatConfig')
  179. f.close()
  180. except IOError:
  181. App.log.debug('Creating empty current_defaults.FlatConfig')
  182. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  183. json.dump({}, f)
  184. f.close()
  185. # create factory_defaults.FlatConfig file if there is none
  186. try:
  187. f = open(self.data_path + '/factory_defaults.FlatConfig')
  188. f.close()
  189. except IOError:
  190. App.log.debug('Creating empty factory_defaults.FlatConfig')
  191. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  192. json.dump({}, f)
  193. f.close()
  194. try:
  195. f = open(self.data_path + '/recent.json')
  196. f.close()
  197. except IOError:
  198. App.log.debug('Creating empty recent.json')
  199. f = open(self.data_path + '/recent.json', 'w')
  200. json.dump([], f)
  201. f.close()
  202. # Application directory. CHDIR to it. Otherwise, trying to load
  203. # GUI icons will fail as their path is relative.
  204. # This will fail under cx_freeze ...
  205. self.app_home = os.path.dirname(os.path.realpath(__file__))
  206. App.log.debug("Application path is " + self.app_home)
  207. App.log.debug("Started in " + os.getcwd())
  208. # cx_freeze workaround
  209. if os.path.isfile(self.app_home):
  210. self.app_home = os.path.dirname(self.app_home)
  211. os.chdir(self.app_home)
  212. # Create multiprocessing pool
  213. self.pool = Pool()
  214. # variable to store mouse coordinates
  215. self.mouse = [0, 0]
  216. # ###################
  217. # # Initialize GUI ##
  218. # ###################
  219. # FlatCAM colors used in plotting
  220. self.FC_light_green = '#BBF268BF'
  221. self.FC_dark_green = '#006E20BF'
  222. self.FC_light_blue = '#a5a5ffbf'
  223. self.FC_dark_blue = '#0000ffbf'
  224. QtCore.QObject.__init__(self)
  225. self.ui = FlatCAMGUI(self.version, self.beta, self)
  226. # self.connect(self.ui,
  227. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  228. # self.save_geometry) PyQt4
  229. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  230. self.ui.final_save.connect(self.final_save)
  231. # #############
  232. # ### Data ####
  233. # #############
  234. self.recent = []
  235. self.clipboard = QtWidgets.QApplication.clipboard()
  236. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  237. self.project_filename = None
  238. self.toggle_units_ignore = False
  239. # self.defaults_form = PreferencesUI()
  240. # when adding entries here read the comments in the method found bellow named:
  241. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  242. self.defaults_form_fields = {
  243. # General App
  244. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  245. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  246. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  247. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  248. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  249. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  250. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  251. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  252. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  253. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  254. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  255. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  256. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  257. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  258. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  259. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  260. # General GUI Preferences
  261. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  262. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  263. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  264. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  265. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  266. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  267. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  268. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  269. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  270. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  271. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  272. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  273. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  274. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  275. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  276. # General GUI Settings
  277. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  278. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  279. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  280. # Gerber General
  281. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  282. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  283. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  284. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  285. # Gerber Options
  286. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  287. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  288. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  289. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  290. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  291. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  292. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  293. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  294. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  295. # Gerber Advanced Options
  296. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  297. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  298. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  299. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  300. # Gerber Export
  301. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  302. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  303. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  304. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  305. # Gerber Editor
  306. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  307. # Excellon General
  308. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  309. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  310. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  311. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  312. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  313. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  314. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  315. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  316. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  317. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  318. # Excellon Options
  319. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  320. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  321. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  322. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  323. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  324. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  325. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  326. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  327. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  328. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  329. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  330. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  331. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  332. # Excellon Advanced Options
  333. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  334. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  335. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  336. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  337. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  338. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  339. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  340. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  341. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  342. # Excellon Export
  343. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  344. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  345. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  346. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  347. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  348. # Geometry General
  349. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  350. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  351. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  352. # Geometry Options
  353. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  354. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  355. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  356. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  357. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  358. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  359. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  360. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  361. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  362. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  363. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  364. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  365. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  366. # Geometry Advanced Options
  367. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  368. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  369. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  370. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  371. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  372. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  373. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  374. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  375. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  376. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  377. # Geometry Editor
  378. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  379. # CNCJob General
  380. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  381. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  382. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  383. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  384. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  385. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  386. # CNC Job Options
  387. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  388. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  389. # CNC Job Advanced Options
  390. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  391. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  392. # NCC Tool
  393. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  394. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  395. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  396. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  397. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  398. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  399. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  400. # CutOut Tool
  401. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  402. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  403. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  404. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  405. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  406. # Paint Area Tool
  407. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  408. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  409. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  410. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  411. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  412. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  413. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  414. # 2-sided Tool
  415. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  416. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  417. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  418. # Film Tool
  419. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  420. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  421. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  422. # Panelize Tool
  423. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  424. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  425. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  426. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  427. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  428. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  429. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  430. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  431. # Calculators Tool
  432. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  433. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  434. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  435. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  436. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  437. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  438. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  439. # Transformations Tool
  440. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  441. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  442. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  443. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  444. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  445. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  446. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  447. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  448. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  449. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  450. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  451. # SolderPaste Dispensing Tool
  452. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  453. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  454. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  455. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  456. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  457. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  458. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  459. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  460. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  461. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  462. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  463. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  464. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  465. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  466. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  467. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  468. }
  469. # ############################
  470. # ### LOAD POSTPROCESSORS ####
  471. # ############################
  472. self.postprocessors = load_postprocessors(self)
  473. for name in list(self.postprocessors.keys()):
  474. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  475. if name.partition('_')[0] == 'Paste':
  476. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  477. continue
  478. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  479. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  480. if name == 'hpgl':
  481. continue
  482. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  483. # ############################
  484. # ### LOAD LANGUAGES ####
  485. # ############################
  486. self.languages = fcTranslate.load_languages()
  487. for name in sorted(self.languages.values()):
  488. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  489. self.defaults = LoudDict()
  490. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  491. self.defaults.update({
  492. # Global APP Preferences
  493. "global_serial": 0,
  494. "global_stats": {},
  495. "units": "IN",
  496. "global_app_level": 'b',
  497. "global_language": 'English',
  498. "global_version_check": True,
  499. "global_send_stats": True,
  500. "global_pan_button": '2',
  501. "global_mselect_key": 'Control',
  502. "global_project_at_startup": False,
  503. "global_project_autohide": True,
  504. "global_toggle_tooltips": True,
  505. "global_worker_number": 2,
  506. "global_tolerance": 0.01,
  507. "global_open_style": True,
  508. "global_compression_level": 3,
  509. "global_save_compressed": True,
  510. # Global GUI Preferences
  511. "global_gridx": 0.0393701,
  512. "global_gridy": 0.0393701,
  513. "global_snap_max": 0.001968504,
  514. "global_workspace": False,
  515. "global_workspaceT": "A4P",
  516. "global_grid_context_menu": {
  517. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  518. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  519. },
  520. "global_plot_fill": '#BBF268BF',
  521. "global_plot_line": '#006E20BF',
  522. "global_sel_fill": '#a5a5ffbf',
  523. "global_sel_line": '#0000ffbf',
  524. "global_alt_sel_fill": '#BBF268BF',
  525. "global_alt_sel_line": '#006E20BF',
  526. "global_draw_color": '#FF0000',
  527. "global_sel_draw_color": '#0000FF',
  528. "global_proj_item_color": '#000000',
  529. "global_proj_item_dis_color": '#b7b7cb',
  530. "global_toolbar_view": 511,
  531. "global_background_timeout": 300000, # Default value is 5 minutes
  532. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  533. # (python trace only for unknown errors),
  534. # 1 = show trace(show trace always),
  535. # 2 = (For the future).
  536. # Persistence
  537. "global_last_folder": None,
  538. "global_last_save_folder": None,
  539. # Default window geometry
  540. "global_def_win_x": 100,
  541. "global_def_win_y": 100,
  542. "global_def_win_w": 1024,
  543. "global_def_win_h": 650,
  544. "global_def_notebook_width": 1,
  545. # Constants...
  546. "global_defaults_save_period_ms": 20000, # Time between default saves.
  547. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  548. "global_shell_at_startup": False, # Show the shell at startup.
  549. "global_recent_limit": 10, # Max. items in recent list.
  550. "fit_key": 'V',
  551. "zoom_out_key": '-',
  552. "zoom_in_key": '=',
  553. "grid_toggle_key": 'G',
  554. "zoom_ratio": 1.5,
  555. "global_point_clipboard_format": "(%.4f, %.4f)",
  556. "global_zdownrate": None,
  557. # General GUI Settings
  558. "global_hover": False,
  559. "global_selection_shape": True,
  560. "global_layout": "compact",
  561. # Gerber General
  562. "gerber_plot": True,
  563. "gerber_solid": True,
  564. "gerber_multicolored": False,
  565. "gerber_isotooldia": 0.016,
  566. "gerber_isopasses": 1,
  567. "gerber_isooverlap": 0.15,
  568. # Gerber Options
  569. "gerber_combine_passes": False,
  570. "gerber_milling_type": "cl",
  571. "gerber_noncoppermargin": 0.1,
  572. "gerber_noncopperrounded": False,
  573. "gerber_bboxmargin": 0.1,
  574. "gerber_bboxrounded": False,
  575. "gerber_circle_steps": 128,
  576. "gerber_use_buffer_for_union": True,
  577. # Gerber Advanced Options
  578. "gerber_aperture_display": False,
  579. "gerber_aperture_scale_factor": 1.0,
  580. "gerber_aperture_buffer_factor": 0.0,
  581. "gerber_follow": False,
  582. # Gerber Export
  583. "gerber_exp_units": 'IN',
  584. "gerber_exp_integer": 2,
  585. "gerber_exp_decimals": 4,
  586. "gerber_exp_zeros": 'L',
  587. # Gerber Editor
  588. "gerber_editor_sel_limit": 30,
  589. # Excellon General
  590. "excellon_plot": True,
  591. "excellon_solid": True,
  592. "excellon_format_upper_in": 2,
  593. "excellon_format_lower_in": 4,
  594. "excellon_format_upper_mm": 3,
  595. "excellon_format_lower_mm": 3,
  596. "excellon_zeros": "L",
  597. "excellon_units": "INCH",
  598. "excellon_optimization_type": 'B',
  599. "excellon_search_time": 3,
  600. # Excellon Options
  601. "excellon_drillz": -0.1,
  602. "excellon_travelz": 0.1,
  603. "excellon_feedrate": 3.0,
  604. "excellon_spindlespeed": None,
  605. "excellon_spindledir": 'CW',
  606. "excellon_dwell": False,
  607. "excellon_dwelltime": 1,
  608. "excellon_toolchange": False,
  609. "excellon_toolchangez": 0.5,
  610. "excellon_ppname_e": 'default',
  611. "excellon_tooldia": 0.016,
  612. "excellon_slot_tooldia": 0.016,
  613. "excellon_gcode_type": "drills",
  614. # Excellon Advanced Options
  615. "excellon_offset": 0.0,
  616. "excellon_toolchangexy": "0.0, 0.0",
  617. "excellon_startz": None,
  618. "excellon_endz": 0.5,
  619. "excellon_feedrate_rapid": 3.0,
  620. "excellon_z_pdepth": -0.02,
  621. "excellon_feedrate_probe": 3.0,
  622. "excellon_f_plunge": False,
  623. "excellon_f_retract": False,
  624. # Excellon Export
  625. "excellon_exp_units": 'INCH',
  626. "excellon_exp_format": 'ndec',
  627. "excellon_exp_integer": 2,
  628. "excellon_exp_decimals": 4,
  629. "excellon_exp_zeros": 'LZ',
  630. # Geometry General
  631. "geometry_plot": True,
  632. "geometry_circle_steps": 128,
  633. "geometry_cnctooldia": 0.016,
  634. # Geometry Options
  635. "geometry_cutz": -0.002,
  636. "geometry_multidepth": False,
  637. "geometry_depthperpass": 0.002,
  638. "geometry_travelz": 0.1,
  639. "geometry_toolchange": False,
  640. "geometry_toolchangez": 0.5,
  641. "geometry_feedrate": 3.0,
  642. "geometry_feedrate_z": 3.0,
  643. "geometry_spindlespeed": None,
  644. "geometry_spindledir": 'CW',
  645. "geometry_dwell": False,
  646. "geometry_dwelltime": 1,
  647. "geometry_ppname_g": 'default',
  648. # Geometry Advanced Options
  649. "geometry_toolchangexy": "0.0, 0.0",
  650. "geometry_startz": None,
  651. "geometry_endz": 0.5,
  652. "geometry_feedrate_rapid": 3.0,
  653. "geometry_extracut": False,
  654. "geometry_z_pdepth": -0.02,
  655. "geometry_f_plunge": False,
  656. "geometry_feedrate_probe": 3.0,
  657. "geometry_segx": 0.0,
  658. "geometry_segy": 0.0,
  659. # Geometry Editor
  660. "geometry_editor_sel_limit": 30,
  661. # CNC Job General
  662. "cncjob_plot": True,
  663. "cncjob_plot_kind": 'all',
  664. "cncjob_tooldia": 0.0393701,
  665. "cncjob_coords_decimals": 4,
  666. "cncjob_fr_decimals": 2,
  667. "cncjob_steps_per_circle": 64,
  668. # CNC Job Options
  669. "cncjob_prepend": "",
  670. "cncjob_append": "",
  671. # CNC Job Advanced Options
  672. "cncjob_toolchange_macro": "",
  673. "cncjob_toolchange_macro_enable": False,
  674. "tools_ncctools": "0.0393701, 0.019685",
  675. "tools_nccoverlap": 0.015748,
  676. "tools_nccmargin": 0.00393701,
  677. "tools_nccmethod": "seed",
  678. "tools_nccconnect": True,
  679. "tools_ncccontour": True,
  680. "tools_nccrest": False,
  681. "tools_cutouttooldia": 0.00393701,
  682. "tools_cutoutmargin": 0.00393701,
  683. "tools_cutoutgapsize": 0.005905512,
  684. "tools_gaps_ff": "8",
  685. "tools_cutout_convexshape": False,
  686. "tools_painttooldia": 0.07,
  687. "tools_paintoverlap": 0.15,
  688. "tools_paintmargin": 0.0,
  689. "tools_paintmethod": "seed",
  690. "tools_selectmethod": "single",
  691. "tools_pathconnect": True,
  692. "tools_paintcontour": True,
  693. "tools_2sided_mirror_axis": "X",
  694. "tools_2sided_axis_loc": "point",
  695. "tools_2sided_drilldia": 0.0393701,
  696. "tools_film_type": 'neg',
  697. "tools_film_boundary": 0.0393701,
  698. "tools_film_scale": 0,
  699. "tools_panelize_spacing_columns": 0,
  700. "tools_panelize_spacing_rows": 0,
  701. "tools_panelize_columns": 1,
  702. "tools_panelize_rows": 1,
  703. "tools_panelize_constrain": False,
  704. "tools_panelize_constrainx": 0.0,
  705. "tools_panelize_constrainy": 0.0,
  706. "tools_panelize_panel_type": 'gerber',
  707. "tools_calc_vshape_tip_dia": 0.007874,
  708. "tools_calc_vshape_tip_angle": 30,
  709. "tools_calc_vshape_cut_z": 0.000787,
  710. "tools_calc_electro_length": 10.0,
  711. "tools_calc_electro_width": 10.0,
  712. "tools_calc_electro_cdensity":13.0,
  713. "tools_calc_electro_growth": 10.0,
  714. "tools_transform_rotate": 90,
  715. "tools_transform_skew_x": 0.0,
  716. "tools_transform_skew_y": 0.0,
  717. "tools_transform_scale_x": 1.0,
  718. "tools_transform_scale_y": 1.0,
  719. "tools_transform_scale_link": True,
  720. "tools_transform_scale_reference": True,
  721. "tools_transform_offset_x": 0.0,
  722. "tools_transform_offset_y": 0.0,
  723. "tools_transform_mirror_reference": False,
  724. "tools_transform_mirror_point": (0, 0),
  725. "tools_solderpaste_tools": "0.0393701, 0.011811",
  726. "tools_solderpaste_new": 0.011811,
  727. "tools_solderpaste_z_start": 0.00019685039,
  728. "tools_solderpaste_z_dispense": 0.00393701,
  729. "tools_solderpaste_z_stop": 0.00019685039,
  730. "tools_solderpaste_z_travel": 0.00393701,
  731. "tools_solderpaste_z_toolchange": 0.0393701,
  732. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  733. "tools_solderpaste_frxy": 3.0,
  734. "tools_solderpaste_frz": 3.0,
  735. "tools_solderpaste_frz_dispense": 0.0393701,
  736. "tools_solderpaste_speedfwd": 20,
  737. "tools_solderpaste_dwellfwd": 1,
  738. "tools_solderpaste_speedrev": 10,
  739. "tools_solderpaste_dwellrev": 1,
  740. "tools_solderpaste_pp": 'Paste_1'
  741. })
  742. # ##############################
  743. # ## Load defaults from file ###
  744. # ##############################
  745. if user_defaults:
  746. self.load_defaults(filename='current_defaults')
  747. # ###########################
  748. # #### APPLY APP LANGUAGE ###
  749. # ###########################
  750. ret_val = fcTranslate.apply_language('strings')
  751. if ret_val == "no language":
  752. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  753. log.debug("Could not find the Language files. The App strings are missing.")
  754. else:
  755. # make the current language the current selection on the language combobox
  756. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  757. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  758. # ##################################
  759. # ## CREATE UNIQUE SERIAL NUMBER ###
  760. # ##################################
  761. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  762. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  763. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  764. self.save_defaults(silent=True)
  765. self.propagate_defaults(silent=True)
  766. self.restore_main_win_geom()
  767. def auto_save_defaults():
  768. try:
  769. self.save_defaults(silent=True)
  770. self.propagate_defaults(silent=True)
  771. finally:
  772. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  773. # the following lines activates automatic defaults save
  774. # if user_defaults:
  775. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  776. # self.options_form = PreferencesUI()
  777. self.options_form_fields = {
  778. "units": self.ui.general_options_form.general_app_group.units_radio,
  779. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  780. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  781. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  782. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  783. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  784. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  785. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  786. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  787. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  788. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  789. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  790. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  791. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  792. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  793. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  794. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  795. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  796. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  797. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  798. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  799. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  800. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  801. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  802. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  803. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  804. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  805. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  806. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  807. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  808. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  809. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  810. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  811. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  812. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  813. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  814. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  815. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  816. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  817. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  818. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  819. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  820. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  821. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  822. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  823. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  824. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  825. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  826. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  827. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  828. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  829. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  830. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  831. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  832. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  833. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  834. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  835. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  836. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  837. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  838. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  839. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  840. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  841. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  842. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  843. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  844. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  845. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  846. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  847. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  848. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  849. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  850. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  851. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  852. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  853. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  854. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  855. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  856. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  857. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  858. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  859. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  860. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  861. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  862. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  863. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  864. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  865. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  866. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  867. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  868. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  869. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  870. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  871. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  872. }
  873. for name in list(self.postprocessors.keys()):
  874. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  875. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  876. self.options = LoudDict()
  877. self.options.set_change_callback(self.on_options_dict_change)
  878. self.options.update({
  879. "units": "IN",
  880. "global_gridx": 1.0,
  881. "global_gridy": 1.0,
  882. "global_snap_max": 0.05,
  883. "global_background_timeout": 300000, # Default value is 5 minutes
  884. "global_verbose_error_level": 0, # Shell verbosity:
  885. # 0 = default(python trace only for unknown errors),
  886. # 1 = show trace(show trace allways), 2 = (For the future).
  887. "gerber_plot": True,
  888. "gerber_solid": True,
  889. "gerber_multicolored": False,
  890. "gerber_isotooldia": 0.016,
  891. "gerber_isopasses": 1,
  892. "gerber_isooverlap": 0.15,
  893. "gerber_combine_passes": True,
  894. "gerber_noncoppermargin": 0.0,
  895. "gerber_noncopperrounded": False,
  896. "gerber_bboxmargin": 0.0,
  897. "gerber_bboxrounded": False,
  898. "excellon_plot": True,
  899. "excellon_solid": False,
  900. "excellon_format_upper_in": 2,
  901. "excellon_format_lower_in": 4,
  902. "excellon_format_upper_mm": 3,
  903. "excellon_format_lower_mm": 3,
  904. "excellon_units": 'INCH',
  905. "excellon_optimization_type": 'B',
  906. "excellon_search_time": 3,
  907. "excellon_zeros": "L",
  908. "excellon_drillz": -0.1,
  909. "excellon_travelz": 0.1,
  910. "excellon_feedrate": 3.0,
  911. "excellon_feedrate_rapid": 3.0,
  912. "excellon_spindlespeed": None,
  913. "excellon_spindledir": 'CW',
  914. "excellon_dwell": True,
  915. "excellon_dwelltime": 1000,
  916. "excellon_toolchange": False,
  917. "excellon_toolchangez": 1.0,
  918. "excellon_toolchangexy": "0.0, 0.0",
  919. "excellon_tooldia": 0.016,
  920. "excellon_ppname_e": 'default',
  921. "excellon_f_plunge": False,
  922. "excellon_startz": None,
  923. "excellon_endz": 2.0,
  924. "geometry_plot": True,
  925. "geometry_segx": 0.0,
  926. "geometry_segy": 0.0,
  927. "geometry_cutz": -0.002,
  928. "geometry_travelz": 0.1,
  929. "geometry_feedrate": 3.0,
  930. "geometry_feedrate_z": 3.0,
  931. "geometry_feedrate_rapid": 3.0,
  932. "geometry_spindlespeed": None,
  933. "geometry_spindledir": 'CW',
  934. "geometry_dwell": True,
  935. "geometry_dwelltime": 1000,
  936. "geometry_cnctooldia": 0.016,
  937. "geometry_toolchange": False,
  938. "geometry_toolchangez": 2.0,
  939. "geometry_toolchangexy": "0.0, 0.0",
  940. "geometry_startz": None,
  941. "geometry_endz": 2.0,
  942. "geometry_ppname_g": "default",
  943. "geometry_f_plunge": False,
  944. "geometry_depthperpass": 0.002,
  945. "geometry_multidepth": False,
  946. "geometry_extracut": False,
  947. "cncjob_plot": True,
  948. "cncjob_tooldia": 0.016,
  949. "cncjob_prepend": "",
  950. "cncjob_append": "",
  951. "tools_ncctools": "1.0, 0.5",
  952. "tools_nccoverlap": 0.4,
  953. "tools_nccmargin": 1,
  954. "tools_cutouttooldia": 0.07,
  955. "tools_cutoutmargin": 0.1,
  956. "tools_cutoutgapsize": 0.15,
  957. "tools_gaps_ff": "8",
  958. "tools_painttooldia": 0.07,
  959. "tools_paintoverlap": 0.15,
  960. "tools_paintmargin": 0.0,
  961. "tools_paintmethod": "seed",
  962. "tools_selectmethod": "single",
  963. "tools_pathconnect": True,
  964. "tools_paintcontour": True,
  965. "tools_2sided_mirror_axis": "X",
  966. "tools_2sided_axis_loc": 'point',
  967. "tools_2sided_drilldia": 1,
  968. "tools_film_type": 'neg',
  969. "tools_film_boundary": 1,
  970. "tools_film_scale": 0,
  971. "tools_panelize_spacing_columns": 0,
  972. "tools_panelize_spacing_rows": 0,
  973. "tools_panelize_columns": 1,
  974. "tools_panelize_rows": 1,
  975. "tools_panelize_constrain": False,
  976. "tools_panelize_constrainx": 0.0,
  977. "tools_panelize_constrainy": 0.0
  978. })
  979. self.options.update(self.defaults) # Copy app defaults to project options
  980. self.gen_form = None
  981. self.ger_form = None
  982. self.exc_form = None
  983. self.geo_form = None
  984. self.cnc_form = None
  985. self.tools_form = None
  986. self.on_options_combo_change(0) # Will show the initial form
  987. # ## Define OBJECT COLLECTION ###
  988. self.collection = ObjectCollection(self)
  989. self.ui.project_tab_layout.addWidget(self.collection.view)
  990. # ##
  991. self.log.debug("Finished creating Object Collection.")
  992. # ## Initialize the color box's color in Preferences -> Global -> Color
  993. # Init Plot Colors
  994. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  995. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  996. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  997. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  998. int(self.defaults['global_plot_fill'][7:9], 16))
  999. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1000. int(self.defaults['global_plot_fill'][7:9], 16))
  1001. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1002. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1003. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1004. # Init Left-Right Selection colors
  1005. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1006. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1007. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1008. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1009. int(self.defaults['global_sel_fill'][7:9], 16))
  1010. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1011. int(self.defaults['global_sel_fill'][7:9], 16))
  1012. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1013. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1014. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1015. # Init Right-Left Selection colors
  1016. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1017. self.defaults['global_alt_sel_fill'])
  1018. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1019. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1020. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1021. int(self.defaults['global_sel_fill'][7:9], 16))
  1022. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1023. int(self.defaults['global_sel_fill'][7:9], 16))
  1024. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1025. self.defaults['global_alt_sel_line'])
  1026. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1027. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1028. # Init Draw color and Selection Draw Color
  1029. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1030. self.defaults['global_draw_color'])
  1031. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1032. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1033. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1034. self.defaults['global_sel_draw_color'])
  1035. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1036. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1037. # Init Project Items color
  1038. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1039. self.defaults['global_proj_item_color'])
  1040. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1041. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1042. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1043. self.defaults['global_proj_item_dis_color'])
  1044. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1045. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1046. # ### End of Data ####
  1047. # ### Plot Area ####
  1048. start_plot_time = time.time() # debug
  1049. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  1050. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  1051. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  1052. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  1053. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  1054. # Keys over plot enabled
  1055. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  1056. self.ui.splitter.setStretchFactor(1, 2)
  1057. # So it can receive key presses
  1058. self.plotcanvas.vispy_canvas.native.setFocus()
  1059. self.app_cursor = self.plotcanvas.new_cursor()
  1060. self.app_cursor.enabled = False
  1061. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1062. # depending on from where those tools are called different actions can be done
  1063. self.call_source = 'app'
  1064. end_plot_time = time.time()
  1065. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1066. # ## EDITOR section
  1067. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1068. self.exc_editor = FlatCAMExcEditor(self)
  1069. self.grb_editor = FlatCAMGrbEditor(self)
  1070. # ### Adjust tabs width ####
  1071. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1072. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1073. self.collection.view.setMinimumWidth(290)
  1074. self.log.debug("Finished adding FlatCAM Editor's.")
  1075. # ### Worker ####
  1076. if self.defaults["global_worker_number"]:
  1077. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1078. else:
  1079. self.workers = WorkerStack(workers_number=2)
  1080. self.worker_task.connect(self.workers.add_task)
  1081. # ## Signal handling ###
  1082. # ## Custom signals
  1083. self.inform.connect(self.info)
  1084. self.app_quit.connect(self.quit_application)
  1085. self.message.connect(self.message_dialog)
  1086. self.progress.connect(self.set_progress_bar)
  1087. self.object_created.connect(self.on_object_created)
  1088. self.object_changed.connect(self.on_object_changed)
  1089. self.object_plotted.connect(self.on_object_plotted)
  1090. self.plots_updated.connect(self.on_plots_updated)
  1091. self.file_opened.connect(self.register_recent)
  1092. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1093. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1094. # ## Standard signals
  1095. # ## Menu
  1096. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1097. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1098. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1099. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1100. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1101. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1102. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1103. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1104. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1105. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1106. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1107. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1108. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1109. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1110. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1111. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1112. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1113. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1114. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1115. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1116. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1117. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1118. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1119. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1120. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1121. self.ui.menufile_exit.triggered.connect(self.final_save)
  1122. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1123. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1124. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1125. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1126. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1127. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1128. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1129. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1130. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1131. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1132. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1133. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1134. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1135. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1136. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1137. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1138. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1139. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1140. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1141. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1142. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1143. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1144. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1145. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1146. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1147. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1148. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1149. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1150. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1151. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1152. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1153. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1154. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1155. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1156. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1157. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1158. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1159. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1160. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1161. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1162. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1163. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1164. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1165. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1166. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1167. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1168. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1169. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1170. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1171. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1172. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1173. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1174. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1175. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1176. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1177. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1178. # ToolBar signals
  1179. self.connect_toolbar_signals()
  1180. # Context Menu
  1181. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1182. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1183. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1184. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1185. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1186. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1187. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1188. self.ui.clearplot.triggered.connect(self.clear_plots)
  1189. self.ui.replot.triggered.connect(self.plot_all)
  1190. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1191. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1192. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1193. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1194. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1195. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1196. # Preferences Plot Area TAB
  1197. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1198. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1199. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1200. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1201. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1202. # ##############################
  1203. # ## GUI PREFERENCES SIGNALS ###
  1204. # ##############################
  1205. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1206. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1207. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1208. )
  1209. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1210. lambda: self.on_toggle_units(no_pref=False))
  1211. # ##############################
  1212. # ## GUI PREFERENCES SIGNALS ###
  1213. # ##############################
  1214. # Setting plot colors signals
  1215. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1216. self.on_pf_color_entry)
  1217. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1218. self.on_pf_color_button)
  1219. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1220. self.on_pf_color_spinner)
  1221. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1222. self.on_pf_color_slider)
  1223. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1224. self.on_pl_color_entry)
  1225. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1226. self.on_pl_color_button)
  1227. # Setting selection (left - right) colors signals
  1228. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1229. self.on_sf_color_entry)
  1230. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1231. self.on_sf_color_button)
  1232. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1233. self.on_sf_color_spinner)
  1234. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1235. self.on_sf_color_slider)
  1236. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1237. self.on_sl_color_entry)
  1238. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1239. self.on_sl_color_button)
  1240. # Setting selection (right - left) colors signals
  1241. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1242. self.on_alt_sf_color_entry)
  1243. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1244. self.on_alt_sf_color_button)
  1245. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1246. self.on_alt_sf_color_spinner)
  1247. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1248. self.on_alt_sf_color_slider)
  1249. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1250. self.on_alt_sl_color_entry)
  1251. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1252. self.on_alt_sl_color_button)
  1253. # Setting Editor Draw colors signals
  1254. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1255. self.on_draw_color_entry)
  1256. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1257. self.on_draw_color_button)
  1258. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1259. self.on_sel_draw_color_entry)
  1260. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1261. self.on_sel_draw_color_button)
  1262. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1263. self.on_proj_color_entry)
  1264. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1265. self.on_proj_color_button)
  1266. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1267. self.on_proj_color_dis_entry)
  1268. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1269. self.on_proj_color_dis_button)
  1270. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1271. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1272. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1273. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1274. self.on_cnc_custom_parameters)
  1275. # Modify G-CODE Plot Area TAB
  1276. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1277. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1278. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1279. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1280. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1281. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1282. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1283. # Object list
  1284. self.collection.view.activated.connect(self.on_row_activated)
  1285. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1286. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1287. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1288. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1289. self.on_excellon_defaults_button)
  1290. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1291. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1292. self.on_excellon_options_button)
  1293. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1294. self.tool_tab_locked = False
  1295. # decide if to show or hide the Notebook side of the screen at startup
  1296. if self.defaults["global_project_at_startup"] is True:
  1297. self.ui.splitter.setSizes([1, 1])
  1298. else:
  1299. self.ui.splitter.setSizes([0, 1])
  1300. # ###################
  1301. # ## Other setups ###
  1302. # ###################
  1303. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1304. self.setup_obj_classes()
  1305. self.setup_recent_items()
  1306. self.setup_component_editor()
  1307. # ############
  1308. # ## Shell ###
  1309. # ############
  1310. # ##
  1311. # Auto-complete KEYWORDS
  1312. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1313. 'aligndrill', 'clear',
  1314. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1315. 'export_gcode',
  1316. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1317. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1318. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1319. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1320. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1321. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1322. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1323. ]
  1324. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1325. 'holes', 'grid', 'minoffset', 'gridoffset', 'axisoffset', 'dia', 'dist',
  1326. 'gridoffsetx', 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate',
  1327. 'feedrate_rapid', 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g',
  1328. 'outname', 'margin', 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed',
  1329. 'toolchange', 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble',
  1330. 'filename', 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads',
  1331. 'x', 'y', 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value',
  1332. 'angle_x', 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1333. ]
  1334. self.tcl_keywords = [
  1335. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1336. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1337. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1338. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1339. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1340. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1341. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1342. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1343. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1344. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1345. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1346. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1347. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1348. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1349. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1350. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1351. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1352. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1353. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1354. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1355. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1356. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1357. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1358. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1359. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1360. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1361. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1362. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1363. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1364. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1365. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1366. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1367. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1368. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1369. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1370. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1371. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1372. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1373. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1374. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1375. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1376. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1377. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1378. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1379. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1380. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1381. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1382. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1383. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1384. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1385. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1386. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1387. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1388. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1389. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1390. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1391. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1392. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1393. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1394. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1395. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1396. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1397. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1398. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1399. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1400. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1401. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1402. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1403. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1404. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1405. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1406. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1407. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1408. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1409. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1410. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1411. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1412. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1413. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1414. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1415. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1416. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1417. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1418. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1419. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1420. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1421. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1422. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1423. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1424. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1425. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1426. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1427. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1428. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1429. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1430. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1431. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1432. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1433. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1434. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1435. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1436. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1437. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1438. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1439. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1440. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1441. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1442. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1443. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1444. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1445. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1446. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1447. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1448. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1449. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1450. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1451. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1452. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1453. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1454. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1455. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1456. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1457. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1458. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1459. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1460. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1461. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1462. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1463. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1464. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1465. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1466. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1467. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1468. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1469. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1470. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1471. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1472. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1473. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1474. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1475. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1476. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1477. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1478. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1479. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1480. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1481. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1482. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1483. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1484. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1485. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1486. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1487. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1488. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1489. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1490. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1491. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1492. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1493. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1494. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1495. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1496. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1497. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1498. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1499. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1500. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1501. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1502. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1503. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1504. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1505. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1506. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1507. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1508. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1509. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1510. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1511. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1512. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1513. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1514. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1515. ]
  1516. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1517. self.shell = FCShell(self, version=self.version)
  1518. self.shell._edit.set_model_data(self.myKeywords)
  1519. self.ui.code_editor.set_model_data(self.myKeywords)
  1520. self.shell.setWindowIcon(self.ui.app_icon)
  1521. self.shell.setWindowTitle("FlatCAM Shell")
  1522. self.shell.resize(*self.defaults["global_shell_shape"])
  1523. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1524. self.shell.append_output("(Type help to get started)\n\n")
  1525. self.init_tcl()
  1526. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1527. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1528. self.ui.shell_dock.setWidget(self.shell)
  1529. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1530. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1531. QtWidgets.QDockWidget.DockWidgetFloatable |
  1532. QtWidgets.QDockWidget.DockWidgetClosable)
  1533. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1534. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1535. if self.defaults["global_shell_at_startup"]:
  1536. self.ui.shell_dock.show()
  1537. else:
  1538. self.ui.shell_dock.hide()
  1539. # ########################
  1540. # ## Tools and Plugins ###
  1541. # ########################
  1542. self.dblsidedtool = None
  1543. self.measurement_tool = None
  1544. self.panelize_tool = None
  1545. self.film_tool = None
  1546. self.paste_tool = None
  1547. self.calculator_tool = None
  1548. self.sub_tool = None
  1549. self.move_tool = None
  1550. self.cutout_tool = None
  1551. self.ncclear_tool = None
  1552. self.paint_tool = None
  1553. self.transform_tool = None
  1554. self.properties_tool = None
  1555. self.pdf_tool = None
  1556. self.image_tool = None
  1557. self.pcb_wizard_tool = None
  1558. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1559. self.install_tools()
  1560. # ## System Font Parsing ###
  1561. # self.f_parse = ParseFont(self)
  1562. # self.parse_system_fonts()
  1563. # test if the program was started with a script as parameter
  1564. if self.cmd_line_shellfile:
  1565. try:
  1566. with open(self.cmd_line_shellfile, "r") as myfile:
  1567. cmd_line_shellfile_text = myfile.read()
  1568. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1569. except Exception as ext:
  1570. print("ERROR: ", ext)
  1571. sys.exit(2)
  1572. # ##########################
  1573. # ### Check for updates ####
  1574. # ##########################
  1575. # Separate thread (Not worker)
  1576. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1577. if (self.beta is False or self.beta is None) and \
  1578. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1579. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1580. self.thr2 = QtCore.QThread()
  1581. self.worker_task.emit({'fcn': self.version_check,
  1582. 'params': []})
  1583. self.thr2.start(QtCore.QThread.LowPriority)
  1584. # ###################################
  1585. # ### Variables for global usage ####
  1586. # ###################################
  1587. # coordinates for relative position display
  1588. self.rel_point1 = (0, 0)
  1589. self.rel_point2 = (0, 0)
  1590. # variable to store coordinates
  1591. self.pos = (0, 0)
  1592. self.pos_jump = (0, 0)
  1593. # decide if we have a double click or single click
  1594. self.doubleclick = False
  1595. # variable to store if a command is active (then the var is not None) and which one it is
  1596. self.command_active = None
  1597. # variable to store the status of moving selection action
  1598. # None value means that it's not an selection action
  1599. # True value = a selection from left to right
  1600. # False value = a selection from right to left
  1601. self.selection_type = None
  1602. # List to store the objects that are currently loaded in FlatCAM
  1603. # This list is updated on each object creation or object delete
  1604. self.all_objects_list = []
  1605. # List to store the objects that are selected
  1606. self.sel_objects_list = []
  1607. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1608. self.key_modifiers = None
  1609. # Variable to hold the status of the axis
  1610. self.toggle_axis = True
  1611. # Variable to store the status of the fullscreen event
  1612. self.toggle_fscreen = False
  1613. # Variable to store the status of the code editor
  1614. self.toggle_codeeditor = False
  1615. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1616. self.click_noproject = False
  1617. self.cursor = None
  1618. # Variable to store the GCODE that was edited
  1619. self.gcode_edited = ""
  1620. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1621. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1622. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1623. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1624. ]
  1625. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1626. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1627. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1628. 'mpf'
  1629. ]
  1630. self.svg_list = ['svg']
  1631. self.dxf_list = ['dxf']
  1632. self.pdf_list = ['pdf']
  1633. self.prj_list = ['flatprj']
  1634. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1635. # flag for polygons not cleared
  1636. self.poly_not_cleared = False
  1637. # VisPy visuals
  1638. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1639. self.isHovering = False
  1640. self.notHovering = True
  1641. # ## Save defaults to factory_defaults.FlatConfig file ###
  1642. # ## It's done only once after install #############
  1643. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1644. fac_def_from_file = factory_file.read()
  1645. factory_defaults = json.loads(fac_def_from_file)
  1646. # if the file contain an empty dictionary then save the factory defaults into the file
  1647. if not factory_defaults:
  1648. self.save_factory_defaults(silent=False)
  1649. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1650. initial_lay = 'compact'
  1651. self.on_layout(lay=initial_lay)
  1652. # Set the combobox in Preferences to the current layout
  1653. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1654. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1655. factory_file.close()
  1656. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1657. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1658. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1659. # Post-GUI initialization: Experimental attempt
  1660. # to perform unit tests on the GUI.
  1661. # if post_gui is not None:
  1662. # post_gui(self)
  1663. App.log.debug("END of constructor. Releasing control.")
  1664. # accept a project file as command line parameter
  1665. # the path/file_name must be enclosed in quotes if it contain spaces
  1666. for argument in App.args:
  1667. if '.FlatPrj' in argument:
  1668. try:
  1669. project_name = str(argument)
  1670. if project_name == "":
  1671. self.inform.emit(_("Open cancelled."))
  1672. else:
  1673. # self.open_project(project_name)
  1674. run_from_arg = True
  1675. self.worker_task.emit({'fcn': self.open_project,
  1676. 'params': [project_name, run_from_arg]})
  1677. except Exception as e:
  1678. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1679. if '.FlatConfig' in argument:
  1680. try:
  1681. file_name = str(argument)
  1682. if file_name == "":
  1683. self.inform.emit(_("Open Config file failed."))
  1684. else:
  1685. # run_from_arg = True
  1686. # self.worker_task.emit({'fcn': self.open_config_file,
  1687. # 'params': [file_name, run_from_arg]})
  1688. self.open_config_file(file_name, run_from_arg=True)
  1689. except Exception as e:
  1690. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1691. if '.FlatScript' in argument:
  1692. try:
  1693. file_name = str(argument)
  1694. if file_name == "":
  1695. self.inform.emit(_("Open Script file failed."))
  1696. else:
  1697. # run_from_arg = True
  1698. # self.worker_task.emit({'fcn': self.open_script_file,
  1699. # 'params': [file_name, run_from_arg]})
  1700. self.on_filerunscript(name=file_name)
  1701. except Exception as e:
  1702. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1703. def defaults_read_form(self):
  1704. for option in self.defaults_form_fields:
  1705. try:
  1706. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1707. except Exception as e:
  1708. log.debug("App.defaults_read_form() --> %s" % str(e))
  1709. def defaults_write_form(self, factor=None):
  1710. for option in self.defaults:
  1711. self.defaults_write_form_field(option, factor=factor)
  1712. # try:
  1713. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1714. # except KeyError:
  1715. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1716. # # TODO: Rethink this?
  1717. # pass
  1718. def defaults_write_form_field(self, field, factor=None):
  1719. try:
  1720. if factor is None:
  1721. self.defaults_form_fields[field].set_value(self.defaults[field])
  1722. else:
  1723. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1724. except KeyError:
  1725. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  1726. # TODO: Rethink this?
  1727. pass
  1728. except AttributeError:
  1729. log.debug(field)
  1730. def clear_pool(self):
  1731. self.pool.close()
  1732. self.pool = Pool()
  1733. self.pool_recreated.emit(self.pool)
  1734. gc.collect()
  1735. # the order that the tools are installed is important as they can depend on each other install position
  1736. def install_tools(self):
  1737. self.dblsidedtool = DblSidedTool(self)
  1738. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1739. self.measurement_tool = Measurement(self)
  1740. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1741. self.panelize_tool = Panelize(self)
  1742. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1743. self.film_tool = Film(self)
  1744. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1745. self.paste_tool = SolderPaste(self)
  1746. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  1747. self.calculator_tool = ToolCalculator(self)
  1748. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1749. self.sub_tool = ToolSub(self)
  1750. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menuedit_convert,
  1751. before=self.ui.menuedit_convert_sg2mg)
  1752. self.move_tool = ToolMove(self)
  1753. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1754. before=self.ui.menueditorigin)
  1755. self.cutout_tool = CutOut(self)
  1756. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1757. before=self.measurement_tool.menuAction)
  1758. self.ncclear_tool = NonCopperClear(self)
  1759. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1760. before=self.measurement_tool.menuAction, separator=True)
  1761. self.paint_tool = ToolPaint(self)
  1762. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1763. before=self.measurement_tool.menuAction, separator=True)
  1764. self.transform_tool = ToolTransform(self)
  1765. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1766. self.properties_tool = Properties(self)
  1767. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1768. self.pdf_tool = ToolPDF(self)
  1769. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  1770. separator=True)
  1771. self.image_tool = ToolImage(self)
  1772. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1773. separator=True)
  1774. self.pcb_wizard_tool = PcbWizard(self)
  1775. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  1776. self.log.debug("Tools are installed.")
  1777. def remove_tools(self):
  1778. for act in self.ui.menutool.actions():
  1779. self.ui.menutool.removeAction(act)
  1780. def init_tools(self):
  1781. log.debug("init_tools()")
  1782. # delete the data currently in the Tools Tab and the Tab itself
  1783. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1784. if widget is not None:
  1785. widget.deleteLater()
  1786. self.ui.notebook.removeTab(2)
  1787. # rebuild the Tools Tab
  1788. self.ui.tool_tab = QtWidgets.QWidget()
  1789. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1790. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1791. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1792. self.ui.tool_scroll_area = VerticalScrollArea()
  1793. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1794. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1795. # first remove all of them
  1796. self.remove_tools()
  1797. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1798. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1799. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1800. # third install all of them
  1801. self.install_tools()
  1802. self.log.debug("Tools are initialized.")
  1803. # def parse_system_fonts(self):
  1804. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1805. # 'params': []})
  1806. def connect_toolbar_signals(self):
  1807. # Toolbar
  1808. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1809. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1810. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1811. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1812. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1813. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1814. self.ui.replot_btn.triggered.connect(self.plot_all)
  1815. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1816. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1817. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1818. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1819. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1820. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1821. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1822. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1823. self.ui.delete_btn.triggered.connect(self.on_delete)
  1824. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1825. # Tools Toolbar Signals
  1826. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1827. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1828. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1829. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1830. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1831. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1832. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1833. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1834. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1835. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1836. def object2editor(self):
  1837. """
  1838. Send the current Geometry or Excellon object (if any) into the editor.
  1839. :return: None
  1840. """
  1841. self.report_usage("object2editor()")
  1842. edited_object = self.collection.get_active()
  1843. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  1844. isinstance(edited_object, FlatCAMExcellon):
  1845. pass
  1846. else:
  1847. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  1848. return
  1849. if isinstance(edited_object, FlatCAMGeometry):
  1850. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1851. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1852. if edited_object.multigeo is True:
  1853. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  1854. if len(edited_tools) > 1:
  1855. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  1856. "is not possible.\n"
  1857. "Edit only one geometry at a time."))
  1858. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=edited_tools[0])
  1859. else:
  1860. self.geo_editor.edit_fcgeometry(edited_object)
  1861. # we set the notebook to hidden
  1862. self.ui.splitter.setSizes([0, 1])
  1863. # set call source to the Editor we go into
  1864. self.call_source = 'geo_editor'
  1865. elif isinstance(edited_object, FlatCAMExcellon):
  1866. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1867. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1868. self.exc_editor.edit_fcexcellon(edited_object)
  1869. # set call source to the Editor we go into
  1870. self.call_source = 'exc_editor'
  1871. if self.ui.splitter.sizes()[0] == 0:
  1872. self.ui.splitter.setSizes([1, 1])
  1873. elif isinstance(edited_object, FlatCAMGerber):
  1874. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1875. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1876. self.grb_editor.edit_fcgerber(edited_object)
  1877. # set call source to the Editor we go into
  1878. self.call_source = 'grb_editor'
  1879. if self.ui.splitter.sizes()[0] == 0:
  1880. self.ui.splitter.setSizes([1, 1])
  1881. # # make sure that we can't select another object while in Editor Mode:
  1882. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1883. self.ui.project_frame.setDisabled(True)
  1884. # delete any selection shape that might be active as they are not relevant in Editor
  1885. self.delete_selection_shape()
  1886. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1887. self.ui.plot_tab_area.protectTab(0)
  1888. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  1889. self.should_we_save = True
  1890. def editor2object(self, cleanup=None):
  1891. """
  1892. Transfers the Geometry or Excellon from the editor to the current object.
  1893. :return: None
  1894. """
  1895. self.report_usage("editor2object()")
  1896. # do not update a geometry or excellon object unless it comes out of an editor
  1897. if self.call_source != 'app':
  1898. edited_obj = self.collection.get_active()
  1899. if cleanup is None:
  1900. msgbox = QtWidgets.QMessageBox()
  1901. msgbox.setText(_("Do you want to save the edited object?"))
  1902. msgbox.setWindowTitle(_("Close Editor"))
  1903. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1904. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1905. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1906. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1907. msgbox.setDefaultButton(bt_yes)
  1908. msgbox.exec_()
  1909. response = msgbox.clickedButton()
  1910. if response == bt_yes:
  1911. # clean the Tools Tab
  1912. self.ui.tool_scroll_area.takeWidget()
  1913. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1914. self.ui.notebook.setTabText(2, "Tool")
  1915. if isinstance(edited_obj, FlatCAMGeometry):
  1916. obj_type = "Geometry"
  1917. if cleanup is None:
  1918. self.geo_editor.update_fcgeometry(edited_obj)
  1919. self.geo_editor.update_options(edited_obj)
  1920. self.geo_editor.deactivate()
  1921. # update the geo object options so it is including the bounding box values
  1922. try:
  1923. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1924. edited_obj.options['xmin'] = xmin
  1925. edited_obj.options['ymin'] = ymin
  1926. edited_obj.options['xmax'] = xmax
  1927. edited_obj.options['ymax'] = ymax
  1928. except AttributeError as e:
  1929. self.inform.emit(_("[WARNING] Object empty after edit."))
  1930. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1931. elif isinstance(edited_obj, FlatCAMGerber):
  1932. obj_type = "Gerber"
  1933. if cleanup is None:
  1934. self.grb_editor.update_fcgerber()
  1935. self.grb_editor.update_options(edited_obj)
  1936. self.grb_editor.deactivate_grb_editor()
  1937. # delete the old object (the source object) if it was an empty one
  1938. if len(edited_obj.solid_geometry) == 0:
  1939. old_name = edited_obj.options['name']
  1940. self.collection.set_active(old_name)
  1941. self.collection.delete_active()
  1942. elif isinstance(edited_obj, FlatCAMExcellon):
  1943. obj_type = "Excellon"
  1944. if cleanup is None:
  1945. self.exc_editor.update_fcexcellon(edited_obj)
  1946. self.exc_editor.update_options(edited_obj)
  1947. self.exc_editor.deactivate()
  1948. else:
  1949. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1950. return
  1951. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1952. elif response == bt_no:
  1953. # clean the Tools Tab
  1954. self.ui.tool_scroll_area.takeWidget()
  1955. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1956. self.ui.notebook.setTabText(2, "Tool")
  1957. if isinstance(edited_obj, FlatCAMGeometry):
  1958. self.geo_editor.deactivate()
  1959. elif isinstance(edited_obj, FlatCAMGerber):
  1960. self.grb_editor.deactivate_grb_editor()
  1961. elif isinstance(edited_obj, FlatCAMExcellon):
  1962. self.exc_editor.deactivate()
  1963. # set focus on the project tab
  1964. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  1965. else:
  1966. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1967. return
  1968. elif response == bt_cancel:
  1969. return
  1970. else:
  1971. if isinstance(edited_obj, FlatCAMGeometry):
  1972. self.geo_editor.deactivate()
  1973. elif isinstance(edited_obj, FlatCAMGerber):
  1974. self.grb_editor.deactivate_grb_editor()
  1975. elif isinstance(edited_obj, FlatCAMExcellon):
  1976. self.exc_editor.deactivate()
  1977. else:
  1978. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1979. return
  1980. # if notebook is hidden we show it
  1981. if self.ui.splitter.sizes()[0] == 0:
  1982. self.ui.splitter.setSizes([1, 1])
  1983. # restore the call_source to app
  1984. self.call_source = 'app'
  1985. edited_obj.plot()
  1986. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1987. self.ui.plot_tab_area.protectTab(0)
  1988. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1989. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1990. self.ui.project_frame.setDisabled(False)
  1991. def get_last_folder(self):
  1992. return self.defaults["global_last_folder"]
  1993. def get_last_save_folder(self):
  1994. loc = self.defaults["global_last_save_folder"]
  1995. if loc is None:
  1996. loc = self.defaults["global_last_folder"]
  1997. if loc is None:
  1998. loc = os.path.dirname(__file__)
  1999. return loc
  2000. def report_usage(self, resource):
  2001. """
  2002. Increments usage counter for the given resource
  2003. in self.defaults['global_stats'].
  2004. :param resource: Name of the resource.
  2005. :return: None
  2006. """
  2007. if resource in self.defaults['global_stats']:
  2008. self.defaults['global_stats'][resource] += 1
  2009. else:
  2010. self.defaults['global_stats'][resource] = 1
  2011. def init_tcl(self):
  2012. if hasattr(self, 'tcl'):
  2013. # self.tcl = None
  2014. # TODO we need to clean non default variables and procedures here
  2015. # new object cannot be used here as it will not remember values created for next passes,
  2016. # because tcl was execudted in old instance of TCL
  2017. pass
  2018. else:
  2019. self.tcl = tk.Tcl()
  2020. self.setup_shell()
  2021. self.log.debug("TCL Shell has been initialized.")
  2022. # TODO: This shouldn't be here.
  2023. class TclErrorException(Exception):
  2024. """
  2025. this exception is defined here, to be able catch it if we ssuccessfully handle all errors from shell command
  2026. """
  2027. pass
  2028. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2029. """
  2030. Shows a message on the FlatCAM Shell
  2031. :param msg: Message to display.
  2032. :param show: Opens the shell.
  2033. :param error: Shows the message as an error.
  2034. :param warning: Shows the message as an warning.
  2035. :param warning: Shows the message as an success.
  2036. :param selected: Indicate that something was selected on canvas
  2037. :return: None
  2038. """
  2039. if show:
  2040. self.ui.shell_dock.show()
  2041. try:
  2042. if error:
  2043. self.shell.append_error(msg + "\n")
  2044. elif warning:
  2045. self.shell.append_warning(msg + "\n")
  2046. elif success:
  2047. self.shell.append_success(msg + "\n")
  2048. elif selected:
  2049. self.shell.append_selected(msg + "\n")
  2050. else:
  2051. self.shell.append_output(msg + "\n")
  2052. except AttributeError:
  2053. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2054. def raise_tcl_unknown_error(self, unknownException):
  2055. """
  2056. Raise exception if is different type than TclErrorException
  2057. this is here mainly to show unknown errors inside TCL shell console.
  2058. :param unknownException:
  2059. :return:
  2060. """
  2061. if not isinstance(unknownException, self.TclErrorException):
  2062. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2063. else:
  2064. raise unknownException
  2065. def display_tcl_error(self, error, error_info=None):
  2066. """
  2067. Escape bracket [ with '\' otherwise there is error
  2068. "ERROR: missing close-bracket" instead of real error
  2069. :param error: it may be text or exception
  2070. :param error_info: Some informations about the error
  2071. :return: None
  2072. """
  2073. if isinstance(error, Exception):
  2074. exc_type, exc_value, exc_traceback = error_info
  2075. if not isinstance(error, self.TclErrorException):
  2076. show_trace = 1
  2077. else:
  2078. show_trace = int(self.defaults['global_verbose_error_level'])
  2079. if show_trace > 0:
  2080. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2081. trc_formated = []
  2082. for a in reversed(trc):
  2083. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2084. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2085. else:
  2086. text = "%s" % error
  2087. else:
  2088. text = error
  2089. text = text.replace('[', '\\[').replace('"', '\\"')
  2090. self.tcl.eval('return -code error "%s"' % text)
  2091. def raise_tcl_error(self, text):
  2092. """
  2093. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2094. :param text: text of error
  2095. :return: raise exception
  2096. """
  2097. self.display_tcl_error(text)
  2098. raise self.TclErrorException(text)
  2099. def exec_command(self, text):
  2100. """
  2101. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2102. Also handles execution in separated threads
  2103. :param text:
  2104. :return: output if there was any
  2105. """
  2106. self.report_usage('exec_command')
  2107. result = self.exec_command_test(text, False)
  2108. # MS: added this method call so the geometry is updated once the TCL command is executed
  2109. self.plot_all()
  2110. return result
  2111. def exec_command_test(self, text, reraise=True):
  2112. """
  2113. Same as exec_command(...) with additional control over exceptions.
  2114. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2115. :param text: Input command
  2116. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2117. :return: Output from the command
  2118. """
  2119. text = str(text)
  2120. try:
  2121. self.shell.open_proccessing() # Disables input box.
  2122. result = self.tcl.eval(str(text))
  2123. if result != 'None':
  2124. self.shell.append_output(result + '\n')
  2125. except tk.TclError as e:
  2126. # This will display more precise answer if something in TCL shell fails
  2127. result = self.tcl.eval("set errorInfo")
  2128. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2129. self.shell.append_error('ERROR: ' + result + '\n')
  2130. # Show error in console and just return or in test raise exception
  2131. if reraise:
  2132. raise e
  2133. finally:
  2134. self.shell.close_proccessing()
  2135. pass
  2136. return result
  2137. # """
  2138. # Code below is unsused. Saved for later.
  2139. # """
  2140. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2141. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2142. # self.log.debug(parts)
  2143. # try:
  2144. # if parts[0] not in commands:
  2145. # self.shell.append_error("Unknown command\n")
  2146. # return
  2147. #
  2148. # #import inspect
  2149. # #inspect.getargspec(someMethod)
  2150. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2151. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2152. # self.shell.append_error(
  2153. # "Command %s takes %d arguments. %d given.\n" %
  2154. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2155. # )
  2156. # return
  2157. #
  2158. # cmdfcn = commands[parts[0]]["fcn"]
  2159. # cmdconv = commands[parts[0]]["converters"]
  2160. # if len(parts) - 1 > 0:
  2161. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2162. # else:
  2163. # retval = cmdfcn()
  2164. # retfcn = commands[parts[0]]["retfcn"]
  2165. # if retval and retfcn(retval):
  2166. # self.shell.append_output(retfcn(retval) + "\n")
  2167. #
  2168. # except Exception as e:
  2169. # #self.shell.append_error(''.join(traceback.format_exc()))
  2170. # #self.shell.append_error("?\n")
  2171. # self.shell.append_error(str(e) + "\n")
  2172. def info(self, msg):
  2173. """
  2174. Informs the user. Normally on the status bar, optionally
  2175. also on the shell.
  2176. :param msg: Text to write.
  2177. :return: None
  2178. """
  2179. # Type of message in brackets at the beginning of the message.
  2180. match = re.search("\[([^\]]+)\](.*)", msg)
  2181. if match:
  2182. level = match.group(1)
  2183. msg_ = match.group(2)
  2184. self.ui.fcinfo.set_status(str(msg_), level=level)
  2185. if level.lower() == "error":
  2186. self.shell_message(msg, error=True, show=True)
  2187. elif level.lower() == "warning":
  2188. self.shell_message(msg, warning=True, show=True)
  2189. elif level.lower() == "error_notcl":
  2190. self.shell_message(msg, error=True, show=False)
  2191. elif level.lower() == "warning_notcl":
  2192. self.shell_message(msg, warning=True, show=False)
  2193. elif level.lower() == "success":
  2194. self.shell_message(msg, success=True, show=False)
  2195. elif level.lower() == "selected":
  2196. self.shell_message(msg, selected=True, show=False)
  2197. else:
  2198. self.shell_message(msg, show=False)
  2199. else:
  2200. self.ui.fcinfo.set_status(str(msg), level="info")
  2201. # make sure that if the message is to clear the infobar with a space
  2202. # is not printed over and over on the shell
  2203. if msg != '':
  2204. self.shell_message(msg)
  2205. def restore_toolbar_view(self):
  2206. tb = self.defaults["global_toolbar_view"]
  2207. if tb & 1:
  2208. self.ui.toolbarfile.setVisible(True)
  2209. else:
  2210. self.ui.toolbarfile.setVisible(False)
  2211. if tb & 2:
  2212. self.ui.toolbargeo.setVisible(True)
  2213. else:
  2214. self.ui.toolbargeo.setVisible(False)
  2215. if tb & 4:
  2216. self.ui.toolbarview.setVisible(True)
  2217. else:
  2218. self.ui.toolbarview.setVisible(False)
  2219. if tb & 8:
  2220. self.ui.toolbartools.setVisible(True)
  2221. else:
  2222. self.ui.toolbartools.setVisible(False)
  2223. if tb & 16:
  2224. self.ui.exc_edit_toolbar.setVisible(True)
  2225. else:
  2226. self.ui.exc_edit_toolbar.setVisible(False)
  2227. if tb & 32:
  2228. self.ui.geo_edit_toolbar.setVisible(True)
  2229. else:
  2230. self.ui.geo_edit_toolbar.setVisible(False)
  2231. if tb & 64:
  2232. self.ui.grb_edit_toolbar.setVisible(True)
  2233. else:
  2234. self.ui.grb_edit_toolbar.setVisible(False)
  2235. if tb & 128:
  2236. self.ui.snap_toolbar.setVisible(True)
  2237. else:
  2238. self.ui.snap_toolbar.setVisible(False)
  2239. if tb & 256:
  2240. self.ui.toolbarshell.setVisible(True)
  2241. else:
  2242. self.ui.toolbarshell.setVisible(False)
  2243. def load_defaults(self, filename):
  2244. """
  2245. Loads the aplication's default settings from current_defaults.FlatConfig into
  2246. ``self.defaults``.
  2247. :return: None
  2248. """
  2249. try:
  2250. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2251. options = f.read()
  2252. f.close()
  2253. except IOError:
  2254. self.log.error("Could not load defaults file.")
  2255. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2256. # in case the defaults file can't be loaded, show all toolbars
  2257. self.defaults["global_toolbar_view"] = 511
  2258. return
  2259. try:
  2260. defaults = json.loads(options)
  2261. except:
  2262. # in case the defaults file can't be loaded, show all toolbars
  2263. self.defaults["global_toolbar_view"] = 511
  2264. e = sys.exc_info()[0]
  2265. App.log.error(str(e))
  2266. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2267. return
  2268. self.defaults.update(defaults)
  2269. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2270. # restore the toolbar view
  2271. self.restore_toolbar_view()
  2272. def on_import_preferences(self):
  2273. """
  2274. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2275. ``self.defaults``.
  2276. :return: None
  2277. """
  2278. self.report_usage("on_import_preferences")
  2279. App.log.debug("on_import_preferences()")
  2280. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2281. try:
  2282. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2283. directory=self.data_path,
  2284. filter=filter_)
  2285. except TypeError:
  2286. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2287. filter=filter_)
  2288. filename = str(filename)
  2289. if filename == "":
  2290. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2291. else:
  2292. try:
  2293. f = open(filename)
  2294. options = f.read()
  2295. f.close()
  2296. except IOError:
  2297. self.log.error("Could not load defaults file.")
  2298. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2299. return
  2300. try:
  2301. defaults_from_file = json.loads(options)
  2302. except Exception as e:
  2303. e = sys.exc_info()[0]
  2304. App.log.error(str(e))
  2305. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2306. return
  2307. self.defaults.update(defaults_from_file)
  2308. self.inform.emit(_("[success] Imported Defaults from %s") %filename)
  2309. def on_export_preferences(self):
  2310. self.report_usage("on_export_preferences")
  2311. App.log.debug("on_export_preferences()")
  2312. defaults_file_content = None
  2313. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2314. try:
  2315. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2316. caption=_("Export FlatCAM Preferences"),
  2317. directory=self.data_path + '/preferences_' + self.date,
  2318. filter=filter
  2319. )
  2320. except TypeError:
  2321. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2322. filter=filter)
  2323. filename = str(filename)
  2324. defaults_from_file = {}
  2325. if filename == "":
  2326. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2327. return
  2328. else:
  2329. try:
  2330. f = open(filename, 'w')
  2331. defaults_file_content = f.read()
  2332. f.close()
  2333. except IOError:
  2334. App.log.debug('Creating a new preferences file ...')
  2335. f = open(filename, 'w')
  2336. json.dump({}, f)
  2337. f.close()
  2338. except:
  2339. e = sys.exc_info()[0]
  2340. App.log.error("Could not load defaults file.")
  2341. App.log.error(str(e))
  2342. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2343. return
  2344. try:
  2345. defaults_from_file = json.loads(defaults_file_content)
  2346. except:
  2347. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2348. # Update options
  2349. self.defaults_read_form()
  2350. defaults_from_file.update(self.defaults)
  2351. self.propagate_defaults(silent=True)
  2352. # Save update options
  2353. try:
  2354. f = open(filename, "w")
  2355. json.dump(defaults_from_file, f)
  2356. f.close()
  2357. except:
  2358. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2359. return
  2360. if self.defaults["global_open_style"] is False:
  2361. self.file_opened.emit("preferences", filename)
  2362. self.file_saved.emit("preferences", filename)
  2363. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2364. def on_preferences_open_folder(self):
  2365. self.report_usage("on_preferences_open_folder()")
  2366. if sys.platform == 'win32':
  2367. subprocess.Popen('explorer %s' % self.data_path)
  2368. elif sys.platform == 'darwin':
  2369. os.system('open "%s"' % self.data_path)
  2370. else:
  2371. subprocess.Popen(['xdg-open', self.data_path])
  2372. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2373. def save_geometry(self, x, y, width, height, notebook_width):
  2374. self.defaults["global_def_win_x"] = x
  2375. self.defaults["global_def_win_y"] = y
  2376. self.defaults["global_def_win_w"] = width
  2377. self.defaults["global_def_win_h"] = height
  2378. self.defaults["global_def_notebook_width"] = notebook_width
  2379. self.save_defaults()
  2380. def message_dialog(self, title, message, kind="info"):
  2381. icon = {"info": QtWidgets.QMessageBox.Information,
  2382. "warning": QtWidgets.QMessageBox.Warning,
  2383. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2384. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2385. dlg.setText(message)
  2386. dlg.exec_()
  2387. def register_recent(self, kind, filename):
  2388. self.log.debug("register_recent()")
  2389. self.log.debug(" %s" % kind)
  2390. self.log.debug(" %s" % filename)
  2391. record = {'kind': str(kind), 'filename': str(filename)}
  2392. if record in self.recent:
  2393. return
  2394. self.recent.insert(0, record)
  2395. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2396. self.recent.pop()
  2397. try:
  2398. f = open(self.data_path + '/recent.json', 'w')
  2399. except IOError:
  2400. App.log.error("Failed to open recent items file for writing.")
  2401. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2402. return
  2403. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2404. f.close()
  2405. # Re-build the recent items menu
  2406. self.setup_recent_items()
  2407. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2408. """
  2409. Creates a new specialized FlatCAMObj and attaches it to the application,
  2410. this is, updates the GUI accordingly, any other records and plots it.
  2411. This method is thread-safe.
  2412. Notes:
  2413. * If the name is in use, the self.collection will modify it
  2414. when appending it to the collection. There is no need to handle
  2415. name conflicts here.
  2416. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2417. :type kind: str
  2418. :param name: Name for the object.
  2419. :type name: str
  2420. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2421. The function is called with 2 parameters: the new object and the App instance.
  2422. :type initialize: function
  2423. :return: None
  2424. :rtype: None
  2425. """
  2426. App.log.debug("new_object()")
  2427. obj_plot = plot
  2428. obj_autoselected = autoselected
  2429. t0 = time.time() # Debug
  2430. ## Create object
  2431. classdict = {
  2432. "gerber": FlatCAMGerber,
  2433. "excellon": FlatCAMExcellon,
  2434. "cncjob": FlatCAMCNCjob,
  2435. "geometry": FlatCAMGeometry
  2436. }
  2437. App.log.debug("Calling object constructor...")
  2438. obj = classdict[kind](name)
  2439. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2440. # Set options from "Project options" form
  2441. self.options_read_form()
  2442. # IMPORTANT
  2443. # The key names in defaults and options dictionary's are not random:
  2444. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2445. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2446. # the options from project options form into the self.options. After that, below, depending on the type of
  2447. # object that is created, it will strip the name of the object and the underline (if the original key was
  2448. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2449. # "toolchange"
  2450. for option in self.options:
  2451. if option.find(kind + "_") == 0:
  2452. oname = option[len(kind) + 1:]
  2453. obj.options[oname] = self.options[option]
  2454. obj.isHovering = False
  2455. obj.notHovering = True
  2456. # Initialize as per user request
  2457. # User must take care to implement initialize
  2458. # in a thread-safe way as is is likely that we
  2459. # have been invoked in a separate thread.
  2460. t1 = time.time()
  2461. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2462. try:
  2463. return_value = initialize(obj, self)
  2464. except Exception as e:
  2465. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2466. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2467. msg += traceback.format_exc()
  2468. self.inform.emit(msg)
  2469. # if str(e) == "Empty Geometry":
  2470. # self.inform.emit("[ERROR_NOTCL] )
  2471. # else:
  2472. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2473. return "fail"
  2474. t2 = time.time()
  2475. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2476. if return_value == 'fail':
  2477. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2478. return "fail"
  2479. # Check units and convert if necessary
  2480. # This condition CAN be true because initialize() can change obj.units
  2481. if self.options["units"].upper() != obj.units.upper():
  2482. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2483. obj.convert_units(self.options["units"])
  2484. t3 = time.time()
  2485. self.log.debug("%f seconds converting units." % (t3 - t2))
  2486. # Create the bounding box for the object and then add the results to the obj.options
  2487. try:
  2488. xmin, ymin, xmax, ymax = obj.bounds()
  2489. obj.options['xmin'] = xmin
  2490. obj.options['ymin'] = ymin
  2491. obj.options['xmax'] = xmax
  2492. obj.options['ymax'] = ymax
  2493. except:
  2494. log.warning("The object has no bounds properties.")
  2495. # don't plot objects with no bounds, there is nothing to plot
  2496. self.plot = False
  2497. pass
  2498. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2499. # Move the object to the main thread and let the app know that it is available.
  2500. obj.moveToThread(self.main_thread)
  2501. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2502. return obj
  2503. def new_excellon_object(self):
  2504. self.report_usage("new_excellon_object()")
  2505. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2506. def new_geometry_object(self):
  2507. self.report_usage("new_geometry_object()")
  2508. def initialize(obj, self):
  2509. obj.multitool = False
  2510. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2511. def new_gerber_object(self):
  2512. self.report_usage("new_gerber_object()")
  2513. def initialize(grb_obj, self):
  2514. grb_obj.multitool = False
  2515. grb_obj.source_file = []
  2516. grb_obj.multigeo = False
  2517. grb_obj.follow = False
  2518. grb_obj.apertures = {}
  2519. grb_obj.solid_geometry = []
  2520. try:
  2521. grb_obj.options['xmin'] = 0
  2522. grb_obj.options['ymin'] = 0
  2523. grb_obj.options['xmax'] = 0
  2524. grb_obj.options['ymax'] = 0
  2525. except KeyError:
  2526. pass
  2527. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2528. def on_object_created(self, obj, plot, autoselect):
  2529. """
  2530. Event callback for object creation.
  2531. :param obj: The newly created FlatCAM object.
  2532. :return: None
  2533. """
  2534. t0 = time.time() # DEBUG
  2535. self.log.debug("on_object_created()")
  2536. # The Collection might change the name if there is a collision
  2537. self.collection.append(obj)
  2538. # after adding the object to the collection always update the list of objects that are in the collection
  2539. self.all_objects_list = self.collection.get_list()
  2540. # self.inform.emit('[selected] %s created & selected: %s' %
  2541. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2542. if obj.kind == 'gerber':
  2543. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2544. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2545. elif obj.kind == 'excellon':
  2546. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2547. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2548. elif obj.kind == 'cncjob':
  2549. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2550. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2551. elif obj.kind == 'geometry':
  2552. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2553. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2554. # update the SHELL auto-completer model with the name of the new object
  2555. self.myKeywords.append(obj.options['name'])
  2556. self.shell._edit.set_model_data(self.myKeywords)
  2557. self.ui.code_editor.set_model_data(self.myKeywords)
  2558. if autoselect:
  2559. # select the just opened object but deselect the previous ones
  2560. self.collection.set_all_inactive()
  2561. self.collection.set_active(obj.options["name"])
  2562. # here it is done the object plotting
  2563. def worker_task(t_obj):
  2564. with self.proc_container.new("Plotting"):
  2565. if isinstance(t_obj, FlatCAMCNCjob):
  2566. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2567. else:
  2568. t_obj.plot()
  2569. t1 = time.time() # DEBUG
  2570. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2571. self.object_plotted.emit(t_obj)
  2572. # Send to worker
  2573. # self.worker.add_task(worker_task, [self])
  2574. if plot is True:
  2575. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2576. def on_object_changed(self, obj):
  2577. # update the bounding box data from obj.options
  2578. xmin, ymin, xmax, ymax = obj.bounds()
  2579. obj.options['xmin'] = xmin
  2580. obj.options['ymin'] = ymin
  2581. obj.options['xmax'] = xmax
  2582. obj.options['ymax'] = ymax
  2583. log.debug("Object changed, updating the bounding box data on self.options")
  2584. # delete the old selection shape
  2585. self.delete_selection_shape()
  2586. self.should_we_save = True
  2587. def on_object_plotted(self, obj):
  2588. self.on_zoom_fit(None)
  2589. def options_read_form(self):
  2590. for option in self.options_form_fields:
  2591. self.options[option] = self.options_form_fields[option].get_value()
  2592. def options_write_form(self):
  2593. for option in self.options:
  2594. self.options_write_form_field(option)
  2595. def options_write_form_field(self, field):
  2596. try:
  2597. self.options_form_fields[field].set_value(self.options[field])
  2598. except KeyError:
  2599. # Changed from error to debug. This allows to have data stored
  2600. # which is not user-editable.
  2601. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2602. pass
  2603. def on_about(self):
  2604. """
  2605. Displays the "about" dialog.
  2606. :return: None
  2607. """
  2608. self.report_usage("on_about")
  2609. version = self.version
  2610. version_date = self.version_date
  2611. beta = self.beta
  2612. class AboutDialog(QtWidgets.QDialog):
  2613. def __init__(self, parent=None):
  2614. QtWidgets.QDialog.__init__(self, parent)
  2615. # Icon and title
  2616. self.setWindowIcon(parent.app_icon)
  2617. self.setWindowTitle("FlatCAM")
  2618. layout1 = QtWidgets.QVBoxLayout()
  2619. self.setLayout(layout1)
  2620. layout2 = QtWidgets.QHBoxLayout()
  2621. layout1.addLayout(layout2)
  2622. logo = QtWidgets.QLabel()
  2623. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2624. layout2.addWidget(logo, stretch=0)
  2625. title = QtWidgets.QLabel(
  2626. _(
  2627. "<font size=8><B>FlatCAM</B></font><BR>"
  2628. "Version {version} {beta} ({date}) - {arch} <BR>"
  2629. "<BR>"
  2630. "2D Computer-Aided Printed Circuit Board<BR>"
  2631. "Manufacturing.<BR>"
  2632. "<BR>"
  2633. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2634. "<BR>"
  2635. "<B> Main Contributors:</B><BR>"
  2636. "Denis Hayrullin<BR>"
  2637. "Kamil Sopko<BR>"
  2638. "Marius Stanciu<BR>"
  2639. "Matthieu Berthomé<BR>"
  2640. "and many others found "
  2641. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2642. "<BR>"
  2643. "Development is done "
  2644. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2645. "DOWNLOAD area "
  2646. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2647. ""
  2648. ).format(version=version,
  2649. beta=('BETA' if beta else ''),
  2650. date=version_date,
  2651. arch=platform.architecture()[0])
  2652. )
  2653. title.setOpenExternalLinks(True)
  2654. layout2.addWidget(title, stretch=1)
  2655. layout3 = QtWidgets.QHBoxLayout()
  2656. layout1.addLayout(layout3)
  2657. layout3.addStretch()
  2658. okbtn = QtWidgets.QPushButton("Close")
  2659. layout3.addWidget(okbtn)
  2660. okbtn.clicked.connect(self.accept)
  2661. AboutDialog(self.ui).exec_()
  2662. def on_file_savedefaults(self):
  2663. """
  2664. Callback for menu item File->Save Defaults. Saves application default options
  2665. ``self.defaults`` to current_defaults.FlatConfig.
  2666. :return: None
  2667. """
  2668. self.save_defaults()
  2669. # def on_app_exit(self):
  2670. # self.report_usage("on_app_exit()")
  2671. #
  2672. # if self.collection.get_list():
  2673. # msgbox = QtWidgets.QMessageBox()
  2674. # # msgbox.setText("<B>Save changes ...</B>")
  2675. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2676. # "\n"
  2677. # "Do you want to Save the project?")
  2678. # msgbox.setWindowTitle("Save changes")
  2679. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2680. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2681. # QtWidgets.QMessageBox.Cancel)
  2682. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2683. #
  2684. # response = msgbox.exec_()
  2685. #
  2686. # if response == QtWidgets.QMessageBox.Yes:
  2687. # self.on_file_saveprojectas(thread=False)
  2688. # elif response == QtWidgets.QMessageBox.Cancel:
  2689. # return
  2690. # self.save_defaults()
  2691. # else:
  2692. # self.save_defaults()
  2693. # log.debug("Application defaults saved ... Exit event.")
  2694. # QtWidgets.qApp.quit()
  2695. def save_defaults(self, silent=False):
  2696. """
  2697. Saves application default options
  2698. ``self.defaults`` to current_defaults.FlatConfig.
  2699. :return: None
  2700. """
  2701. self.report_usage("save_defaults")
  2702. # Read options from file
  2703. try:
  2704. f = open(self.data_path + "/current_defaults.FlatConfig")
  2705. defaults_file_content = f.read()
  2706. f.close()
  2707. except:
  2708. e = sys.exc_info()[0]
  2709. App.log.error("Could not load defaults file.")
  2710. App.log.error(str(e))
  2711. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2712. return
  2713. try:
  2714. defaults = json.loads(defaults_file_content)
  2715. except:
  2716. e = sys.exc_info()[0]
  2717. App.log.error("Failed to parse defaults file.")
  2718. App.log.error(str(e))
  2719. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2720. return
  2721. # Update options
  2722. self.defaults_read_form()
  2723. defaults.update(self.defaults)
  2724. self.propagate_defaults(silent=True)
  2725. # Save the toolbar view
  2726. tb_status = 0
  2727. if self.ui.toolbarfile.isVisible():
  2728. tb_status += 1
  2729. if self.ui.toolbargeo.isVisible():
  2730. tb_status += 2
  2731. if self.ui.toolbarview.isVisible():
  2732. tb_status += 4
  2733. if self.ui.toolbartools.isVisible():
  2734. tb_status += 8
  2735. if self.ui.exc_edit_toolbar.isVisible():
  2736. tb_status += 16
  2737. if self.ui.geo_edit_toolbar.isVisible():
  2738. tb_status += 32
  2739. if self.ui.grb_edit_toolbar.isVisible():
  2740. tb_status += 64
  2741. if self.ui.snap_toolbar.isVisible():
  2742. tb_status += 128
  2743. if self.ui.toolbarshell.isVisible():
  2744. tb_status += 256
  2745. self.defaults["global_toolbar_view"] = tb_status
  2746. # Save update options
  2747. try:
  2748. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2749. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2750. f.close()
  2751. except:
  2752. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2753. return
  2754. if not silent:
  2755. self.inform.emit(_("[success] Defaults saved."))
  2756. def save_factory_defaults(self, silent=False):
  2757. """
  2758. Saves application factory default options
  2759. ``self.defaults`` to factory_defaults.FlatConfig.
  2760. It's a one time job done just after the first install.
  2761. :return: None
  2762. """
  2763. self.report_usage("save_factory_defaults")
  2764. # Read options from file
  2765. try:
  2766. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2767. factory_defaults_file_content = f_f_def.read()
  2768. f_f_def.close()
  2769. except:
  2770. e = sys.exc_info()[0]
  2771. App.log.error("Could not load factory defaults file.")
  2772. App.log.error(str(e))
  2773. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2774. return
  2775. try:
  2776. factory_defaults = json.loads(factory_defaults_file_content)
  2777. except:
  2778. e = sys.exc_info()[0]
  2779. App.log.error("Failed to parse factory defaults file.")
  2780. App.log.error(str(e))
  2781. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2782. return
  2783. # Update options
  2784. self.defaults_read_form()
  2785. factory_defaults.update(self.defaults)
  2786. self.propagate_defaults(silent=True)
  2787. # Save update options
  2788. try:
  2789. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2790. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2791. f_f_def_s.close()
  2792. except:
  2793. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2794. return
  2795. if silent is False:
  2796. self.inform.emit(_("Factory defaults saved."))
  2797. def final_save(self):
  2798. if self.save_in_progress:
  2799. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  2800. return
  2801. if self.should_we_save and self.collection.get_list():
  2802. msgbox = QtWidgets.QMessageBox()
  2803. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2804. "\n"
  2805. "Do you want to Save the project?"))
  2806. msgbox.setWindowTitle(_("Save changes"))
  2807. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2808. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2809. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2810. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2811. msgbox.setDefaultButton(bt_yes)
  2812. msgbox.exec_()
  2813. response = msgbox.clickedButton()
  2814. if response == bt_yes:
  2815. self.on_file_saveprojectas(thread=True, quit=True)
  2816. elif response == bt_no:
  2817. self.quit_application()
  2818. elif response == bt_cancel:
  2819. return
  2820. else:
  2821. self.quit_application()
  2822. def quit_application(self):
  2823. self.save_defaults()
  2824. log.debug("App.final_save() --> App Defaults saved.")
  2825. # save toolbar state to file
  2826. settings = QSettings("Open Source", "FlatCAM")
  2827. settings.setValue('saved_gui_state', self.ui.saveState())
  2828. settings.setValue('maximized_gui', self.ui.isMaximized())
  2829. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  2830. # This will write the setting to the platform specific storage.
  2831. del settings
  2832. log.debug("App.final_save() --> App UI state saved.")
  2833. QtWidgets.qApp.quit()
  2834. def on_toggle_shell(self):
  2835. """
  2836. toggle shell if is visible close it if closed open it
  2837. :return:
  2838. """
  2839. self.report_usage("on_toggle_shell()")
  2840. if self.ui.shell_dock.isVisible():
  2841. self.ui.shell_dock.hide()
  2842. else:
  2843. self.ui.shell_dock.show()
  2844. def on_edit_join(self, name=None):
  2845. """
  2846. Callback for Edit->Join. Joins the selected geometry objects into
  2847. a new one.
  2848. :return: None
  2849. """
  2850. self.report_usage("on_edit_join()")
  2851. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2852. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2853. tooldias = []
  2854. geo_type_list = []
  2855. objs = self.collection.get_selected()
  2856. for obj in objs:
  2857. geo_type_list.append(obj.multigeo)
  2858. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2859. if len(set(geo_type_list)) != 1:
  2860. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2861. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2862. "convert from one to another and retry joining \n"
  2863. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2864. "the result may not be what was expected. \n"
  2865. "Check the generated GCODE."))
  2866. return
  2867. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2868. if True in geo_type_list:
  2869. def initialize(obj, app):
  2870. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2871. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2872. for v in obj.tools.values():
  2873. v['data']['name'] = obj_name_multi
  2874. self.new_object("geometry", obj_name_multi, initialize)
  2875. else:
  2876. def initialize(obj, app):
  2877. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2878. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2879. for v in obj.tools.values():
  2880. v['data']['name'] = obj_name_single
  2881. self.new_object("geometry", obj_name_single, initialize)
  2882. self.should_we_save = True
  2883. def on_edit_join_exc(self):
  2884. """
  2885. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2886. a new one.
  2887. :return: None
  2888. """
  2889. self.report_usage("on_edit_join_exc()")
  2890. objs = self.collection.get_selected()
  2891. for obj in objs:
  2892. if not isinstance(obj, FlatCAMExcellon):
  2893. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  2894. return
  2895. def initialize(obj, app):
  2896. FlatCAMExcellon.merge(objs, obj)
  2897. self.new_object("excellon", 'Combo_Excellon', initialize)
  2898. self.should_we_save = True
  2899. def on_edit_join_grb(self):
  2900. """
  2901. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2902. a new one.
  2903. :return: None
  2904. """
  2905. self.report_usage("on_edit_join_grb()")
  2906. objs = self.collection.get_selected()
  2907. for obj in objs:
  2908. if not isinstance(obj, FlatCAMGerber):
  2909. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  2910. return
  2911. def initialize(obj, app):
  2912. FlatCAMGerber.merge(objs, obj)
  2913. self.new_object("gerber", 'Combo_Gerber', initialize)
  2914. self.should_we_save = True
  2915. def on_convert_singlegeo_to_multigeo(self):
  2916. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2917. obj = self.collection.get_active()
  2918. if obj is None:
  2919. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2920. return
  2921. if not isinstance(obj, FlatCAMGeometry):
  2922. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2923. return
  2924. obj.multigeo = True
  2925. for tooluid, dict_value in obj.tools.items():
  2926. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2927. if not isinstance(obj.solid_geometry, list):
  2928. obj.solid_geometry = [obj.solid_geometry]
  2929. obj.solid_geometry[:] = []
  2930. obj.plot()
  2931. self.should_we_save = True
  2932. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2933. def on_convert_multigeo_to_singlegeo(self):
  2934. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2935. obj = self.collection.get_active()
  2936. if obj is None:
  2937. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2938. return
  2939. if not isinstance(obj, FlatCAMGeometry):
  2940. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2941. return
  2942. obj.multigeo = False
  2943. total_solid_geometry = []
  2944. for tooluid, dict_value in obj.tools.items():
  2945. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2946. # clear the original geometry
  2947. dict_value['solid_geometry'][:] = []
  2948. obj.solid_geometry = deepcopy(total_solid_geometry)
  2949. obj.plot()
  2950. self.should_we_save = True
  2951. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2952. def on_options_dict_change(self, field):
  2953. self.options_write_form_field(field)
  2954. if field == "units":
  2955. self.set_screen_units(self.options['units'])
  2956. def on_defaults_dict_change(self, field):
  2957. self.defaults_write_form_field(field)
  2958. if field == "units":
  2959. self.set_screen_units(self.defaults['units'])
  2960. def set_screen_units(self, units):
  2961. self.ui.units_label.setText("[" + units.lower() + "]")
  2962. def on_toggle_units(self, no_pref=False):
  2963. """
  2964. Callback for the Units radio-button change in the Options tab.
  2965. Changes the application's default units or the current project's units.
  2966. If changing the project's units, the change propagates to all of
  2967. the objects in the project.
  2968. :return: None
  2969. """
  2970. self.report_usage("on_toggle_units")
  2971. if self.toggle_units_ignore:
  2972. return
  2973. # If option is the same, then ignore
  2974. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2975. self.defaults["units"].upper():
  2976. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2977. return
  2978. # Options to scale
  2979. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2980. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2981. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2982. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  2983. "excellon_z_pdepth",
  2984. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  2985. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  2986. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  2987. "geometry_feedrate_probe",
  2988. 'cncjob_tooldia',
  2989. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  2990. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  2991. "tools_2sided_drilldia", "tools_film_boundary",
  2992. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2993. "tools_panelize_constrainx", "tools_panelize_constrainy",
  2994. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  2995. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  2996. "tools_transform_offset_y",
  2997. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  2998. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  2999. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3000. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3001. 'global_gridx', 'global_gridy', 'global_snap_max']
  3002. def scale_options(sfactor):
  3003. for dim in dimensions:
  3004. if dim == 'excellon_toolchangexy':
  3005. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  3006. coords_xy[0] *= sfactor
  3007. coords_xy[1] *= sfactor
  3008. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3009. elif dim == 'geometry_toolchangexy':
  3010. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  3011. coords_xy[0] *= sfactor
  3012. coords_xy[1] *= sfactor
  3013. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3014. elif dim == 'tools_ncctools':
  3015. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  3016. ncctols[0] *= sfactor
  3017. ncctols[1] *= sfactor
  3018. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  3019. elif dim == 'tools_solderpaste_tools':
  3020. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  3021. sp_tools[0] *= sfactor
  3022. sp_tools[1] *= sfactor
  3023. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  3024. elif dim == 'tools_solderpaste_xy_toolchange':
  3025. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3026. sp_coords[0] *= sfactor
  3027. sp_coords[1] *= sfactor
  3028. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3029. else:
  3030. try:
  3031. self.options[dim] = float(self.options[dim]) * sfactor
  3032. except Exception as e:
  3033. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3034. def scale_defaults(sfactor):
  3035. for dim in dimensions:
  3036. if dim == 'excellon_toolchangexy':
  3037. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  3038. coords_xy[0] *= sfactor
  3039. coords_xy[1] *= sfactor
  3040. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3041. elif dim == 'geometry_toolchangexy':
  3042. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  3043. coords_xy[0] *= sfactor
  3044. coords_xy[1] *= sfactor
  3045. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3046. elif dim == 'tools_ncctools':
  3047. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  3048. ncctols[0] *= sfactor
  3049. ncctols[1] *= sfactor
  3050. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  3051. elif dim == 'tools_solderpaste_tools':
  3052. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  3053. sp_tools[0] *= sfactor
  3054. sp_tools[1] *= sfactor
  3055. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  3056. elif dim == 'tools_solderpaste_xy_toolchange':
  3057. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3058. sp_coords[0] *= sfactor
  3059. sp_coords[1] *= sfactor
  3060. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3061. else:
  3062. try:
  3063. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  3064. except Exception as e:
  3065. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3066. # The scaling factor depending on choice of units.
  3067. factor = 1/25.4
  3068. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3069. factor = 25.4
  3070. # Changing project units. Warn user.
  3071. msgbox = QtWidgets.QMessageBox()
  3072. msgbox.setWindowTitle("Toggle Units")
  3073. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3074. msgbox.setText("<B>Change project units ...</B>")
  3075. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  3076. "properties of all objects to be scaled accordingly.\nContinue?")
  3077. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3078. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3079. msgbox.setDefaultButton(bt_ok)
  3080. msgbox.exec_()
  3081. response = msgbox.clickedButton()
  3082. if response == bt_ok:
  3083. if no_pref is False:
  3084. self.options_read_form()
  3085. scale_options(factor)
  3086. self.options_write_form()
  3087. self.defaults_read_form()
  3088. scale_defaults(factor)
  3089. self.defaults_write_form()
  3090. self.should_we_save = True
  3091. # change this only if the workspace is active
  3092. if self.defaults['global_workspace'] is True:
  3093. self.plotcanvas.draw_workspace()
  3094. # adjust the grid values on the main toolbar
  3095. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  3096. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  3097. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3098. for obj in self.collection.get_list():
  3099. obj.convert_units(units)
  3100. # make that the properties stored in the object are also updated
  3101. self.object_changed.emit(obj)
  3102. obj.build_ui()
  3103. current = self.collection.get_active()
  3104. if current is not None:
  3105. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3106. if not isinstance(current, FlatCAMGeometry):
  3107. current.to_form()
  3108. self.plot_all()
  3109. self.inform.emit(_("[success] Converted units to %s") % units)
  3110. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3111. self.set_screen_units(units)
  3112. else:
  3113. # Undo toggling
  3114. self.toggle_units_ignore = True
  3115. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3116. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3117. else:
  3118. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3119. self.toggle_units_ignore = False
  3120. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3121. self.options_read_form()
  3122. self.defaults_read_form()
  3123. def on_toggle_units_click(self):
  3124. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3125. if self.defaults["units"] == 'MM':
  3126. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3127. else:
  3128. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3129. self.on_toggle_units(no_pref=True)
  3130. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3131. lambda: self.on_toggle_units(no_pref=False))
  3132. def on_fullscreen(self):
  3133. self.report_usage("on_fullscreen()")
  3134. if self.toggle_fscreen is False:
  3135. if sys.platform == 'win32':
  3136. self.ui.showFullScreen()
  3137. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3138. tb.setVisible(False)
  3139. self.ui.splitter_left.setVisible(False)
  3140. self.toggle_fscreen = True
  3141. else:
  3142. if sys.platform == 'win32':
  3143. self.ui.showNormal()
  3144. self.restore_toolbar_view()
  3145. self.ui.splitter_left.setVisible(True)
  3146. self.toggle_fscreen = False
  3147. def on_toggle_plotarea(self):
  3148. self.report_usage("on_toggle_plotarea()")
  3149. try:
  3150. name = self.ui.plot_tab_area.widget(0).objectName()
  3151. except AttributeError:
  3152. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3153. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3154. self.ui.plot_tab_area.protectTab(0)
  3155. return
  3156. if name != 'plotarea':
  3157. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3158. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3159. self.ui.plot_tab_area.protectTab(0)
  3160. else:
  3161. self.ui.plot_tab_area.closeTab(0)
  3162. def on_toggle_notebook(self):
  3163. if self.ui.splitter.sizes()[0] == 0:
  3164. self.ui.splitter.setSizes([1, 1])
  3165. else:
  3166. self.ui.splitter.setSizes([0, 1])
  3167. def on_toggle_axis(self):
  3168. self.report_usage("on_toggle_axis()")
  3169. if self.toggle_axis is False:
  3170. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3171. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3172. self.plotcanvas.redraw()
  3173. self.toggle_axis = True
  3174. else:
  3175. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3176. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3177. self.plotcanvas.redraw()
  3178. self.toggle_axis = False
  3179. def on_toggle_grid(self):
  3180. self.report_usage("on_toggle_grid()")
  3181. self.ui.grid_snap_btn.trigger()
  3182. def on_options_combo_change(self, sel):
  3183. """
  3184. Called when the combo box to choose between application defaults and
  3185. project option changes value. The corresponding variables are
  3186. copied to the UI.
  3187. :param sel: The option index that was chosen.
  3188. :return: None
  3189. """
  3190. # combo_sel = self.ui.notebook.combo_options.get_active()
  3191. App.log.debug("Options --> %s" % sel)
  3192. # form = [self.defaults_form, self.options_form][sel]
  3193. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3194. if sel == 0:
  3195. self.gen_form = self.ui.general_defaults_form
  3196. self.ger_form = self.ui.gerber_defaults_form
  3197. self.exc_form = self.ui.excellon_defaults_form
  3198. self.geo_form = self.ui.geometry_defaults_form
  3199. self.cnc_form = self.ui.cncjob_defaults_form
  3200. self.tools_form = self.ui.tools_defaults_form
  3201. elif sel == 1:
  3202. self.gen_form = self.ui.general_options_form
  3203. self.ger_form = self.ui.gerber_options_form
  3204. self.exc_form = self.ui.excellon_options_form
  3205. self.geo_form = self.ui.geometry_options_form
  3206. self.cnc_form = self.ui.cncjob_options_form
  3207. self.tools_form = self.ui.tools_options_form
  3208. else:
  3209. return
  3210. try:
  3211. self.ui.general_scroll_area.takeWidget()
  3212. except:
  3213. self.log.debug("Nothing to remove")
  3214. self.ui.general_scroll_area.setWidget(self.gen_form)
  3215. self.gen_form.show()
  3216. try:
  3217. self.ui.gerber_scroll_area.takeWidget()
  3218. except:
  3219. self.log.debug("Nothing to remove")
  3220. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3221. self.ger_form.show()
  3222. try:
  3223. self.ui.excellon_scroll_area.takeWidget()
  3224. except:
  3225. self.log.debug("Nothing to remove")
  3226. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3227. self.exc_form.show()
  3228. try:
  3229. self.ui.geometry_scroll_area.takeWidget()
  3230. except:
  3231. self.log.debug("Nothing to remove")
  3232. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3233. self.geo_form.show()
  3234. try:
  3235. self.ui.cncjob_scroll_area.takeWidget()
  3236. except:
  3237. self.log.debug("Nothing to remove")
  3238. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3239. self.cnc_form.show()
  3240. try:
  3241. self.ui.tools_scroll_area.takeWidget()
  3242. except:
  3243. self.log.debug("Nothing to remove")
  3244. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3245. self.tools_form.show()
  3246. self.log.debug("Finished GUI form initialization.")
  3247. # self.options2form()
  3248. def on_excellon_defaults_button(self):
  3249. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3250. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3251. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3252. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3253. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3254. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3255. log.debug("Excellon app defaults loaded ...")
  3256. def on_excellon_options_button(self):
  3257. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3258. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3259. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3260. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3261. self.options_form_fields["excellon_zeros"].set_value('L')
  3262. self.options_form_fields["excellon_units"].set_value('INCH')
  3263. log.debug("Excellon options defaults loaded ...")
  3264. # Setting plot colors handlers
  3265. def on_pf_color_entry(self):
  3266. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3267. self.defaults['global_plot_fill'][7:9]
  3268. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3269. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3270. def on_pf_color_button(self):
  3271. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3272. c_dialog = QtWidgets.QColorDialog()
  3273. plot_fill_color = c_dialog.getColor(initial=current_color)
  3274. if plot_fill_color.isValid() is False:
  3275. return
  3276. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3277. "background-color:%s" % str(plot_fill_color.name()))
  3278. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3279. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3280. self.defaults['global_plot_fill'] = new_val
  3281. def on_pf_color_spinner(self):
  3282. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3283. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3284. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  3285. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3286. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  3287. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3288. def on_pf_color_slider(self):
  3289. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3290. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3291. def on_pl_color_entry(self):
  3292. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3293. self.defaults['global_plot_line'][7:9]
  3294. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3295. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3296. def on_pl_color_button(self):
  3297. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3298. # print(current_color)
  3299. c_dialog = QtWidgets.QColorDialog()
  3300. plot_line_color = c_dialog.getColor(initial=current_color)
  3301. if plot_line_color.isValid() is False:
  3302. return
  3303. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3304. "background-color:%s" % str(plot_line_color.name()))
  3305. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3306. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3307. self.defaults['global_plot_line'] = new_val_line
  3308. # Setting selection colors (left - right) handlers
  3309. def on_sf_color_entry(self):
  3310. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3311. self.defaults['global_sel_fill'][7:9]
  3312. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3313. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3314. def on_sf_color_button(self):
  3315. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3316. c_dialog = QtWidgets.QColorDialog()
  3317. plot_fill_color = c_dialog.getColor(initial=current_color)
  3318. if plot_fill_color.isValid() is False:
  3319. return
  3320. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3321. "background-color:%s" % str(plot_fill_color.name()))
  3322. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3323. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3324. self.defaults['global_sel_fill'] = new_val
  3325. def on_sf_color_spinner(self):
  3326. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3327. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3328. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  3329. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3330. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  3331. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3332. def on_sf_color_slider(self):
  3333. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3334. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3335. def on_sl_color_entry(self):
  3336. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3337. self.defaults['global_sel_line'][7:9]
  3338. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3339. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3340. def on_sl_color_button(self):
  3341. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3342. c_dialog = QtWidgets.QColorDialog()
  3343. plot_line_color = c_dialog.getColor(initial=current_color)
  3344. if plot_line_color.isValid() is False:
  3345. return
  3346. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3347. "background-color:%s" % str(plot_line_color.name()))
  3348. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3349. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3350. self.defaults['global_sel_line'] = new_val_line
  3351. # Setting selection colors (right - left) handlers
  3352. def on_alt_sf_color_entry(self):
  3353. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3354. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3355. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3356. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3357. def on_alt_sf_color_button(self):
  3358. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3359. c_dialog = QtWidgets.QColorDialog()
  3360. plot_fill_color = c_dialog.getColor(initial=current_color)
  3361. if plot_fill_color.isValid() is False:
  3362. return
  3363. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3364. "background-color:%s" % str(plot_fill_color.name()))
  3365. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3366. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3367. self.defaults['global_alt_sel_fill'] = new_val
  3368. def on_alt_sf_color_spinner(self):
  3369. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3370. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3371. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  3372. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3373. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  3374. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3375. def on_alt_sf_color_slider(self):
  3376. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3377. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3378. def on_alt_sl_color_entry(self):
  3379. self.defaults['global_alt_sel_line'] = \
  3380. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  3381. self.defaults['global_alt_sel_line'][7:9]
  3382. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3383. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3384. def on_alt_sl_color_button(self):
  3385. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3386. c_dialog = QtWidgets.QColorDialog()
  3387. plot_line_color = c_dialog.getColor(initial=current_color)
  3388. if plot_line_color.isValid() is False:
  3389. return
  3390. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3391. "background-color:%s" % str(plot_line_color.name()))
  3392. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3393. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3394. self.defaults['global_alt_sel_line'] = new_val_line
  3395. # Setting Editor colors
  3396. def on_draw_color_entry(self):
  3397. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3398. .draw_color_entry.get_value()
  3399. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3400. "background-color:%s" % str(self.defaults['global_draw_color']))
  3401. def on_draw_color_button(self):
  3402. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3403. c_dialog = QtWidgets.QColorDialog()
  3404. draw_color = c_dialog.getColor(initial=current_color)
  3405. if draw_color.isValid() is False:
  3406. return
  3407. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3408. "background-color:%s" % str(draw_color.name()))
  3409. new_val = str(draw_color.name())
  3410. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3411. self.defaults['global_draw_color'] = new_val
  3412. def on_sel_draw_color_entry(self):
  3413. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3414. .sel_draw_color_entry.get_value()
  3415. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3416. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3417. def on_sel_draw_color_button(self):
  3418. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3419. c_dialog = QtWidgets.QColorDialog()
  3420. sel_draw_color = c_dialog.getColor(initial=current_color)
  3421. if sel_draw_color.isValid() is False:
  3422. return
  3423. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3424. "background-color:%s" % str(sel_draw_color.name()))
  3425. new_val_sel = str(sel_draw_color.name())
  3426. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3427. self.defaults['global_sel_draw_color'] = new_val_sel
  3428. def on_proj_color_entry(self):
  3429. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  3430. .proj_color_entry.get_value()
  3431. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3432. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  3433. def on_proj_color_button(self):
  3434. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  3435. c_dialog = QtWidgets.QColorDialog()
  3436. proj_color = c_dialog.getColor(initial=current_color)
  3437. if proj_color.isValid() is False:
  3438. return
  3439. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3440. "background-color:%s" % str(proj_color.name()))
  3441. new_val_sel = str(proj_color.name())
  3442. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  3443. self.defaults['global_proj_item_color'] = new_val_sel
  3444. def on_proj_color_dis_entry(self):
  3445. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  3446. .proj_color_dis_entry.get_value()
  3447. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3448. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  3449. def on_proj_color_dis_button(self):
  3450. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  3451. c_dialog = QtWidgets.QColorDialog()
  3452. proj_color = c_dialog.getColor(initial=current_color)
  3453. if proj_color.isValid() is False:
  3454. return
  3455. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3456. "background-color:%s" % str(proj_color.name()))
  3457. new_val_sel = str(proj_color.name())
  3458. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  3459. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3460. def on_deselect_all(self):
  3461. self.collection.set_all_inactive()
  3462. self.delete_selection_shape()
  3463. def on_workspace_modified(self):
  3464. self.save_defaults(silent=True)
  3465. self.plotcanvas.draw_workspace()
  3466. def on_workspace(self):
  3467. self.report_usage("on_workspace()")
  3468. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3469. self.plotcanvas.restore_workspace()
  3470. else:
  3471. self.plotcanvas.delete_workspace()
  3472. self.save_defaults(silent=True)
  3473. def on_workspace_menu(self):
  3474. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3475. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3476. else:
  3477. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3478. self.on_workspace()
  3479. def on_layout(self, index=None, lay=None):
  3480. self.report_usage("on_layout()")
  3481. if lay:
  3482. current_layout = lay
  3483. else:
  3484. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3485. settings = QSettings("Open Source", "FlatCAM")
  3486. settings.setValue('layout', current_layout)
  3487. # This will write the setting to the platform specific storage.
  3488. del settings
  3489. # first remove the toolbars:
  3490. try:
  3491. self.ui.removeToolBar(self.ui.toolbarfile)
  3492. self.ui.removeToolBar(self.ui.toolbargeo)
  3493. self.ui.removeToolBar(self.ui.toolbarview)
  3494. self.ui.removeToolBar(self.ui.toolbarshell)
  3495. self.ui.removeToolBar(self.ui.toolbartools)
  3496. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3497. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3498. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3499. self.ui.removeToolBar(self.ui.snap_toolbar)
  3500. self.ui.removeToolBar(self.ui.toolbarshell)
  3501. except:
  3502. pass
  3503. if current_layout == 'standard':
  3504. ### TOOLBAR INSTALLATION ###
  3505. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3506. self.ui.toolbarfile.setObjectName('File_TB')
  3507. self.ui.addToolBar(self.ui.toolbarfile)
  3508. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3509. self.ui.toolbargeo.setObjectName('Edit_TB')
  3510. self.ui.addToolBar(self.ui.toolbargeo)
  3511. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3512. self.ui.toolbarview.setObjectName('View_TB')
  3513. self.ui.addToolBar(self.ui.toolbarview)
  3514. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3515. self.ui.toolbarshell.setObjectName('Shell_TB')
  3516. self.ui.addToolBar(self.ui.toolbarshell)
  3517. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3518. self.ui.toolbartools.setObjectName('Tools_TB')
  3519. self.ui.addToolBar(self.ui.toolbartools)
  3520. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3521. self.ui.exc_edit_toolbar.setVisible(False)
  3522. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3523. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3524. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3525. self.ui.geo_edit_toolbar.setVisible(False)
  3526. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3527. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3528. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3529. self.ui.grb_edit_toolbar.setVisible(False)
  3530. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3531. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3532. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3533. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3534. # self.ui.snap_toolbar.setMaximumHeight(30)
  3535. self.ui.addToolBar(self.ui.snap_toolbar)
  3536. self.ui.corner_snap_btn.setVisible(False)
  3537. self.ui.snap_magnet.setVisible(False)
  3538. elif current_layout == 'compact':
  3539. ### TOOLBAR INSTALLATION ###
  3540. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3541. self.ui.toolbarfile.setObjectName('File_TB')
  3542. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3543. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3544. self.ui.toolbargeo.setObjectName('Edit_TB')
  3545. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3546. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3547. self.ui.toolbarview.setObjectName('View_TB')
  3548. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3549. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3550. self.ui.toolbarshell.setObjectName('Shell_TB')
  3551. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3552. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3553. self.ui.toolbartools.setObjectName('Tools_TB')
  3554. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3555. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3556. # self.ui.geo_edit_toolbar.setVisible(False)
  3557. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3558. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3559. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3560. # self.ui.grb_edit_toolbar.setVisible(False)
  3561. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3562. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  3563. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3564. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3565. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3566. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3567. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3568. self.ui.snap_toolbar.setMaximumHeight(30)
  3569. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3570. self.ui.corner_snap_btn.setVisible(True)
  3571. self.ui.snap_magnet.setVisible(True)
  3572. # add all the actions to the toolbars
  3573. self.ui.populate_toolbars()
  3574. # reconnect all the signals to the toolbar actions
  3575. self.connect_toolbar_signals()
  3576. self.ui.grid_snap_btn.setChecked(True)
  3577. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3578. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3579. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3580. self.ui.grid_gap_link_cb.setChecked(True)
  3581. def on_cnc_custom_parameters(self, signal_text):
  3582. if signal_text == 'Parameters':
  3583. return
  3584. else:
  3585. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3586. def on_save_button(self):
  3587. self.save_defaults(silent=False)
  3588. # load the defaults so they are updated into the app
  3589. self.load_defaults(filename='current_defaults')
  3590. # Re-fresh project options
  3591. self.on_options_app2project()
  3592. def handlePrint(self):
  3593. self.report_usage("handlePrint()")
  3594. dialog = QtPrintSupport.QPrintDialog()
  3595. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3596. self.ui.code_editor.document().print_(dialog.printer())
  3597. def handlePreview(self):
  3598. self.report_usage("handlePreview()")
  3599. dialog = QtPrintSupport.QPrintPreviewDialog()
  3600. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3601. dialog.exec_()
  3602. def handleTextChanged(self):
  3603. # enable = not self.ui.code_editor.document().isEmpty()
  3604. # self.ui.buttonPrint.setEnabled(enable)
  3605. # self.ui.buttonPreview.setEnabled(enable)
  3606. pass
  3607. def handleOpen(self, filt=None):
  3608. self.report_usage("handleOpen()")
  3609. if filt:
  3610. _filter_ = filt
  3611. else:
  3612. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3613. "All Files (*.*)"
  3614. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  3615. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  3616. if path:
  3617. file = QtCore.QFile(path)
  3618. if file.open(QtCore.QIODevice.ReadOnly):
  3619. stream = QtCore.QTextStream(file)
  3620. self.gcode_edited = stream.readAll()
  3621. self.ui.code_editor.setPlainText(self.gcode_edited)
  3622. file.close()
  3623. def handleSaveGCode(self,name=None, filt=None):
  3624. self.report_usage("handleSaveGCode()")
  3625. if filt:
  3626. _filter_ = filt
  3627. else:
  3628. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3629. "All Files (*.*)"
  3630. if name:
  3631. obj_name = name
  3632. else:
  3633. try:
  3634. obj_name = self.collection.get_active().options['name']
  3635. except AttributeError:
  3636. obj_name = 'file'
  3637. if filt is None:
  3638. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3639. try:
  3640. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3641. caption=_("Export G-Code ..."),
  3642. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3643. filter=_filter_
  3644. )[0])
  3645. except TypeError:
  3646. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3647. if filename == "":
  3648. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  3649. return
  3650. else:
  3651. try:
  3652. my_gcode = self.ui.code_editor.toPlainText()
  3653. with open(filename, 'w') as f:
  3654. for line in my_gcode:
  3655. f.write(line)
  3656. except FileNotFoundError:
  3657. self.inform.emit(_("[WARNING] No such file or directory"))
  3658. return
  3659. # Just for adding it to the recent files list.
  3660. if self.defaults["global_open_style"] is False:
  3661. self.file_opened.emit("cncjob", filename)
  3662. self.file_saved.emit("cncjob", filename)
  3663. self.inform.emit(_("Saved to: %s") % filename)
  3664. def handleFindGCode(self):
  3665. self.report_usage("handleFindGCode()")
  3666. flags = QtGui.QTextDocument.FindCaseSensitively
  3667. text_to_be_found = self.ui.entryFind.get_value()
  3668. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3669. if r is False:
  3670. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3671. def handleReplaceGCode(self):
  3672. self.report_usage("handleReplaceGCode()")
  3673. old = self.ui.entryFind.get_value()
  3674. new = self.ui.entryReplace.get_value()
  3675. if self.ui.sel_all_cb.isChecked():
  3676. while True:
  3677. cursor = self.ui.code_editor.textCursor()
  3678. cursor.beginEditBlock()
  3679. flags = QtGui.QTextDocument.FindCaseSensitively
  3680. # self.ui.editor is the QPlainTextEdit
  3681. r = self.ui.code_editor.find(str(old), flags)
  3682. if r:
  3683. qc = self.ui.code_editor.textCursor()
  3684. if qc.hasSelection():
  3685. qc.insertText(new)
  3686. else:
  3687. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3688. break
  3689. # Mark end of undo block
  3690. cursor.endEditBlock()
  3691. else:
  3692. cursor = self.ui.code_editor.textCursor()
  3693. cursor.beginEditBlock()
  3694. qc = self.ui.code_editor.textCursor()
  3695. if qc.hasSelection():
  3696. qc.insertText(new)
  3697. # Mark end of undo block
  3698. cursor.endEditBlock()
  3699. def on_tool_add_keypress(self):
  3700. ## Current application units in Upper Case
  3701. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3702. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3703. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3704. if notebook_widget_name == 'selected_tab':
  3705. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3706. # Tool add works for Geometry only if Advanced is True in Preferences
  3707. if self.defaults["global_app_level"] == 'a':
  3708. tool_add_popup = FCInputDialog(title="New Tool ...",
  3709. text='Enter a Tool Diameter:',
  3710. min=0.0000, max=99.9999, decimals=4)
  3711. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3712. val, ok = tool_add_popup.get_value()
  3713. if ok:
  3714. if float(val) == 0:
  3715. self.inform.emit(
  3716. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3717. return
  3718. self.collection.get_active().on_tool_add(dia=float(val))
  3719. else:
  3720. self.inform.emit(
  3721. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3722. else:
  3723. msgbox = QtWidgets.QMessageBox()
  3724. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3725. "Go to Preferences -> General - Show Advanced Options."))
  3726. msgbox.setWindowTitle("Tool adding ...")
  3727. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3728. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3729. msgbox.setDefaultButton(bt_ok)
  3730. msgbox.exec_()
  3731. # work only if the notebook tab on focus is the Tools_Tab
  3732. if notebook_widget_name == 'tool_tab':
  3733. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3734. tool_add_popup = FCInputDialog(title="New Tool ...",
  3735. text='Enter a Tool Diameter:',
  3736. min=0.0000, max=99.9999, decimals=4)
  3737. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3738. val, ok = tool_add_popup.get_value()
  3739. # and only if the tool is NCC Tool
  3740. if tool_widget == self.ncclear_tool.toolName:
  3741. if ok:
  3742. if float(val) == 0:
  3743. self.inform.emit(
  3744. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3745. return
  3746. self.ncclear_tool.on_tool_add(dia=float(val))
  3747. else:
  3748. self.inform.emit(
  3749. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3750. # and only if the tool is Paint Area Tool
  3751. elif tool_widget == self.paint_tool.toolName:
  3752. if ok:
  3753. if float(val) == 0:
  3754. self.inform.emit(
  3755. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3756. return
  3757. self.paint_tool.on_tool_add(dia=float(val))
  3758. else:
  3759. self.inform.emit(
  3760. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3761. # and only if the tool is Solder Paste Dispensing Tool
  3762. elif tool_widget == self.paste_tool.toolName:
  3763. if ok:
  3764. if float(val) == 0:
  3765. self.inform.emit(
  3766. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3767. return
  3768. self.paste_tool.on_tool_add(dia=float(val))
  3769. else:
  3770. self.inform.emit(
  3771. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3772. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3773. # See description bellow.
  3774. def on_delete_keypress(self):
  3775. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3776. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3777. if notebook_widget_name == 'selected_tab':
  3778. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3779. self.collection.get_active().on_tool_delete()
  3780. # work only if the notebook tab on focus is the Tools_Tab
  3781. elif notebook_widget_name == 'tool_tab':
  3782. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3783. # and only if the tool is NCC Tool
  3784. if tool_widget == self.ncclear_tool.toolName:
  3785. self.ncclear_tool.on_tool_delete()
  3786. # and only if the tool is Paint Tool
  3787. elif tool_widget == self.paint_tool.toolName:
  3788. self.paint_tool.on_tool_delete()
  3789. # and only if the tool is Solder Paste Dispensing Tool
  3790. elif tool_widget == self.paste_tool.toolName:
  3791. self.paste_tool.on_tool_delete()
  3792. else:
  3793. self.on_delete()
  3794. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3795. # some screens you have to be careful where you hover with your mouse.
  3796. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3797. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3798. # Complicated, I know :)
  3799. def on_delete(self):
  3800. """
  3801. Delete the currently selected FlatCAMObjs.
  3802. :return: None
  3803. """
  3804. self.report_usage("on_delete()")
  3805. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3806. # a geometry object before we update it.
  3807. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3808. if self.collection.get_active():
  3809. self.log.debug("on_delete()")
  3810. self.report_usage("on_delete")
  3811. while (self.collection.get_active()):
  3812. obj_active = self.collection.get_active()
  3813. # if the deleted object is FlatCAMGerber then make sure to delete the possbile mark shapes
  3814. if isinstance(obj_active, FlatCAMGerber):
  3815. for el in obj_active.mark_shapes:
  3816. obj_active.mark_shapes[el].clear(update=True)
  3817. obj_active.mark_shapes[el].enabled = False
  3818. obj_active.mark_shapes[el] = None
  3819. self.delete_first_selected()
  3820. self.inform.emit(_("Object(s) deleted ..."))
  3821. # make sure that the selection shape is deleted, too
  3822. self.delete_selection_shape()
  3823. else:
  3824. self.inform.emit(_("Failed. No object(s) selected..."))
  3825. else:
  3826. self.inform.emit(_("Save the work in Editor and try again ..."))
  3827. def on_set_origin(self):
  3828. """
  3829. Set the origin to the left mouse click position
  3830. :return: None
  3831. """
  3832. # display the message for the user
  3833. # and ask him to click on the desired position
  3834. self.report_usage("on_set_origin()")
  3835. self.inform.emit(_('Click to set the origin ...'))
  3836. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3837. def on_jump_to(self, custom_location=None, fit_center=True):
  3838. """
  3839. Jump to a location by setting the mouse cursor location
  3840. :return:
  3841. """
  3842. self.report_usage("on_jump_to()")
  3843. if not custom_location:
  3844. dia_box = Dialog_box(title=_("Jump to ..."),
  3845. label=_("Enter the coordinates in format X,Y:"),
  3846. icon=QtGui.QIcon('share/jump_to16.png'))
  3847. if dia_box.ok is True:
  3848. try:
  3849. location = eval(dia_box.location)
  3850. if not isinstance(location, tuple):
  3851. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3852. return
  3853. except:
  3854. return
  3855. else:
  3856. return
  3857. else:
  3858. location = custom_location
  3859. if fit_center:
  3860. self.plotcanvas.fit_center(loc=location)
  3861. cursor = QtGui.QCursor()
  3862. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3863. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3864. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3865. self.inform.emit(_("[success] Done."))
  3866. def on_copy_object(self):
  3867. self.report_usage("on_copy_object()")
  3868. def initialize(obj_init, app):
  3869. obj_init.solid_geometry = obj.solid_geometry
  3870. try:
  3871. obj_init.follow_geometry = obj.follow_geometry
  3872. except AttributeError:
  3873. pass
  3874. try:
  3875. obj_init.apertures = obj.apertures
  3876. except AttributeError:
  3877. pass
  3878. try:
  3879. if obj.tools:
  3880. obj_init.tools = obj.tools
  3881. except Exception as e:
  3882. log.debug("App.on_copy_object() --> %s" % str(e))
  3883. def initialize_excellon(obj_init, app):
  3884. obj_init.tools = obj.tools
  3885. # drills are offset, so they need to be deep copied
  3886. obj_init.drills = deepcopy(obj.drills)
  3887. # slots are offset, so they need to be deep copied
  3888. obj_init.slots = deepcopy(obj.slots)
  3889. obj_init.create_geometry()
  3890. for obj in self.collection.get_selected():
  3891. obj_name = obj.options["name"]
  3892. try:
  3893. if isinstance(obj, FlatCAMExcellon):
  3894. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3895. elif isinstance(obj,FlatCAMGerber):
  3896. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3897. elif isinstance(obj,FlatCAMGeometry):
  3898. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3899. except Exception as e:
  3900. return "Operation failed: %s" % str(e)
  3901. def on_copy_object2(self, custom_name):
  3902. def initialize_geometry(obj_init, app):
  3903. obj_init.solid_geometry = obj.solid_geometry
  3904. try:
  3905. obj_init.follow_geometry = obj.follow_geometry
  3906. except AttributeError:
  3907. pass
  3908. try:
  3909. obj_init.apertures = obj.apertures
  3910. except AttributeError:
  3911. pass
  3912. try:
  3913. if obj.tools:
  3914. obj_init.tools = obj.tools
  3915. except Exception as e:
  3916. log.debug("on_copy_object2() --> %s" % str(e))
  3917. def initialize_gerber(obj_init, app):
  3918. obj_init.solid_geometry = obj.solid_geometry
  3919. obj_init.apertures = deepcopy(obj.apertures)
  3920. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3921. def initialize_excellon(obj_init, app):
  3922. obj_init.tools = obj.tools
  3923. # drills are offset, so they need to be deep copied
  3924. obj_init.drills = deepcopy(obj.drills)
  3925. # slots are offset, so they need to be deep copied
  3926. obj_init.slots = deepcopy(obj.slots)
  3927. obj_init.create_geometry()
  3928. for obj in self.collection.get_selected():
  3929. obj_name = obj.options["name"]
  3930. try:
  3931. if isinstance(obj, FlatCAMExcellon):
  3932. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3933. elif isinstance(obj,FlatCAMGerber):
  3934. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3935. elif isinstance(obj,FlatCAMGeometry):
  3936. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3937. except Exception as e:
  3938. return "Operation failed: %s" % str(e)
  3939. def on_rename_object(self, text):
  3940. self.report_usage("on_rename_object()")
  3941. named_obj = self.collection.get_active()
  3942. for obj in named_obj:
  3943. if obj is list:
  3944. self.on_rename_object(text)
  3945. else:
  3946. try:
  3947. obj.options['name'] = text
  3948. except Exception as e:
  3949. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  3950. def convert_any2geo(self):
  3951. self.report_usage("convert_any2geo()")
  3952. def initialize(obj_init, app):
  3953. obj_init.solid_geometry = obj.solid_geometry
  3954. try:
  3955. obj_init.follow_geometry = obj.follow_geometry
  3956. except AttributeError:
  3957. pass
  3958. try:
  3959. obj_init.apertures = obj.apertures
  3960. except AttributeError:
  3961. pass
  3962. try:
  3963. if obj.tools:
  3964. obj_init.tools = obj.tools
  3965. except AttributeError:
  3966. pass
  3967. def initialize_excellon(obj_init, app):
  3968. # objs = self.collection.get_selected()
  3969. # FlatCAMGeometry.merge(objs, obj)
  3970. solid_geo = []
  3971. for tool in obj.tools:
  3972. for geo in obj.tools[tool]['solid_geometry']:
  3973. solid_geo.append(geo)
  3974. obj_init.solid_geometry = deepcopy(solid_geo)
  3975. if not self.collection.get_selected():
  3976. log.warning("App.convert_any2geo --> No object selected")
  3977. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  3978. return
  3979. for obj in self.collection.get_selected():
  3980. obj_name = obj.options["name"]
  3981. try:
  3982. if isinstance(obj, FlatCAMExcellon):
  3983. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  3984. else:
  3985. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  3986. except Exception as e:
  3987. return "Operation failed: %s" % str(e)
  3988. def convert_any2gerber(self):
  3989. self.report_usage("convert_any2gerber()")
  3990. def initialize_geometry(obj_init, app):
  3991. apertures = {}
  3992. apid = 0
  3993. apertures[str(apid)] = {}
  3994. apertures[str(apid)]['geometry'] = []
  3995. for obj_orig in obj.solid_geometry:
  3996. new_elem = dict()
  3997. new_elem['solid'] = obj_orig
  3998. new_elem['follow'] = obj_orig.exterior
  3999. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4000. apertures[str(apid)]['size'] = 0.0
  4001. apertures[str(apid)]['type'] = 'C'
  4002. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4003. obj_init.apertures = deepcopy(apertures)
  4004. def initialize_excellon(obj_init, app):
  4005. apertures = {}
  4006. apid = 10
  4007. for tool in obj.tools:
  4008. apertures[str(apid)] = {}
  4009. apertures[str(apid)]['geometry'] = []
  4010. for geo in obj.tools[tool]['solid_geometry']:
  4011. new_el = dict()
  4012. new_el['solid'] = geo
  4013. new_el['follow'] = geo.exterior
  4014. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4015. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4016. apertures[str(apid)]['type'] = 'C'
  4017. apid += 1
  4018. # create solid_geometry
  4019. solid_geometry = []
  4020. for apid in apertures:
  4021. for geo_el in apertures[apid]['geometry']:
  4022. solid_geometry.append(geo_el['solid'])
  4023. solid_geometry = MultiPolygon(solid_geometry)
  4024. solid_geometry = solid_geometry.buffer(0.0000001)
  4025. obj_init.solid_geometry = deepcopy(solid_geometry)
  4026. obj_init.apertures = deepcopy(apertures)
  4027. # clear the working objects (perhaps not necessary due of Python GC)
  4028. apertures.clear()
  4029. if not self.collection.get_selected():
  4030. log.warning("App.convert_any2gerber --> No object selected")
  4031. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4032. return
  4033. for obj in self.collection.get_selected():
  4034. obj_name = obj.options["name"]
  4035. try:
  4036. if isinstance(obj, FlatCAMExcellon):
  4037. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4038. elif isinstance(obj, FlatCAMGeometry):
  4039. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4040. else:
  4041. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4042. except Exception as e:
  4043. return "Operation failed: %s" % str(e)
  4044. def on_set_zero_click(self, event):
  4045. #this function will be available only for mouse left click
  4046. pos =[]
  4047. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4048. if event.button == 1:
  4049. if self.grid_status() == True:
  4050. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4051. else:
  4052. pos = pos_canvas
  4053. x = 0 - pos[0]
  4054. y = 0 - pos[1]
  4055. for obj in self.collection.get_list():
  4056. obj.offset((x,y))
  4057. self.object_changed.emit(obj)
  4058. obj.plot()
  4059. # Update the object bounding box options
  4060. a, b, c, d = obj.bounds()
  4061. obj.options['xmin'] = a
  4062. obj.options['ymin'] = b
  4063. obj.options['xmax'] = c
  4064. obj.options['ymax'] = d
  4065. # self.plot_all(zoom=False)
  4066. self.inform.emit(_('[success] Origin set ...'))
  4067. self.plotcanvas.fit_view()
  4068. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4069. self.should_we_save = True
  4070. def on_selectall(self):
  4071. self.report_usage("on_selectall()")
  4072. # delete the possible selection box around a possible selected object
  4073. self.delete_selection_shape()
  4074. for name in self.collection.get_names():
  4075. self.collection.set_active(name)
  4076. curr_sel_obj = self.collection.get_by_name(name)
  4077. # create the selection box around the selected object
  4078. if self.defaults['global_selection_shape'] is True:
  4079. self.draw_selection_shape(curr_sel_obj)
  4080. def on_preferences(self):
  4081. # add the tab if it was closed
  4082. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4083. # delete the absolute and relative position and messages in the infobar
  4084. self.ui.position_label.setText("")
  4085. self.ui.rel_position_label.setText("")
  4086. # Switch plot_area to preferences page
  4087. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4088. self.ui.show()
  4089. def on_flipy(self):
  4090. self.report_usage("on_flipy()")
  4091. obj_list = self.collection.get_selected()
  4092. xminlist = []
  4093. yminlist = []
  4094. xmaxlist = []
  4095. ymaxlist = []
  4096. if not obj_list:
  4097. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  4098. else:
  4099. try:
  4100. # first get a bounding box to fit all
  4101. for obj in obj_list:
  4102. xmin, ymin, xmax, ymax = obj.bounds()
  4103. xminlist.append(xmin)
  4104. yminlist.append(ymin)
  4105. xmaxlist.append(xmax)
  4106. ymaxlist.append(ymax)
  4107. # get the minimum x,y and maximum x,y for all objects selected
  4108. xminimal = min(xminlist)
  4109. yminimal = min(yminlist)
  4110. xmaximal = max(xmaxlist)
  4111. ymaximal = max(ymaxlist)
  4112. px = 0.5 * (xminimal + xmaximal)
  4113. py = 0.5 * (yminimal + ymaximal)
  4114. # execute mirroring
  4115. for obj in obj_list:
  4116. obj.mirror('X', [px, py])
  4117. obj.plot()
  4118. self.object_changed.emit(obj)
  4119. self.inform.emit(_("[success] Flip on Y axis done."))
  4120. except Exception as e:
  4121. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4122. return
  4123. def on_flipx(self):
  4124. self.report_usage("on_flipx()")
  4125. obj_list = self.collection.get_selected()
  4126. xminlist = []
  4127. yminlist = []
  4128. xmaxlist = []
  4129. ymaxlist = []
  4130. if not obj_list:
  4131. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  4132. else:
  4133. try:
  4134. # first get a bounding box to fit all
  4135. for obj in obj_list:
  4136. xmin, ymin, xmax, ymax = obj.bounds()
  4137. xminlist.append(xmin)
  4138. yminlist.append(ymin)
  4139. xmaxlist.append(xmax)
  4140. ymaxlist.append(ymax)
  4141. # get the minimum x,y and maximum x,y for all objects selected
  4142. xminimal = min(xminlist)
  4143. yminimal = min(yminlist)
  4144. xmaximal = max(xmaxlist)
  4145. ymaximal = max(ymaxlist)
  4146. px = 0.5 * (xminimal + xmaximal)
  4147. py = 0.5 * (yminimal + ymaximal)
  4148. # execute mirroring
  4149. for obj in obj_list:
  4150. obj.mirror('Y', [px, py])
  4151. obj.plot()
  4152. self.object_changed.emit(obj)
  4153. self.inform.emit(_("[success] Flip on X axis done."))
  4154. except Exception as e:
  4155. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4156. return
  4157. def on_rotate(self, silent=False, preset=None):
  4158. self.report_usage("on_rotate()")
  4159. obj_list = self.collection.get_selected()
  4160. xminlist = []
  4161. yminlist = []
  4162. xmaxlist = []
  4163. ymaxlist = []
  4164. if not obj_list:
  4165. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  4166. else:
  4167. if silent is False:
  4168. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4169. min=-360, max=360, decimals=4,
  4170. init_val=float(self.defaults['tools_transform_rotate']))
  4171. num, ok = rotatebox.get_value()
  4172. else:
  4173. num = preset
  4174. ok = True
  4175. if ok:
  4176. try:
  4177. # first get a bounding box to fit all
  4178. for obj in obj_list:
  4179. xmin, ymin, xmax, ymax = obj.bounds()
  4180. xminlist.append(xmin)
  4181. yminlist.append(ymin)
  4182. xmaxlist.append(xmax)
  4183. ymaxlist.append(ymax)
  4184. # get the minimum x,y and maximum x,y for all objects selected
  4185. xminimal = min(xminlist)
  4186. yminimal = min(yminlist)
  4187. xmaximal = max(xmaxlist)
  4188. ymaximal = max(ymaxlist)
  4189. px = 0.5 * (xminimal + xmaximal)
  4190. py = 0.5 * (yminimal + ymaximal)
  4191. for sel_obj in obj_list:
  4192. sel_obj.rotate(-float(num), point=(px, py))
  4193. sel_obj.plot()
  4194. self.object_changed.emit(sel_obj)
  4195. self.inform.emit(_("[success] Rotation done."))
  4196. except Exception as e:
  4197. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  4198. return
  4199. def on_skewx(self):
  4200. self.report_usage("on_skewx()")
  4201. obj_list = self.collection.get_selected()
  4202. xminlist = []
  4203. yminlist = []
  4204. if not obj_list:
  4205. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  4206. else:
  4207. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4208. min=-360, max=360, decimals=4,
  4209. init_val=float(self.defaults['tools_transform_skew_x']))
  4210. num, ok = skewxbox.get_value()
  4211. if ok:
  4212. # first get a bounding box to fit all
  4213. for obj in obj_list:
  4214. xmin, ymin, xmax, ymax = obj.bounds()
  4215. xminlist.append(xmin)
  4216. yminlist.append(ymin)
  4217. # get the minimum x,y and maximum x,y for all objects selected
  4218. xminimal = min(xminlist)
  4219. yminimal = min(yminlist)
  4220. for obj in obj_list:
  4221. obj.skew(num, 0, point=(xminimal, yminimal))
  4222. obj.plot()
  4223. self.object_changed.emit(obj)
  4224. self.inform.emit(_("[success] Skew on X axis done."))
  4225. def on_skewy(self):
  4226. self.report_usage("on_skewy()")
  4227. obj_list = self.collection.get_selected()
  4228. xminlist = []
  4229. yminlist = []
  4230. if not obj_list:
  4231. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  4232. else:
  4233. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4234. min=-360, max=360, decimals=4,
  4235. init_val=float(self.defaults['tools_transform_skew_y']))
  4236. num, ok = skewybox.get_value()
  4237. if ok:
  4238. # first get a bounding box to fit all
  4239. for obj in obj_list:
  4240. xmin, ymin, xmax, ymax = obj.bounds()
  4241. xminlist.append(xmin)
  4242. yminlist.append(ymin)
  4243. # get the minimum x,y and maximum x,y for all objects selected
  4244. xminimal = min(xminlist)
  4245. yminimal = min(yminlist)
  4246. for obj in obj_list:
  4247. obj.skew(0, num, point=(xminimal, yminimal))
  4248. obj.plot()
  4249. self.object_changed.emit(obj)
  4250. self.inform.emit(_("[success] Skew on Y axis done."))
  4251. def delete_first_selected(self):
  4252. # Keep this for later
  4253. try:
  4254. name = self.collection.get_active().options["name"]
  4255. except AttributeError:
  4256. self.log.debug("Nothing selected for deletion")
  4257. return
  4258. # Remove plot
  4259. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4260. # self.plotcanvas.auto_adjust_axes()
  4261. # Clear form
  4262. self.setup_component_editor()
  4263. # Remove from dictionary
  4264. self.collection.delete_active()
  4265. self.inform.emit("Object deleted: %s" % name)
  4266. def on_plots_updated(self):
  4267. """
  4268. Callback used to report when the plots have changed.
  4269. Adjust axes and zooms to fit.
  4270. :return: None
  4271. """
  4272. # self.plotcanvas.auto_adjust_axes()
  4273. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  4274. self.on_zoom_fit(None)
  4275. self.collection.update_view()
  4276. # TODO: Rework toolbar 'clear', 'replot' functions
  4277. def on_toolbar_replot(self):
  4278. """
  4279. Callback for toolbar button. Re-plots all objects.
  4280. :return: None
  4281. """
  4282. self.report_usage("on_toolbar_replot")
  4283. self.log.debug("on_toolbar_replot()")
  4284. try:
  4285. self.collection.get_active().read_form()
  4286. except AttributeError:
  4287. self.log.debug("on_toolbar_replot(): AttributeError")
  4288. pass
  4289. self.plot_all()
  4290. def on_row_activated(self, index):
  4291. if index.isValid():
  4292. if index.internalPointer().parent_item != self.collection.root_item:
  4293. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4294. def grid_status(self):
  4295. if self.ui.grid_snap_btn.isChecked():
  4296. return 1
  4297. else:
  4298. return 0
  4299. def populate_cmenu_grids(self):
  4300. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4301. self.ui.cmenu_gridmenu.clear()
  4302. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4303. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  4304. grid_toggle.setCheckable(True)
  4305. if self.grid_status():
  4306. grid_toggle.setChecked(True)
  4307. else:
  4308. grid_toggle.setChecked(False)
  4309. self.ui.cmenu_gridmenu.addSeparator()
  4310. for grid in sorted_list:
  4311. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4312. action.triggered.connect(self.set_grid)
  4313. self.ui.cmenu_gridmenu.addSeparator()
  4314. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  4315. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  4316. grid_add.triggered.connect(self.on_grid_add)
  4317. grid_delete.triggered.connect(self.on_grid_delete)
  4318. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4319. def set_grid(self):
  4320. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4321. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4322. def on_grid_add(self):
  4323. ## Current application units in lower Case
  4324. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4325. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4326. text=_('Enter a Grid Value:'),
  4327. min=0.0000, max=99.9999, decimals=4)
  4328. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4329. val, ok = grid_add_popup.get_value()
  4330. if ok:
  4331. if float(val) == 0:
  4332. self.inform.emit(
  4333. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4334. return
  4335. else:
  4336. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4337. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4338. self.inform.emit(
  4339. _("[success] New Grid added ..."))
  4340. else:
  4341. self.inform.emit(
  4342. _("[WARNING_NOTCL] Grid already exists ..."))
  4343. else:
  4344. self.inform.emit(
  4345. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4346. def on_grid_delete(self):
  4347. ## Current application units in lower Case
  4348. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4349. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4350. text='Enter a Grid Value:',
  4351. min=0.0000, max=99.9999, decimals=4)
  4352. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4353. val, ok = grid_del_popup.get_value()
  4354. if ok:
  4355. if float(val) == 0:
  4356. self.inform.emit(
  4357. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4358. return
  4359. else:
  4360. try:
  4361. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4362. except ValueError:
  4363. self.inform.emit(
  4364. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4365. return
  4366. self.inform.emit(
  4367. _("[success] Grid Value deleted ..."))
  4368. else:
  4369. self.inform.emit(
  4370. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4371. def on_shortcut_list(self):
  4372. self.report_usage("on_shortcut_list()")
  4373. # add the tab if it was closed
  4374. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  4375. # delete the absolute and relative position and messages in the infobar
  4376. self.ui.position_label.setText("")
  4377. self.ui.rel_position_label.setText("")
  4378. # Switch plot_area to preferences page
  4379. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4380. self.ui.show()
  4381. def on_select_tab(self, name):
  4382. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4383. if self.ui.splitter.sizes()[0] == 0:
  4384. self.ui.splitter.setSizes([1, 1])
  4385. else:
  4386. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4387. self.ui.splitter.setSizes([0, 1])
  4388. if name == 'project':
  4389. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4390. elif name == 'selected':
  4391. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4392. elif name == 'tool':
  4393. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4394. def on_copy_name(self):
  4395. self.report_usage("on_copy_name()")
  4396. obj = self.collection.get_active()
  4397. try:
  4398. name = obj.options["name"]
  4399. except AttributeError:
  4400. log.debug("on_copy_name() --> No object selected to copy it's name")
  4401. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4402. return
  4403. self.clipboard.setText(name)
  4404. self.inform.emit(_("Name copied on clipboard ..."))
  4405. def on_mouse_click_over_plot(self, event):
  4406. """
  4407. Default actions are:
  4408. :param event: Contains information about the event, like which button
  4409. was clicked, the pixel coordinates and the axes coordinates.
  4410. :return: None
  4411. """
  4412. self.pos = []
  4413. # So it can receive key presses
  4414. self.plotcanvas.vispy_canvas.native.setFocus()
  4415. # Set the mouse button for panning
  4416. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  4417. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4418. if self.grid_status() == True:
  4419. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4420. self.app_cursor.enabled = True
  4421. else:
  4422. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4423. self.app_cursor.enabled = False
  4424. try:
  4425. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4426. if event.button == 1:
  4427. # Reset here the relative coordinates so there is a new reference on the click position
  4428. if self.rel_point1 is None:
  4429. self.rel_point1 = self.pos
  4430. else:
  4431. self.rel_point2 = copy(self.rel_point1)
  4432. self.rel_point1 = self.pos
  4433. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4434. if modifiers == QtCore.Qt.ShiftModifier:
  4435. # do not auto open the Project Tab
  4436. self.click_noproject = True
  4437. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  4438. return
  4439. self.on_mouse_move_over_plot(event, origin_click=True)
  4440. except Exception as e:
  4441. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4442. def on_double_click_over_plot(self, event):
  4443. self.doubleclick = True
  4444. def on_mouse_move_over_plot(self, event, origin_click=None):
  4445. """
  4446. Callback for the mouse motion event over the plot.
  4447. :param event: Contains information about the event.
  4448. :param origin_click
  4449. :return: None
  4450. """
  4451. # So it can receive key presses
  4452. self.plotcanvas.vispy_canvas.native.setFocus()
  4453. self.pos_jump = event.pos
  4454. self.ui.popMenu.mouse_is_panning = False
  4455. if origin_click != True:
  4456. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4457. if event.button == 2 and event.is_dragging == 1:
  4458. self.ui.popMenu.mouse_is_panning = True
  4459. return
  4460. if self.rel_point1 is not None:
  4461. try: # May fail in case mouse not within axes
  4462. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4463. if self.grid_status():
  4464. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4465. self.app_cursor.enabled = True
  4466. # Update cursor
  4467. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  4468. else:
  4469. pos = (pos_canvas[0], pos_canvas[1])
  4470. self.app_cursor.enabled = False
  4471. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4472. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  4473. dx = pos[0] - self.rel_point1[0]
  4474. dy = pos[1] - self.rel_point1[1]
  4475. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4476. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4477. self.mouse = [pos[0], pos[1]]
  4478. # if the mouse is moved and the LMB is clicked then the action is a selection
  4479. if event.is_dragging == 1 and event.button == 1:
  4480. self.delete_selection_shape()
  4481. if dx < 0:
  4482. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4483. face_color=self.defaults['global_alt_sel_fill'])
  4484. self.selection_type = False
  4485. else:
  4486. self.draw_moving_selection_shape(self.pos, pos)
  4487. self.selection_type = True
  4488. # hover effect - enabled in Preferences -> General -> GUI Settings
  4489. if self.defaults['global_hover']:
  4490. for obj in self.collection.get_list():
  4491. try:
  4492. # select the object(s) only if it is enabled (plotted)
  4493. if obj.options['plot']:
  4494. if obj not in self.collection.get_selected():
  4495. poly_obj = Polygon(
  4496. [(obj.options['xmin'], obj.options['ymin']),
  4497. (obj.options['xmax'], obj.options['ymin']),
  4498. (obj.options['xmax'], obj.options['ymax']),
  4499. (obj.options['xmin'], obj.options['ymax'])]
  4500. )
  4501. if Point(pos).within(poly_obj):
  4502. if obj.isHovering is False:
  4503. obj.isHovering = True
  4504. obj.notHovering = True
  4505. # create the selection box around the selected object
  4506. self.draw_hover_shape(obj, color='#d1e0e0')
  4507. else:
  4508. if obj.notHovering is True:
  4509. obj.notHovering = False
  4510. obj.isHovering = False
  4511. self.delete_hover_shape()
  4512. except:
  4513. # the Exception here will happen if we try to select on screen and we have an
  4514. # newly (and empty) just created Geometry or Excellon object that do not have the
  4515. # xmin, xmax, ymin, ymax options.
  4516. # In this case poly_obj creation (see above) will fail
  4517. pass
  4518. except:
  4519. self.ui.position_label.setText("")
  4520. self.ui.rel_position_label.setText("")
  4521. self.mouse = None
  4522. def on_mouse_click_release_over_plot(self, event):
  4523. """
  4524. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4525. and has been registered in ''self.__init__()''.
  4526. :param event: contains information about the event.
  4527. :return:
  4528. """
  4529. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4530. if self.grid_status():
  4531. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4532. else:
  4533. pos = (pos_canvas[0], pos_canvas[1])
  4534. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4535. # canvas menu
  4536. try:
  4537. if event.button == 2: # right click
  4538. if self.ui.popMenu.mouse_is_panning is False:
  4539. self.cursor = QtGui.QCursor()
  4540. self.populate_cmenu_grids()
  4541. self.ui.popMenu.popup(self.cursor.pos())
  4542. except Exception as e:
  4543. log.warning("Error: %s" % str(e))
  4544. return
  4545. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4546. # selection and then select a type of selection ("enclosing" or "touching")
  4547. try:
  4548. if event.button == 1: # left click
  4549. if self.doubleclick is True:
  4550. self.doubleclick = False
  4551. if self.collection.get_selected():
  4552. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4553. if self.ui.splitter.sizes()[0] == 0:
  4554. self.ui.splitter.setSizes([1, 1])
  4555. # delete the selection shape(S) as it may be in the way
  4556. self.delete_selection_shape()
  4557. self.delete_hover_shape()
  4558. else:
  4559. if self.selection_type is not None:
  4560. self.selection_area_handler(self.pos, pos, self.selection_type)
  4561. self.selection_type = None
  4562. else:
  4563. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4564. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4565. # deselect, and if it's not selected then it will be selected
  4566. if modifiers == QtCore.Qt.ControlModifier:
  4567. # If there is no active command (self.command_active is None) then we check if we clicked
  4568. # on a object by checking the bounding limits against mouse click position
  4569. if self.command_active is None:
  4570. self.select_objects(key='CTRL')
  4571. self.delete_hover_shape()
  4572. else:
  4573. # If there is no active command (self.command_active is None) then we check if we clicked
  4574. # on a object by checking the bounding limits against mouse click position
  4575. if self.command_active is None:
  4576. self.select_objects()
  4577. self.delete_hover_shape()
  4578. except Exception as e:
  4579. log.warning("Error: %s" % str(e))
  4580. return
  4581. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4582. """
  4583. :param start_pos: mouse position when the selection LMB click was done
  4584. :param end_pos: mouse position when the left mouse button is released
  4585. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4586. :return:
  4587. """
  4588. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4589. self.delete_selection_shape()
  4590. for obj in self.collection.get_list():
  4591. try:
  4592. # select the object(s) only if it is enabled (plotted)
  4593. if obj.options['plot']:
  4594. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4595. (obj.options['xmax'], obj.options['ymin']),
  4596. (obj.options['xmax'], obj.options['ymax']),
  4597. (obj.options['xmin'], obj.options['ymax'])])
  4598. if sel_type is True:
  4599. if poly_obj.within(poly_selection):
  4600. # create the selection box around the selected object
  4601. if self.defaults['global_selection_shape'] is True:
  4602. self.draw_selection_shape(obj)
  4603. self.collection.set_active(obj.options['name'])
  4604. else:
  4605. if poly_selection.intersects(poly_obj):
  4606. # create the selection box around the selected object
  4607. if self.defaults['global_selection_shape'] is True:
  4608. self.draw_selection_shape(obj)
  4609. self.collection.set_active(obj.options['name'])
  4610. except Exception as e:
  4611. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4612. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4613. # In this case poly_obj creation (see above) will fail
  4614. log.debug("App.selection_area_handler() --> %s" % str(e))
  4615. def select_objects(self, key=None):
  4616. # list where we store the overlapped objects under our mouse left click position
  4617. objects_under_the_click_list = []
  4618. # Populate the list with the overlapped objects on the click position
  4619. curr_x, curr_y = self.pos
  4620. for obj in self.all_objects_list:
  4621. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4622. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4623. if obj.options['name'] not in objects_under_the_click_list:
  4624. if obj.options['plot']:
  4625. # add objects to the objects_under_the_click list only if the object is plotted
  4626. # (active and not disabled)
  4627. objects_under_the_click_list.append(obj.options['name'])
  4628. try:
  4629. # If there is no element in the overlapped objects list then make everyone inactive
  4630. # because we selected "nothing"
  4631. if not objects_under_the_click_list:
  4632. self.collection.set_all_inactive()
  4633. # delete the possible selection box around a possible selected object
  4634. self.delete_selection_shape()
  4635. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4636. # only when working on App
  4637. if self.call_source == 'app':
  4638. if self.click_noproject is False:
  4639. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4640. else:
  4641. # restore auto open the Project Tab
  4642. self.click_noproject = False
  4643. # delete any text in the status bar, implicitly the last object name that was selected
  4644. self.inform.emit("")
  4645. else:
  4646. self.call_source = 'app'
  4647. else:
  4648. # case when there is only an object under the click and we toggle it
  4649. if len(objects_under_the_click_list) == 1:
  4650. if self.collection.get_active() is None :
  4651. self.collection.set_active(objects_under_the_click_list[0])
  4652. # create the selection box around the selected object
  4653. curr_sel_obj = self.collection.get_active()
  4654. if self.defaults['global_selection_shape'] is True:
  4655. self.draw_selection_shape(curr_sel_obj)
  4656. # self.inform.emit('[selected] %s: %s selected' %
  4657. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4658. if curr_sel_obj.kind == 'gerber':
  4659. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4660. color='green', name=str(curr_sel_obj.options['name'])))
  4661. elif curr_sel_obj.kind == 'excellon':
  4662. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4663. color='brown', name=str(curr_sel_obj.options['name'])))
  4664. elif curr_sel_obj.kind == 'cncjob':
  4665. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4666. color='blue', name=str(curr_sel_obj.options['name'])))
  4667. elif curr_sel_obj.kind == 'geometry':
  4668. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4669. color='red', name=str(curr_sel_obj.options['name'])))
  4670. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4671. self.collection.set_all_inactive()
  4672. self.delete_selection_shape()
  4673. self.collection.set_active(objects_under_the_click_list[0])
  4674. # create the selection box around the selected object
  4675. curr_sel_obj = self.collection.get_active()
  4676. if self.defaults['global_selection_shape'] is True:
  4677. self.draw_selection_shape(curr_sel_obj)
  4678. # self.inform.emit('[selected] %s: %s selected' %
  4679. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4680. if curr_sel_obj.kind == 'gerber':
  4681. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4682. color='green', name=str(curr_sel_obj.options['name'])))
  4683. elif curr_sel_obj.kind == 'excellon':
  4684. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4685. color='brown', name=str(curr_sel_obj.options['name'])))
  4686. elif curr_sel_obj.kind == 'cncjob':
  4687. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4688. color='blue', name=str(curr_sel_obj.options['name'])))
  4689. elif curr_sel_obj.kind == 'geometry':
  4690. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4691. color='red', name=str(curr_sel_obj.options['name'])))
  4692. else:
  4693. self.collection.set_all_inactive()
  4694. self.delete_selection_shape()
  4695. if self.call_source == 'app':
  4696. # delete any text in the status bar, implicitly the last object name that was selected
  4697. self.inform.emit("")
  4698. else:
  4699. self.call_source = 'app'
  4700. else:
  4701. # If there is no selected object
  4702. # make active the first element of the overlapped objects list
  4703. if self.collection.get_active() is None:
  4704. self.collection.set_active(objects_under_the_click_list[0])
  4705. name_sel_obj = self.collection.get_active().options['name']
  4706. # In case that there is a selected object but it is not in the overlapped object list
  4707. # make that object inactive and activate the first element in the overlapped object list
  4708. if name_sel_obj not in objects_under_the_click_list:
  4709. self.collection.set_inactive(name_sel_obj)
  4710. name_sel_obj = objects_under_the_click_list[0]
  4711. self.collection.set_active(name_sel_obj)
  4712. else:
  4713. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4714. self.collection.set_all_inactive()
  4715. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4716. len(objects_under_the_click_list)])
  4717. curr_sel_obj = self.collection.get_active()
  4718. # delete the possible selection box around a possible selected object
  4719. self.delete_selection_shape()
  4720. # create the selection box around the selected object
  4721. if self.defaults['global_selection_shape'] is True:
  4722. self.draw_selection_shape(curr_sel_obj)
  4723. # self.inform.emit('[selected] %s: %s selected' %
  4724. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4725. if curr_sel_obj.kind == 'gerber':
  4726. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4727. color='green', name=str(curr_sel_obj.options['name'])))
  4728. elif curr_sel_obj.kind == 'excellon':
  4729. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4730. color='brown', name=str(curr_sel_obj.options['name'])))
  4731. elif curr_sel_obj.kind == 'cncjob':
  4732. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4733. color='blue', name=str(curr_sel_obj.options['name'])))
  4734. elif curr_sel_obj.kind == 'geometry':
  4735. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4736. color='red', name=str(curr_sel_obj.options['name'])))
  4737. # for obj in self.collection.get_list():
  4738. # obj.plot()
  4739. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4740. # TODO: on selected objects change the object colors and do not draw the selection box
  4741. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4742. except Exception as e:
  4743. log.error("[ERROR] Something went bad. %s" % str(e))
  4744. return
  4745. def delete_hover_shape(self):
  4746. self.hover_shapes.clear()
  4747. self.hover_shapes.redraw()
  4748. def draw_hover_shape(self, sel_obj, color=None):
  4749. """
  4750. :param sel_obj: the object for which the hover shape must be drawn
  4751. :return:
  4752. """
  4753. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4754. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4755. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4756. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4757. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4758. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4759. hover_rect = hover_rect.buffer(-0.1)
  4760. hover_rect = hover_rect.buffer(0.2)
  4761. else:
  4762. hover_rect = hover_rect.buffer(-0.00393)
  4763. hover_rect = hover_rect.buffer(0.00787)
  4764. if color:
  4765. face = Color(color)
  4766. face.alpha = 0.2
  4767. outline = Color(color, alpha=0.8)
  4768. else:
  4769. face = Color(self.defaults['global_sel_fill'])
  4770. face.alpha = 0.2
  4771. outline = self.defaults['global_sel_line']
  4772. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4773. def delete_selection_shape(self):
  4774. self.move_tool.sel_shapes.clear()
  4775. self.move_tool.sel_shapes.redraw()
  4776. def draw_selection_shape(self, sel_obj, color=None):
  4777. """
  4778. :param sel_obj: the object for which the selection shape must be drawn
  4779. :return:
  4780. """
  4781. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4782. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4783. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4784. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4785. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4786. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4787. sel_rect = sel_rect.buffer(-0.1)
  4788. sel_rect = sel_rect.buffer(0.2)
  4789. else:
  4790. sel_rect = sel_rect.buffer(-0.00393)
  4791. sel_rect = sel_rect.buffer(0.00787)
  4792. if color:
  4793. face = Color(color, alpha=0.2)
  4794. outline = Color(color, alpha=0.8)
  4795. else:
  4796. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4797. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4798. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4799. face_color=face, update=True, layer=0, tolerance=None))
  4800. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4801. """
  4802. :param old_coords: old coordinates
  4803. :param coords: new coordinates
  4804. :return:
  4805. """
  4806. if 'color' in kwargs:
  4807. color = kwargs['color']
  4808. else:
  4809. color = self.defaults['global_sel_line']
  4810. if 'face_color' in kwargs:
  4811. face_color = kwargs['face_color']
  4812. else:
  4813. face_color = self.defaults['global_sel_fill']
  4814. x0, y0 = old_coords
  4815. x1, y1 = coords
  4816. pt1 = (x0, y0)
  4817. pt2 = (x1, y0)
  4818. pt3 = (x1, y1)
  4819. pt4 = (x0, y1)
  4820. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4821. color_t = Color(face_color)
  4822. color_t.alpha = 0.3
  4823. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4824. layer=0, tolerance=None)
  4825. def on_file_new_click(self):
  4826. if self.collection.get_list() and self.should_we_save:
  4827. msgbox = QtWidgets.QMessageBox()
  4828. # msgbox.setText("<B>Save changes ...</B>")
  4829. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4830. "Creating a New project will delete them.\n"
  4831. "Do you want to Save the project?"))
  4832. msgbox.setWindowTitle(_("Save changes"))
  4833. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4834. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4835. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4836. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4837. msgbox.setDefaultButton(bt_yes)
  4838. msgbox.exec_()
  4839. response = msgbox.clickedButton()
  4840. if response == bt_yes:
  4841. self.on_file_saveprojectas()
  4842. elif response == bt_cancel:
  4843. return
  4844. elif response == bt_no:
  4845. self.on_file_new()
  4846. else:
  4847. self.on_file_new()
  4848. self.inform.emit(_("[success] New Project created..."))
  4849. def on_file_new(self):
  4850. """
  4851. Callback for menu item File->New. Returns the application to its
  4852. startup state. This method is thread-safe.
  4853. :return: None
  4854. """
  4855. self.report_usage("on_file_new")
  4856. # Remove everything from memory
  4857. App.log.debug("on_file_new()")
  4858. if self.call_source != 'app':
  4859. self.editor2object(cleanup=True)
  4860. ### EDITOR section
  4861. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  4862. self.exc_editor = FlatCAMExcEditor(self)
  4863. self.grb_editor = FlatCAMGrbEditor(self)
  4864. # Clear pool
  4865. self.clear_pool()
  4866. #delete shapes left drawn from mark shape_collections, if any
  4867. for obj in self.collection.get_list():
  4868. try:
  4869. obj.mark_shapes.enabled = False
  4870. obj.mark_shapes.clear(update=True)
  4871. except:
  4872. pass
  4873. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4874. self.init_tcl()
  4875. self.delete_selection_shape()
  4876. self.collection.delete_all()
  4877. self.setup_component_editor()
  4878. # Clear project filename
  4879. self.project_filename = None
  4880. # Load the application defaults
  4881. self.load_defaults(filename='current_defaults')
  4882. # Re-fresh project options
  4883. self.on_options_app2project()
  4884. # Init Tools
  4885. self.init_tools()
  4886. # Close any Tabs opened in the Plot Tab Area section
  4887. for index in range(self.ui.plot_tab_area.count()):
  4888. self.ui.plot_tab_area.closeTab(index)
  4889. # for whatever reason previous command does not close the last tab so I do it manually
  4890. self.ui.plot_tab_area.closeTab(0)
  4891. # # And then add again the Plot Area
  4892. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4893. self.ui.plot_tab_area.protectTab(0)
  4894. # take the focus of the Notebook on Project Tab.
  4895. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4896. def obj_properties(self):
  4897. self.report_usage("obj_properties()")
  4898. self.properties_tool.run(toggle=False)
  4899. def on_project_context_save(self):
  4900. obj = self.collection.get_active()
  4901. if type(obj) == FlatCAMGeometry:
  4902. self.on_file_exportdxf()
  4903. elif type(obj) == FlatCAMExcellon:
  4904. self.on_file_saveexcellon()
  4905. elif type(obj) == FlatCAMCNCjob:
  4906. obj.on_exportgcode_button_click()
  4907. elif type(obj) == FlatCAMGerber:
  4908. self.on_file_savegerber()
  4909. def obj_move(self):
  4910. self.report_usage("obj_move()")
  4911. self.move_tool.run(toggle=False)
  4912. def on_fileopengerber(self):
  4913. """
  4914. File menu callback for opening a Gerber.
  4915. :return: None
  4916. """
  4917. self.report_usage("on_fileopengerber")
  4918. App.log.debug("on_fileopengerber()")
  4919. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4920. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4921. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  4922. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4923. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4924. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4925. "Allegro Files (*.art);;" \
  4926. "Mentor Files (*.pho *.gdo);;" \
  4927. "All Files (*.*)"
  4928. try:
  4929. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4930. directory=self.get_last_folder(), filter=_filter_)
  4931. except TypeError:
  4932. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4933. filenames = [str(filename) for filename in filenames]
  4934. if len(filenames) == 0:
  4935. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4936. else:
  4937. for filename in filenames:
  4938. if filename != '':
  4939. self.worker_task.emit({'fcn': self.open_gerber,
  4940. 'params': [filename]})
  4941. def on_fileopenexcellon(self):
  4942. """
  4943. File menu callback for opening an Excellon file.
  4944. :return: None
  4945. """
  4946. self.report_usage("on_fileopenexcellon")
  4947. App.log.debug("on_fileopenexcellon()")
  4948. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  4949. "All Files (*.*)"
  4950. try:
  4951. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4952. directory=self.get_last_folder(), filter=_filter_)
  4953. except TypeError:
  4954. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4955. filenames = [str(filename) for filename in filenames]
  4956. if len(filenames) == 0:
  4957. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  4958. else:
  4959. for filename in filenames:
  4960. if filename != '':
  4961. self.worker_task.emit({'fcn': self.open_excellon,
  4962. 'params': [filename]})
  4963. def on_fileopengcode(self):
  4964. """
  4965. File menu call back for opening gcode.
  4966. :return: None
  4967. """
  4968. self.report_usage("on_fileopengcode")
  4969. App.log.debug("on_fileopengcode()")
  4970. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4971. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4972. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4973. "All Files (*.*)"
  4974. try:
  4975. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  4976. directory=self.get_last_folder(), filter=_filter_)
  4977. except TypeError:
  4978. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  4979. filenames = [str(filename) for filename in filenames]
  4980. if len(filenames) == 0:
  4981. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  4982. else:
  4983. for filename in filenames:
  4984. if filename != '':
  4985. self.worker_task.emit({'fcn': self.open_gcode,
  4986. 'params': [filename]})
  4987. def on_file_openproject(self):
  4988. """
  4989. File menu callback for opening a project.
  4990. :return: None
  4991. """
  4992. self.report_usage("on_file_openproject")
  4993. App.log.debug("on_file_openproject()")
  4994. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4995. try:
  4996. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  4997. directory=self.get_last_folder(), filter=_filter_)
  4998. except TypeError:
  4999. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  5000. # The Qt methods above will return a QString which can cause problems later.
  5001. # So far json.dump() will fail to serialize it.
  5002. # TODO: Improve the serialization methods and remove this fix.
  5003. filename = str(filename)
  5004. if filename == "":
  5005. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  5006. else:
  5007. # self.worker_task.emit({'fcn': self.open_project,
  5008. # 'params': [filename]})
  5009. # The above was failing because open_project() is not
  5010. # thread safe. The new_project()
  5011. self.open_project(filename)
  5012. def on_file_openconfig(self):
  5013. """
  5014. File menu callback for opening a config file.
  5015. :return: None
  5016. """
  5017. self.report_usage("on_file_openconfig")
  5018. App.log.debug("on_file_openconfig()")
  5019. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5020. try:
  5021. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5022. directory=self.data_path, filter=_filter_)
  5023. except TypeError:
  5024. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5025. filter = _filter_)
  5026. if filename == "":
  5027. self.inform.emit(_("[WARNING_NOTCL Open Config cancelled."))
  5028. else:
  5029. self.open_config_file(filename)
  5030. def on_file_exportsvg(self):
  5031. """
  5032. Callback for menu item File->Export SVG.
  5033. :return: None
  5034. """
  5035. self.report_usage("on_file_exportsvg")
  5036. App.log.debug("on_file_exportsvg()")
  5037. obj = self.collection.get_active()
  5038. if obj is None:
  5039. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5040. msg = _("Please Select a Geometry object to export")
  5041. msgbox = QtWidgets.QMessageBox()
  5042. msgbox.setInformativeText(msg)
  5043. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5044. msgbox.setDefaultButton(bt_ok)
  5045. msgbox.exec_()
  5046. return
  5047. # Check for more compatible types and add as required
  5048. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  5049. and not isinstance(obj, FlatCAMExcellon)):
  5050. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  5051. msgbox = QtWidgets.QMessageBox()
  5052. msgbox.setInformativeText(msg)
  5053. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5054. msgbox.setDefaultButton(bt_ok)
  5055. msgbox.exec_()
  5056. return
  5057. name = self.collection.get_active().options["name"]
  5058. filter = "SVG File (*.svg);;All Files (*.*)"
  5059. try:
  5060. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5061. caption=_("Export SVG"),
  5062. directory=self.get_last_save_folder() + '/' + str(name),
  5063. filter=filter)
  5064. except TypeError:
  5065. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  5066. filename = str(filename)
  5067. if filename == "":
  5068. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  5069. return
  5070. else:
  5071. self.export_svg(name, filename)
  5072. if self.defaults["global_open_style"] is False:
  5073. self.file_opened.emit("SVG", filename)
  5074. self.file_saved.emit("SVG", filename)
  5075. def on_file_exportpng(self):
  5076. self.report_usage("on_file_exportpng")
  5077. App.log.debug("on_file_exportpng()")
  5078. image = _screenshot()
  5079. data = np.asarray(image)
  5080. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5081. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  5082. return
  5083. filter_ = "PNG File (*.png);;All Files (*.*)"
  5084. try:
  5085. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5086. caption=_("Export PNG Image"),
  5087. directory=self.get_last_save_folder() + '/png_' + self.date,
  5088. filter=filter_)
  5089. except TypeError:
  5090. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  5091. filename = str(filename)
  5092. if filename == "":
  5093. self.inform.emit(_("Export PNG cancelled."))
  5094. return
  5095. else:
  5096. write_png(filename, data)
  5097. if self.defaults["global_open_style"] is False:
  5098. self.file_opened.emit("png", filename)
  5099. self.file_saved.emit("png", filename)
  5100. def on_file_savegerber(self):
  5101. """
  5102. Callback for menu item File->Export Gerber.
  5103. :return: None
  5104. """
  5105. self.report_usage("on_file_savegerber")
  5106. App.log.debug("on_file_savegerber()")
  5107. obj = self.collection.get_active()
  5108. if obj is None:
  5109. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  5110. return
  5111. # Check for more compatible types and add as required
  5112. if not isinstance(obj, FlatCAMGerber):
  5113. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5114. return
  5115. name = self.collection.get_active().options["name"]
  5116. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5117. try:
  5118. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5119. caption="Save Gerber source file",
  5120. directory=self.get_last_save_folder() + '/' + name,
  5121. filter=filter)
  5122. except TypeError:
  5123. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  5124. filename = str(filename)
  5125. if filename == "":
  5126. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  5127. return
  5128. else:
  5129. self.save_source_file(name, filename)
  5130. if self.defaults["global_open_style"] is False:
  5131. self.file_opened.emit("Gerber", filename)
  5132. self.file_saved.emit("Gerber", filename)
  5133. def on_file_saveexcellon(self):
  5134. """
  5135. Callback for menu item File->Export Gerber.
  5136. :return: None
  5137. """
  5138. self.report_usage("on_file_saveexcellon")
  5139. App.log.debug("on_file_saveexcellon()")
  5140. obj = self.collection.get_active()
  5141. if obj is None:
  5142. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  5143. return
  5144. # Check for more compatible types and add as required
  5145. if not isinstance(obj, FlatCAMExcellon):
  5146. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5147. return
  5148. name = self.collection.get_active().options["name"]
  5149. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5150. try:
  5151. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5152. caption=_("Save Excellon source file"),
  5153. directory=self.get_last_save_folder() + '/' + name,
  5154. filter=filter)
  5155. except TypeError:
  5156. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  5157. filename = str(filename)
  5158. if filename == "":
  5159. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  5160. return
  5161. else:
  5162. self.save_source_file(name, filename)
  5163. if self.defaults["global_open_style"] is False:
  5164. self.file_opened.emit("Excellon", filename)
  5165. self.file_saved.emit("Excellon", filename)
  5166. def on_file_exportexcellon(self):
  5167. """
  5168. Callback for menu item File->Export->Excellon.
  5169. :return: None
  5170. """
  5171. self.report_usage("on_file_exportexcellon")
  5172. App.log.debug("on_file_exportexcellon()")
  5173. obj = self.collection.get_active()
  5174. if obj is None:
  5175. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  5176. return
  5177. # Check for more compatible types and add as required
  5178. if not isinstance(obj, FlatCAMExcellon):
  5179. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5180. return
  5181. name = self.collection.get_active().options["name"]
  5182. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5183. try:
  5184. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5185. caption=_("Export Excellon"),
  5186. directory=self.get_last_save_folder() + '/' + name,
  5187. filter=filter)
  5188. except TypeError:
  5189. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  5190. filename = str(filename)
  5191. if filename == "":
  5192. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  5193. return
  5194. else:
  5195. self.export_excellon(name, filename)
  5196. if self.defaults["global_open_style"] is False:
  5197. self.file_opened.emit("Excellon", filename)
  5198. self.file_saved.emit("Excellon", filename)
  5199. def on_file_exportgerber(self):
  5200. """
  5201. Callback for menu item File->Export->Gerber.
  5202. :return: None
  5203. """
  5204. self.report_usage("on_file_exportgerber")
  5205. App.log.debug("on_file_exportgerber()")
  5206. obj = self.collection.get_active()
  5207. if obj is None:
  5208. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export."))
  5209. return
  5210. # Check for more compatible types and add as required
  5211. if not isinstance(obj, FlatCAMGerber):
  5212. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5213. return
  5214. name = self.collection.get_active().options["name"]
  5215. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  5216. try:
  5217. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5218. caption=_("Export Gerber"),
  5219. directory=self.get_last_save_folder() + '/' + name,
  5220. filter=_filter_)
  5221. except TypeError:
  5222. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  5223. filename = str(filename)
  5224. if filename == "":
  5225. self.inform.emit(_("[WARNING_NOTCL] Export Gerber cancelled."))
  5226. return
  5227. else:
  5228. self.export_gerber(name, filename)
  5229. if self.defaults["global_open_style"] is False:
  5230. self.file_opened.emit("Gerber", filename)
  5231. self.file_saved.emit("Gerber", filename)
  5232. def on_file_exportdxf(self):
  5233. """
  5234. Callback for menu item File->Export DXF.
  5235. :return: None
  5236. """
  5237. self.report_usage("on_file_exportdxf")
  5238. App.log.debug("on_file_exportdxf()")
  5239. obj = self.collection.get_active()
  5240. if obj is None:
  5241. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5242. msg = _("Please Select a Geometry object to export")
  5243. msgbox = QtWidgets.QMessageBox()
  5244. msgbox.setInformativeText(msg)
  5245. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5246. msgbox.setDefaultButton(bt_ok)
  5247. msgbox.exec_()
  5248. return
  5249. # Check for more compatible types and add as required
  5250. if not isinstance(obj, FlatCAMGeometry):
  5251. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  5252. msgbox = QtWidgets.QMessageBox()
  5253. msgbox.setInformativeText(msg)
  5254. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5255. msgbox.setDefaultButton(bt_ok)
  5256. msgbox.exec_()
  5257. return
  5258. name = self.collection.get_active().options["name"]
  5259. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5260. try:
  5261. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5262. caption=_("Export DXF"),
  5263. directory=self.get_last_save_folder() + '/' + name,
  5264. filter=_filter_)
  5265. except TypeError:
  5266. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  5267. filter=_filter_)
  5268. filename = str(filename)
  5269. if filename == "":
  5270. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  5271. return
  5272. else:
  5273. self.export_dxf(name, filename)
  5274. if self.defaults["global_open_style"] is False:
  5275. self.file_opened.emit("DXF", filename)
  5276. self.file_saved.emit("DXF", filename)
  5277. def on_file_importsvg(self, type_of_obj):
  5278. """
  5279. Callback for menu item File->Import SVG.
  5280. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5281. :type type_of_obj: str
  5282. :return: None
  5283. """
  5284. self.report_usage("on_file_importsvg")
  5285. App.log.debug("on_file_importsvg()")
  5286. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  5287. try:
  5288. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5289. directory=self.get_last_folder(), filter=_filter_)
  5290. except TypeError:
  5291. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5292. filter=_filter_)
  5293. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5294. type_of_obj = "geometry"
  5295. filenames = [str(filename) for filename in filenames]
  5296. if len(filenames) == 0:
  5297. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  5298. else:
  5299. for filename in filenames:
  5300. if filename != '':
  5301. self.worker_task.emit({'fcn': self.import_svg,
  5302. 'params': [filename, type_of_obj]})
  5303. def on_file_importdxf(self, type_of_obj):
  5304. """
  5305. Callback for menu item File->Import DXF.
  5306. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5307. :type type_of_obj: str
  5308. :return: None
  5309. """
  5310. self.report_usage("on_file_importdxf")
  5311. App.log.debug("on_file_importdxf()")
  5312. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5313. try:
  5314. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5315. directory=self.get_last_folder(),
  5316. filter=_filter_)
  5317. except TypeError:
  5318. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5319. filter=_filter_)
  5320. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5321. type_of_obj = "geometry"
  5322. filenames = [str(filename) for filename in filenames]
  5323. if len(filenames) == 0:
  5324. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  5325. else:
  5326. for filename in filenames:
  5327. if filename != '':
  5328. self.worker_task.emit({'fcn': self.import_dxf,
  5329. 'params': [filename, type_of_obj]})
  5330. # ##################################################################################################################
  5331. # ## The following section has the functions that are displayed and call the Editor tab CNCJob Tab #################
  5332. # ##################################################################################################################
  5333. def init_code_editor(self, name):
  5334. # Signals section
  5335. # Disconnect the old signals
  5336. self.ui.buttonOpen.clicked.disconnect()
  5337. self.ui.buttonSave.clicked.disconnect()
  5338. # add the tab if it was closed
  5339. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5340. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5341. # delete the absolute and relative position and messages in the infobar
  5342. self.ui.position_label.setText("")
  5343. self.ui.rel_position_label.setText("")
  5344. # first clear previous text in text editor (if any)
  5345. self.ui.code_editor.clear()
  5346. self.ui.code_editor.setReadOnly(False)
  5347. self.toggle_codeeditor = True
  5348. self.ui.code_editor.completer_enable = False
  5349. # Switch plot_area to CNCJob tab
  5350. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5351. def on_view_source(self):
  5352. try:
  5353. obj = self.collection.get_active()
  5354. except:
  5355. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5356. return 'fail'
  5357. # then append the text from GCode to the text editor
  5358. try:
  5359. file = StringIO(obj.source_file)
  5360. except AttributeError:
  5361. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5362. return 'fail'
  5363. if obj.kind == 'gerber':
  5364. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5365. elif obj.kind == 'excellon':
  5366. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5367. self.init_code_editor(name=_("Source Editor"))
  5368. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5369. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5370. try:
  5371. for line in file:
  5372. proc_line = str(line).strip('\n')
  5373. self.ui.code_editor.append(proc_line)
  5374. except Exception as e:
  5375. log.debug('App.on_view_source() -->%s' % str(e))
  5376. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5377. return
  5378. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5379. self.handleTextChanged()
  5380. self.ui.show()
  5381. def on_toggle_code_editor(self):
  5382. self.report_usage("on_toggle_code_editor()")
  5383. if self.toggle_codeeditor is False:
  5384. self.init_code_editor(name=_("Code Editor"))
  5385. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  5386. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  5387. else:
  5388. for idx in range(self.ui.plot_tab_area.count()):
  5389. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  5390. self.ui.plot_tab_area.closeTab(idx)
  5391. break
  5392. self.toggle_codeeditor = False
  5393. def on_filenewscript(self):
  5394. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5395. self.init_code_editor(name=_("Script Editor"))
  5396. self.ui.code_editor.completer_enable = True
  5397. self.ui.code_editor.append(_(
  5398. "#\n"
  5399. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  5400. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  5401. "#\n\n"
  5402. "# FlatCAM commands list:\n"
  5403. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  5404. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  5405. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  5406. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  5407. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  5408. "# WriteGCode\n"
  5409. "#\n\n"
  5410. ))
  5411. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5412. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5413. self.handleTextChanged()
  5414. self.ui.code_editor.show()
  5415. def on_fileopenscript(self):
  5416. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5417. try:
  5418. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  5419. directory=self.get_last_folder(), filter=_filter_)
  5420. except TypeError:
  5421. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  5422. # The Qt methods above will return a QString which can cause problems later.
  5423. # So far json.dump() will fail to serialize it.
  5424. # TODO: Improve the serialization methods and remove this fix.
  5425. filename = str(filename)
  5426. if filename == "":
  5427. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  5428. else:
  5429. self.on_filenewscript()
  5430. try:
  5431. with open(filename, "r") as opened_script:
  5432. try:
  5433. for line in opened_script:
  5434. proc_line = str(line).strip('\n')
  5435. self.ui.code_editor.append(proc_line)
  5436. except Exception as e:
  5437. log.debug('App.on_fileopenscript() -->%s' % str(e))
  5438. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  5439. return
  5440. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5441. self.handleTextChanged()
  5442. self.ui.show()
  5443. except Exception as e:
  5444. log.debug("App.on_fileopenscript() -> %s" % str(e))
  5445. def on_filerunscript(self, name=None):
  5446. """
  5447. File menu callback for loading and running a TCL script.
  5448. :return: None
  5449. """
  5450. self.report_usage("on_filerunscript")
  5451. App.log.debug("on_file_runscript()")
  5452. if name:
  5453. filename = name
  5454. else:
  5455. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5456. try:
  5457. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  5458. directory=self.get_last_folder(), filter=_filter_)
  5459. except TypeError:
  5460. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  5461. # The Qt methods above will return a QString which can cause problems later.
  5462. # So far json.dump() will fail to serialize it.
  5463. # TODO: Improve the serialization methods and remove this fix.
  5464. filename = str(filename)
  5465. if filename == "":
  5466. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  5467. else:
  5468. try:
  5469. with open(filename, "r") as tcl_script:
  5470. cmd_line_shellfile_content = tcl_script.read()
  5471. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  5472. except Exception as e:
  5473. log.debug("App.on_filerunscript() -> %s" % str(e))
  5474. sys.exit(2)
  5475. def on_file_saveproject(self):
  5476. """
  5477. Callback for menu item File->Save Project. Saves the project to
  5478. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  5479. if set to None. The project is saved by calling ``self.save_project()``.
  5480. :return: None
  5481. """
  5482. self.report_usage("on_file_saveproject")
  5483. if self.project_filename is None:
  5484. self.on_file_saveprojectas()
  5485. else:
  5486. self.worker_task.emit({'fcn': self.save_project,
  5487. 'params': [self.project_filename]})
  5488. if self.defaults["global_open_style"] is False:
  5489. self.file_opened.emit("project", self.project_filename)
  5490. self.file_saved.emit("project", self.project_filename)
  5491. self.should_we_save = False
  5492. def on_file_saveprojectas(self, make_copy=False, thread=True, quit=False):
  5493. """
  5494. Callback for menu item File->Save Project As... Opens a file
  5495. chooser and saves the project to the given file via
  5496. ``self.save_project()``.
  5497. :return: None
  5498. """
  5499. self.report_usage("on_file_saveprojectas")
  5500. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  5501. try:
  5502. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5503. caption=_("Save Project As ..."),
  5504. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  5505. filter=filter_)
  5506. except TypeError:
  5507. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  5508. filename = str(filename)
  5509. if filename == '':
  5510. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  5511. return
  5512. try:
  5513. f = open(filename, 'r')
  5514. f.close()
  5515. except IOError:
  5516. pass
  5517. if thread is True:
  5518. self.worker_task.emit({'fcn': self.save_project,
  5519. 'params': [filename, quit]})
  5520. else:
  5521. self.save_project(filename, quit)
  5522. # self.save_project(filename)
  5523. if self.defaults["global_open_style"] is False:
  5524. self.file_opened.emit("project", filename)
  5525. self.file_saved.emit("project", filename)
  5526. if not make_copy:
  5527. self.project_filename = filename
  5528. self.should_we_save = False
  5529. def export_svg(self, obj_name, filename, scale_factor=0.00):
  5530. """
  5531. Exports a Geometry Object to an SVG file.
  5532. :param filename: Path to the SVG file to save to.
  5533. :return:
  5534. """
  5535. self.report_usage("export_svg()")
  5536. if filename is None:
  5537. filename = self.defaults["global_last_save_folder"]
  5538. self.log.debug("export_svg()")
  5539. try:
  5540. obj = self.collection.get_by_name(str(obj_name))
  5541. except:
  5542. # TODO: The return behavior has not been established... should raise exception?
  5543. return "Could not retrieve object: %s" % obj_name
  5544. with self.proc_container.new(_("Exporting SVG")) as proc:
  5545. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5546. # Determine bounding area for svg export
  5547. bounds = obj.bounds()
  5548. size = obj.size()
  5549. # Convert everything to strings for use in the xml doc
  5550. svgwidth = str(size[0])
  5551. svgheight = str(size[1])
  5552. minx = str(bounds[0])
  5553. miny = str(bounds[1] - size[1])
  5554. uom = obj.units.lower()
  5555. # Add a SVG Header and footer to the svg output from shapely
  5556. # The transform flips the Y Axis so that everything renders
  5557. # properly within svg apps such as inkscape
  5558. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5559. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5560. svg_header += 'width="' + svgwidth + uom + '" '
  5561. svg_header += 'height="' + svgheight + uom + '" '
  5562. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  5563. svg_header += '<g transform="scale(1,-1)">'
  5564. svg_footer = '</g> </svg>'
  5565. svg_elem = svg_header + exported_svg + svg_footer
  5566. # Parse the xml through a xml parser just to add line feeds
  5567. # and to make it look more pretty for the output
  5568. svgcode = parse_xml_string(svg_elem)
  5569. with open(filename, 'w') as fp:
  5570. fp.write(svgcode.toprettyxml())
  5571. if self.defaults["global_open_style"] is False:
  5572. self.file_opened.emit("SVG", filename)
  5573. self.file_saved.emit("SVG", filename)
  5574. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5575. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  5576. """
  5577. Exports a Geometry Object to an SVG file in negative.
  5578. :param filename: Path to the SVG file to save to.
  5579. :param: use_thread: If True use threads
  5580. :type: Bool
  5581. :return:
  5582. """
  5583. self.report_usage("export_negative()")
  5584. if filename is None:
  5585. filename = self.defaults["global_last_save_folder"]
  5586. self.log.debug("export_svg() negative")
  5587. try:
  5588. obj = self.collection.get_by_name(str(obj_name))
  5589. except:
  5590. # TODO: The return behavior has not been established... should raise exception?
  5591. return "Could not retrieve object: %s" % obj_name
  5592. try:
  5593. box = self.collection.get_by_name(str(box_name))
  5594. except:
  5595. # TODO: The return behavior has not been established... should raise exception?
  5596. return "Could not retrieve object: %s" % box_name
  5597. if box is None:
  5598. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5599. box = obj
  5600. def make_negative_film():
  5601. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5602. self.progress.emit(40)
  5603. # Determine bounding area for svg export
  5604. bounds = box.bounds()
  5605. size = box.size()
  5606. uom = obj.units.lower()
  5607. # Convert everything to strings for use in the xml doc
  5608. svgwidth = str(size[0] + (2 * boundary))
  5609. svgheight = str(size[1] + (2 * boundary))
  5610. minx = str(bounds[0] - boundary)
  5611. miny = str(bounds[1] + boundary + size[1])
  5612. miny_rect = str(bounds[1] - boundary)
  5613. # Add a SVG Header and footer to the svg output from shapely
  5614. # The transform flips the Y Axis so that everything renders
  5615. # properly within svg apps such as inkscape
  5616. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5617. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5618. svg_header += 'width="' + svgwidth + uom + '" '
  5619. svg_header += 'height="' + svgheight + uom + '" '
  5620. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5621. svg_header += '>'
  5622. svg_header += '<g transform="scale(1,-1)">'
  5623. svg_footer = '</g> </svg>'
  5624. self.progress.emit(60)
  5625. # Change the attributes of the exported SVG
  5626. # We don't need stroke-width - wrong, we do when we have lines with certain width
  5627. # We set opacity to maximum
  5628. # We set the color to WHITE
  5629. root = ET.fromstring(exported_svg)
  5630. for child in root:
  5631. child.set('fill', '#FFFFFF')
  5632. child.set('opacity', '1.0')
  5633. child.set('stroke', '#FFFFFF')
  5634. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  5635. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  5636. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  5637. first_svg_elem_tag = 'rect'
  5638. first_svg_elem_attribs = {
  5639. 'x': minx,
  5640. 'y': miny_rect,
  5641. 'width': svgwidth,
  5642. 'height': svgheight,
  5643. 'id': 'neg_rect',
  5644. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  5645. }
  5646. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  5647. exported_svg = ET.tostring(root)
  5648. svg_elem = svg_header + str(exported_svg) + svg_footer
  5649. self.progress.emit(80)
  5650. # Parse the xml through a xml parser just to add line feeds
  5651. # and to make it look more pretty for the output
  5652. doc = parse_xml_string(svg_elem)
  5653. with open(filename, 'w') as fp:
  5654. fp.write(doc.toprettyxml())
  5655. self.progress.emit(100)
  5656. if self.defaults["global_open_style"] is False:
  5657. self.file_opened.emit("SVG", filename)
  5658. self.file_saved.emit("SVG", filename)
  5659. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5660. if use_thread is True:
  5661. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5662. def job_thread_film(app_obj):
  5663. try:
  5664. make_negative_film()
  5665. except Exception as e:
  5666. proc.done()
  5667. return
  5668. proc.done()
  5669. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5670. else:
  5671. make_negative_film()
  5672. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  5673. """
  5674. Exports a Geometry Object to an SVG file in negative.
  5675. :param filename: Path to the SVG file to save to.
  5676. :param: use_thread: If True use threads
  5677. :type: Bool
  5678. :return:
  5679. """
  5680. self.report_usage("export_svg_black()")
  5681. if filename is None:
  5682. filename = self.defaults["global_last_save_folder"]
  5683. self.log.debug("export_svg() black")
  5684. try:
  5685. obj = self.collection.get_by_name(str(obj_name))
  5686. except:
  5687. # TODO: The return behavior has not been established... should raise exception?
  5688. return "Could not retrieve object: %s" % obj_name
  5689. try:
  5690. box = self.collection.get_by_name(str(box_name))
  5691. except:
  5692. # TODO: The return behavior has not been established... should raise exception?
  5693. return "Could not retrieve object: %s" % box_name
  5694. if box is None:
  5695. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5696. box = obj
  5697. def make_black_film():
  5698. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5699. self.progress.emit(40)
  5700. # Change the attributes of the exported SVG
  5701. # We don't need stroke-width
  5702. # We set opacity to maximum
  5703. # We set the colour to WHITE
  5704. root = ET.fromstring(exported_svg)
  5705. for child in root:
  5706. child.set('fill', '#000000')
  5707. child.set('opacity', '1.0')
  5708. child.set('stroke', '#000000')
  5709. exported_svg = ET.tostring(root)
  5710. # Determine bounding area for svg export
  5711. bounds = box.bounds()
  5712. size = box.size()
  5713. # This contain the measure units
  5714. uom = obj.units.lower()
  5715. # Define a boundary around SVG of about 1.0mm (~39mils)
  5716. if uom in "mm":
  5717. boundary = 1.0
  5718. else:
  5719. boundary = 0.0393701
  5720. self.progress.emit(80)
  5721. # Convert everything to strings for use in the xml doc
  5722. svgwidth = str(size[0] + (2 * boundary))
  5723. svgheight = str(size[1] + (2 * boundary))
  5724. minx = str(bounds[0] - boundary)
  5725. miny = str(bounds[1] + boundary + size[1])
  5726. self.log.debug(minx)
  5727. self.log.debug(miny)
  5728. # Add a SVG Header and footer to the svg output from shapely
  5729. # The transform flips the Y Axis so that everything renders
  5730. # properly within svg apps such as inkscape
  5731. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5732. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5733. svg_header += 'width="' + svgwidth + uom + '" '
  5734. svg_header += 'height="' + svgheight + uom + '" '
  5735. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5736. svg_header += '>'
  5737. svg_header += '<g transform="scale(1,-1)">'
  5738. svg_footer = '</g> </svg>'
  5739. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5740. self.progress.emit(90)
  5741. # Parse the xml through a xml parser just to add line feeds
  5742. # and to make it look more pretty for the output
  5743. doc = parse_xml_string(svg_elem)
  5744. with open(filename, 'w') as fp:
  5745. fp.write(doc.toprettyxml())
  5746. self.progress.emit(100)
  5747. if self.defaults["global_open_style"] is False:
  5748. self.file_opened.emit("SVG", filename)
  5749. self.file_saved.emit("SVG", filename)
  5750. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5751. if use_thread is True:
  5752. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5753. def job_thread_film(app_obj):
  5754. try:
  5755. make_black_film()
  5756. except Exception as e:
  5757. proc.done()
  5758. return
  5759. proc.done()
  5760. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5761. else:
  5762. make_black_film()
  5763. def save_source_file(self, obj_name, filename, use_thread=True):
  5764. """
  5765. Exports a Gerber Object to an Gerber file.
  5766. :param filename: Path to the Gerber file to save to.
  5767. :return:
  5768. """
  5769. self.report_usage("save source file()")
  5770. if filename is None:
  5771. filename = self.defaults["global_last_save_folder"]
  5772. self.log.debug("save source file()")
  5773. obj = self.collection.get_by_name(obj_name)
  5774. file_string = StringIO(obj.source_file)
  5775. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5776. with open(filename, 'w') as file:
  5777. file.writelines('G04*\n')
  5778. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5779. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5780. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5781. file.writelines('G04 Created on : %s*\n' % time_string)
  5782. for line in file_string:
  5783. file.writelines(line)
  5784. def export_excellon(self, obj_name, filename, use_thread=True):
  5785. """
  5786. Exports a Excellon Object to an Excellon file.
  5787. :param filename: Path to the Excellon file to save to.
  5788. :return:
  5789. """
  5790. self.report_usage("export_excellon()")
  5791. if filename is None:
  5792. filename = self.defaults["global_last_save_folder"]
  5793. self.log.debug("export_excellon()")
  5794. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5795. self.defaults["excellon_exp_decimals"]
  5796. )
  5797. units = ''
  5798. try:
  5799. obj = self.collection.get_by_name(str(obj_name))
  5800. except:
  5801. # TODO: The return behavior has not been established... should raise exception?
  5802. return "Could not retrieve object: %s" % obj_name
  5803. # updated units
  5804. eunits = self.defaults["excellon_exp_units"]
  5805. ewhole = self.defaults["excellon_exp_integer"]
  5806. efract = self.defaults["excellon_exp_decimals"]
  5807. ezeros = self.defaults["excellon_exp_zeros"]
  5808. eformat = self.defaults[ "excellon_exp_format"]
  5809. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5810. if fc_units == 'MM':
  5811. factor = 1 if eunits == 'METRIC' else 0.03937
  5812. else:
  5813. factor = 25.4 if eunits == 'METRIC' else 1
  5814. def make_excellon():
  5815. try:
  5816. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5817. header = 'M48\n'
  5818. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5819. (str(self.version), str(self.version_date))
  5820. header += ';Filename: %s' % str(obj_name) + '\n'
  5821. header += ';Created on : %s' % time_str + '\n'
  5822. if eformat == 'dec':
  5823. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5824. header += eunits + '\n'
  5825. for tool in obj.tools:
  5826. if eunits == 'METRIC':
  5827. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5828. tool=str(tool),
  5829. dec=2)
  5830. else:
  5831. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5832. tool=str(tool),
  5833. dec=4)
  5834. else:
  5835. if ezeros == 'LZ':
  5836. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5837. form='ndec', e_zeros='LZ', factor=factor)
  5838. header += '%s,%s\n' % (eunits, 'LZ')
  5839. header += format_exc
  5840. for tool in obj.tools:
  5841. if eunits == 'METRIC':
  5842. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5843. tool=str(tool),
  5844. dec=2)
  5845. else:
  5846. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5847. tool=str(tool),
  5848. dec=4)
  5849. else:
  5850. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5851. form='ndec', e_zeros='TZ', factor=factor)
  5852. header += '%s,%s\n' % (eunits, 'TZ')
  5853. header += format_exc
  5854. for tool in obj.tools:
  5855. if eunits == 'METRIC':
  5856. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5857. tool=str(tool),
  5858. dec=2)
  5859. else:
  5860. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5861. tool=str(tool),
  5862. dec=4)
  5863. header += '%\n'
  5864. footer = 'M30\n'
  5865. exported_excellon = header
  5866. exported_excellon += excellon_code
  5867. exported_excellon += footer
  5868. with open(filename, 'w') as fp:
  5869. fp.write(exported_excellon)
  5870. if self.defaults["global_open_style"] is False:
  5871. self.file_opened.emit("Excellon", filename)
  5872. self.file_saved.emit("Excellon", filename)
  5873. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5874. except Exception as e:
  5875. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5876. return 'fail'
  5877. if use_thread is True:
  5878. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5879. def job_thread_exc(app_obj):
  5880. ret = make_excellon()
  5881. if ret == 'fail':
  5882. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5883. return
  5884. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5885. else:
  5886. ret = make_excellon()
  5887. if ret == 'fail':
  5888. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5889. return
  5890. def export_gerber(self, obj_name, filename, use_thread=True):
  5891. """
  5892. Exports a Gerber Object to an Gerber file.
  5893. :param filename: Path to the Gerber file to save to.
  5894. :return:
  5895. """
  5896. self.report_usage("export_gerber()")
  5897. if filename is None:
  5898. filename = self.defaults["global_last_save_folder"]
  5899. self.log.debug("export_gerber()")
  5900. try:
  5901. obj = self.collection.get_by_name(str(obj_name))
  5902. except:
  5903. # TODO: The return behavior has not been established... should raise exception?
  5904. return "Could not retrieve object: %s" % obj_name
  5905. # updated units
  5906. gunits = self.defaults["gerber_exp_units"]
  5907. gwhole = self.defaults["gerber_exp_integer"]
  5908. gfract = self.defaults["gerber_exp_decimals"]
  5909. gzeros = self.defaults["gerber_exp_zeros"]
  5910. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5911. if fc_units == 'MM':
  5912. factor = 1 if gunits == 'MM' else 0.03937
  5913. else:
  5914. factor = 25.4 if gunits == 'MM' else 1
  5915. def make_gerber():
  5916. try:
  5917. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5918. header = 'G04*\n'
  5919. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  5920. (str(self.version), str(self.version_date))
  5921. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  5922. header += 'G04 Created on : %s*' % time_str + '\n'
  5923. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  5924. header += "%MO{units}*%\n".format(units=gunits)
  5925. for apid in obj.apertures:
  5926. if obj.apertures[apid]['type'] == 'C':
  5927. header += "%ADD{apid}{type},{size}*%\n".format(
  5928. apid=str(apid),
  5929. type='C',
  5930. size=(factor * obj.apertures[apid]['size'])
  5931. )
  5932. elif obj.apertures[apid]['type'] == 'R':
  5933. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  5934. apid=str(apid),
  5935. type='R',
  5936. width=(factor * obj.apertures[apid]['width']),
  5937. height=(factor * obj.apertures[apid]['height'])
  5938. )
  5939. elif obj.apertures[apid]['type'] == 'O':
  5940. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  5941. apid=str(apid),
  5942. type='O',
  5943. width=(factor * obj.apertures[apid]['width']),
  5944. height=(factor * obj.apertures[apid]['height'])
  5945. )
  5946. header += '\n'
  5947. # obsolete units but some software may need it
  5948. if gunits == 'IN':
  5949. header += 'G70*\n'
  5950. else:
  5951. header += 'G71*\n'
  5952. # Absolute Mode
  5953. header += 'G90*\n'
  5954. header += 'G01*\n'
  5955. # positive polarity
  5956. header += '%LPD*%\n'
  5957. footer = 'M02*\n'
  5958. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  5959. exported_gerber = header
  5960. exported_gerber += gerber_code
  5961. exported_gerber += footer
  5962. with open(filename, 'w') as fp:
  5963. fp.write(exported_gerber)
  5964. if self.defaults["global_open_style"] is False:
  5965. self.file_opened.emit("Gerber", filename)
  5966. self.file_saved.emit("Gerber", filename)
  5967. self.inform.emit(_("[success] Gerber file exported to %s") % filename)
  5968. except Exception as e:
  5969. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  5970. return 'fail'
  5971. if use_thread is True:
  5972. with self.proc_container.new(_("Exporting Gerber")) as proc:
  5973. def job_thread_exc(app_obj):
  5974. ret = make_gerber()
  5975. if ret == 'fail':
  5976. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  5977. return
  5978. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5979. else:
  5980. ret = make_gerber()
  5981. if ret == 'fail':
  5982. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  5983. return
  5984. def export_dxf(self, obj_name, filename, use_thread=True):
  5985. """
  5986. Exports a Geometry Object to an DXF file.
  5987. :param filename: Path to the DXF file to save to.
  5988. :return:
  5989. """
  5990. self.report_usage("export_dxf()")
  5991. if filename is None:
  5992. filename = self.defaults["global_last_save_folder"]
  5993. self.log.debug("export_dxf()")
  5994. format_exc = ''
  5995. units = ''
  5996. try:
  5997. obj = self.collection.get_by_name(str(obj_name))
  5998. except:
  5999. # TODO: The return behavior has not been established... should raise exception?
  6000. return "Could not retrieve object: %s" % obj_name
  6001. # updated units
  6002. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6003. if units == 'IN' or units == 'INCH':
  6004. units = 'INCH'
  6005. elif units == 'MM' or units == 'METIRC':
  6006. units ='METRIC'
  6007. def make_dxf():
  6008. try:
  6009. dxf_code = obj.export_dxf()
  6010. dxf_code.saveas(filename)
  6011. if self.defaults["global_open_style"] is False:
  6012. self.file_opened.emit("DXF", filename)
  6013. self.file_saved.emit("DXF", filename)
  6014. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  6015. except:
  6016. return 'fail'
  6017. if use_thread is True:
  6018. with self.proc_container.new(_("Exporting DXF")) as proc:
  6019. def job_thread_exc(app_obj):
  6020. ret = make_dxf()
  6021. if ret == 'fail':
  6022. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6023. return
  6024. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6025. else:
  6026. ret = make_dxf()
  6027. if ret == 'fail':
  6028. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6029. return
  6030. def import_svg(self, filename, geo_type='geometry', outname=None):
  6031. """
  6032. Adds a new Geometry Object to the projects and populates
  6033. it with shapes extracted from the SVG file.
  6034. :param filename: Path to the SVG file.
  6035. :param outname:
  6036. :return:
  6037. """
  6038. self.report_usage("import_svg()")
  6039. obj_type = ""
  6040. if geo_type is None or geo_type == "geometry":
  6041. obj_type = "geometry"
  6042. elif geo_type == "gerber":
  6043. obj_type = geo_type
  6044. else:
  6045. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6046. "Only Geometry and Gerber are supported"))
  6047. return
  6048. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6049. def obj_init(geo_obj, app_obj):
  6050. geo_obj.import_svg(filename, obj_type, units=units)
  6051. geo_obj.multigeo = False
  6052. with self.proc_container.new(_("Importing SVG")) as proc:
  6053. # Object name
  6054. name = outname or filename.split('/')[-1].split('\\')[-1]
  6055. self.new_object(obj_type, name, obj_init, autoselected=False)
  6056. self.progress.emit(20)
  6057. # Register recent file
  6058. self.file_opened.emit("svg", filename)
  6059. # GUI feedback
  6060. self.inform.emit(_("[success] Opened: %s") % filename)
  6061. self.progress.emit(100)
  6062. def import_dxf(self, filename, geo_type='geometry', outname=None):
  6063. """
  6064. Adds a new Geometry Object to the projects and populates
  6065. it with shapes extracted from the DXF file.
  6066. :param filename: Path to the DXF file.
  6067. :param outname:
  6068. :type putname: str
  6069. :return:
  6070. """
  6071. self.report_usage("import_dxf()")
  6072. obj_type = ""
  6073. if geo_type is None or geo_type == "geometry":
  6074. obj_type = "geometry"
  6075. elif geo_type == "gerber":
  6076. obj_type = geo_type
  6077. else:
  6078. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6079. "Only Geometry and Gerber are supported"))
  6080. return
  6081. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6082. def obj_init(geo_obj, app_obj):
  6083. geo_obj.import_dxf(filename, obj_type, units=units)
  6084. geo_obj.multigeo = False
  6085. with self.proc_container.new(_("Importing DXF")) as proc:
  6086. # Object name
  6087. name = outname or filename.split('/')[-1].split('\\')[-1]
  6088. self.new_object(obj_type, name, obj_init, autoselected=False)
  6089. self.progress.emit(20)
  6090. # Register recent file
  6091. self.file_opened.emit("dxf", filename)
  6092. # GUI feedback
  6093. self.inform.emit(_("[success] Opened: %s") % filename)
  6094. self.progress.emit(100)
  6095. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  6096. """
  6097. Adds a new Geometry Object to the projects and populates
  6098. it with shapes extracted from the SVG file.
  6099. :param filename: Path to the SVG file.
  6100. :param o_type: type of FlatCAM objeect
  6101. :param dpi: dot per inch
  6102. :param mode: black or color
  6103. :param mask: dictate the level of detail
  6104. :param outname: name for the resulting file
  6105. :return:
  6106. """
  6107. self.report_usage("import_image()")
  6108. if o_type is None or o_type == "geometry":
  6109. obj_type = "geometry"
  6110. elif o_type == "gerber":
  6111. obj_type = o_type
  6112. else:
  6113. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6114. "Only Geometry and Gerber are supported"))
  6115. return
  6116. def obj_init(geo_obj, app_obj):
  6117. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  6118. geo_obj.multigeo = False
  6119. with self.proc_container.new(_("Importing Image")) as proc:
  6120. # Object name
  6121. name = outname or filename.split('/')[-1].split('\\')[-1]
  6122. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  6123. self.new_object(obj_type, name, obj_init)
  6124. self.progress.emit(20)
  6125. # Register recent file
  6126. self.file_opened.emit("image", filename)
  6127. # GUI feedback
  6128. self.inform.emit(_("[success] Opened: %s") % filename)
  6129. self.progress.emit(100)
  6130. def open_gerber(self, filename, outname=None):
  6131. """
  6132. Opens a Gerber file, parses it and creates a new object for
  6133. it in the program. Thread-safe.
  6134. :param outname: Name of the resulting object. None causes the
  6135. name to be that of the file.
  6136. :param filename: Gerber file filename
  6137. :type filename: str
  6138. :param follow: If true, the parser will not create polygons, just lines
  6139. following the gerber path.
  6140. :type follow: bool
  6141. :return: None
  6142. """
  6143. # How the object should be initialized
  6144. def obj_init(gerber_obj, app_obj):
  6145. assert isinstance(gerber_obj, FlatCAMGerber), \
  6146. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  6147. # Opening the file happens here
  6148. self.progress.emit(30)
  6149. try:
  6150. gerber_obj.parse_file(filename)
  6151. except IOError:
  6152. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  6153. app_obj.progress.emit(0)
  6154. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  6155. return "fail"
  6156. except ParseError as err:
  6157. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename,
  6158. error=str(err)))
  6159. app_obj.progress.emit(0)
  6160. self.log.error(str(err))
  6161. return "fail"
  6162. except:
  6163. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  6164. msg += traceback.format_exc()
  6165. app_obj.inform.emit(msg)
  6166. return "fail"
  6167. if gerber_obj.is_empty():
  6168. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  6169. # self.collection.set_active(gerber_obj.options["name"])
  6170. # self.collection.delete_active()
  6171. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  6172. return "fail"
  6173. # Further parsing
  6174. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  6175. App.log.debug("open_gerber()")
  6176. with self.proc_container.new(_("Opening Gerber")) as proc:
  6177. self.progress.emit(10)
  6178. # Object name
  6179. name = outname or filename.split('/')[-1].split('\\')[-1]
  6180. # ## Object creation ###
  6181. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  6182. if ret == 'fail':
  6183. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  6184. return
  6185. # Register recent file
  6186. self.file_opened.emit("gerber", filename)
  6187. self.progress.emit(100)
  6188. # GUI feedback
  6189. self.inform.emit(_("[success] Opened: %s") % filename)
  6190. def open_excellon(self, filename, outname=None):
  6191. """
  6192. Opens an Excellon file, parses it and creates a new object for
  6193. it in the program. Thread-safe.
  6194. :param outname: Name of the resulting object. None causes the
  6195. name to be that of the file.
  6196. :param filename: Excellon file filename
  6197. :type filename: str
  6198. :return: None
  6199. """
  6200. App.log.debug("open_excellon()")
  6201. # How the object should be initialized
  6202. def obj_init(excellon_obj, app_obj):
  6203. # self.progress.emit(20)
  6204. try:
  6205. ret = excellon_obj.parse_file(filename=filename)
  6206. if ret == "fail":
  6207. log.debug("Excellon parsing failed.")
  6208. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  6209. return "fail"
  6210. except IOError:
  6211. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  6212. log.debug("Could not open Excellon object.")
  6213. self.progress.emit(0) # TODO: self and app_bjj mixed
  6214. return "fail"
  6215. except:
  6216. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  6217. msg += traceback.format_exc()
  6218. app_obj.inform.emit(msg)
  6219. return "fail"
  6220. ret = excellon_obj.create_geometry()
  6221. if ret == 'fail':
  6222. log.debug("Could not create geometry for Excellon object.")
  6223. return "fail"
  6224. for tool in excellon_obj.tools:
  6225. if excellon_obj.tools[tool]['solid_geometry']:
  6226. return
  6227. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  6228. return "fail"
  6229. with self.proc_container.new(_("Opening Excellon.")):
  6230. # Object name
  6231. name = outname or filename.split('/')[-1].split('\\')[-1]
  6232. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  6233. if ret_val == 'fail':
  6234. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  6235. return
  6236. # Register recent file
  6237. self.file_opened.emit("excellon", filename)
  6238. # GUI feedback
  6239. self.inform.emit(_("[success] Opened: %s") % filename)
  6240. def open_gcode(self, filename, outname=None):
  6241. """
  6242. Opens a G-gcode file, parses it and creates a new object for
  6243. it in the program. Thread-safe.
  6244. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6245. :param filename: G-code file filename
  6246. :type filename: str
  6247. :return: None
  6248. """
  6249. App.log.debug("open_gcode()")
  6250. # How the object should be initialized
  6251. def obj_init(job_obj, app_obj_):
  6252. """
  6253. :param job_obj: the resulting object
  6254. :type app_obj_: App
  6255. """
  6256. assert isinstance(app_obj_, App), \
  6257. "Initializer expected App, got %s" % type(app_obj_)
  6258. self.progress.emit(10)
  6259. try:
  6260. f = open(filename)
  6261. gcode = f.read()
  6262. f.close()
  6263. except IOError:
  6264. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  6265. self.progress.emit(0)
  6266. return "fail"
  6267. job_obj.gcode = gcode
  6268. self.progress.emit(20)
  6269. ret = job_obj.gcode_parse()
  6270. if ret == "fail":
  6271. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  6272. return "fail"
  6273. self.progress.emit(60)
  6274. job_obj.create_geometry()
  6275. with self.proc_container.new(_("Opening G-Code.")):
  6276. # Object name
  6277. name = outname or filename.split('/')[-1].split('\\')[-1]
  6278. # New object creation and file processing
  6279. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  6280. if ret == 'fail':
  6281. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  6282. "Attempting to create a FlatCAM CNCJob Object from "
  6283. "G-Code file failed during processing"))
  6284. return "fail"
  6285. # Register recent file
  6286. self.file_opened.emit("cncjob", filename)
  6287. # GUI feedback
  6288. self.inform.emit(_("[success] Opened: %s") % filename)
  6289. self.progress.emit(100)
  6290. def open_config_file(self, filename, run_from_arg=None):
  6291. """
  6292. Loads a config file from the specified file.
  6293. :param filename: Name of the file from which to load.
  6294. :type filename: str
  6295. :return: None
  6296. """
  6297. App.log.debug("Opening config file: " + filename)
  6298. # add the tab if it was closed
  6299. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  6300. # first clear previous text in text editor (if any)
  6301. self.ui.code_editor.clear()
  6302. # Switch plot_area to CNCJob tab
  6303. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6304. try:
  6305. if filename:
  6306. f = QtCore.QFile(filename)
  6307. if f.open(QtCore.QIODevice.ReadOnly):
  6308. stream = QtCore.QTextStream(f)
  6309. gcode_edited = stream.readAll()
  6310. self.ui.code_editor.setPlainText(gcode_edited)
  6311. f.close()
  6312. except IOError:
  6313. App.log.error("Failed to open config file: %s" % filename)
  6314. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  6315. return
  6316. def open_project(self, filename, run_from_arg=None):
  6317. """
  6318. Loads a project from the specified file.
  6319. 1) Loads and parses file
  6320. 2) Registers the file as recently opened.
  6321. 3) Calls on_file_new()
  6322. 4) Updates options
  6323. 5) Calls new_object() with the object's from_dict() as init method.
  6324. 6) Calls plot_all()
  6325. :param filename: Name of the file from which to load.
  6326. :type filename: str
  6327. :param run_from_arg: True if run for arguments
  6328. :return: None
  6329. """
  6330. App.log.debug("Opening project: " + filename)
  6331. # Open and parse an uncompressed Project file
  6332. try:
  6333. f = open(filename, 'r')
  6334. except IOError:
  6335. App.log.error("Failed to open project file: %s" % filename)
  6336. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6337. return
  6338. try:
  6339. d = json.load(f, object_hook=dict2obj)
  6340. except:
  6341. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s" % filename)
  6342. f.close()
  6343. # Open and parse a compressed Project file
  6344. try:
  6345. with lzma.open(filename) as f:
  6346. file_content = f.read().decode('utf-8')
  6347. d = json.loads(file_content, object_hook=dict2obj)
  6348. except IOError:
  6349. App.log.error("Failed to open project file: %s" % filename)
  6350. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6351. return
  6352. self.file_opened.emit("project", filename)
  6353. # Clear the current project
  6354. # # NOT THREAD SAFE ##
  6355. if run_from_arg is True:
  6356. pass
  6357. else:
  6358. self.on_file_new()
  6359. # Project options
  6360. self.options.update(d['options'])
  6361. self.project_filename = filename
  6362. self.set_screen_units(self.options["units"])
  6363. # Re create objects
  6364. App.log.debug("Re-creating objects...")
  6365. for obj in d['objs']:
  6366. def obj_init(obj_inst, app_inst):
  6367. obj_inst.from_dict(obj)
  6368. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  6369. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  6370. self.plot_all()
  6371. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  6372. self.should_we_save = False
  6373. App.log.debug("Project loaded")
  6374. def propagate_defaults(self, silent=False):
  6375. """
  6376. This method is used to set default values in classes. It's
  6377. an alternative to project options but allows the use
  6378. of values invisible to the user.
  6379. :return: None
  6380. """
  6381. if silent is False:
  6382. self.log.debug("propagate_defaults()")
  6383. # Which objects to update the given parameters.
  6384. routes = {
  6385. "global_zdownrate": CNCjob,
  6386. "excellon_zeros": Excellon,
  6387. "excellon_format_upper_in": Excellon,
  6388. "excellon_format_lower_in": Excellon,
  6389. "excellon_format_upper_mm": Excellon,
  6390. "excellon_format_lower_mm": Excellon,
  6391. "excellon_units": Excellon,
  6392. "gerber_use_buffer_for_union": Gerber,
  6393. "geometry_multidepth": Geometry
  6394. }
  6395. for param in routes:
  6396. if param in routes[param].defaults:
  6397. try:
  6398. routes[param].defaults[param] = self.defaults[param]
  6399. if silent is False:
  6400. self.log.debug(" " + param + " OK")
  6401. except KeyError:
  6402. if silent is False:
  6403. self.log.debug(" ERROR: " + param + " not in defaults.")
  6404. else:
  6405. # Try extracting the name:
  6406. # classname_param here is param in the object
  6407. if param.find(routes[param].__name__.lower() + "_") == 0:
  6408. p = param[len(routes[param].__name__) + 1:]
  6409. if p in routes[param].defaults:
  6410. routes[param].defaults[p] = self.defaults[param]
  6411. if silent is False:
  6412. self.log.debug(" " + param + " OK!")
  6413. def restore_main_win_geom(self):
  6414. try:
  6415. self.ui.setGeometry(self.defaults["global_def_win_x"],
  6416. self.defaults["global_def_win_y"],
  6417. self.defaults["global_def_win_w"],
  6418. self.defaults["global_def_win_h"])
  6419. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  6420. settings = QSettings("Open Source", "FlatCAM")
  6421. if settings.contains("maximized_gui"):
  6422. maximized_ui = settings.value('maximized_gui', type=bool)
  6423. if maximized_ui is True:
  6424. self.ui.showMaximized()
  6425. except KeyError as e:
  6426. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  6427. def plot_all(self, zoom=True):
  6428. """
  6429. Re-generates all plots from all objects.
  6430. :return: None
  6431. """
  6432. self.log.debug("Plot_all()")
  6433. for obj in self.collection.get_list():
  6434. def worker_task(obj):
  6435. with self.proc_container.new("Plotting"):
  6436. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  6437. if zoom:
  6438. self.object_plotted.emit(obj)
  6439. # Send to worker
  6440. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  6441. def register_folder(self, filename):
  6442. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6443. def register_save_folder(self, filename):
  6444. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6445. def set_progress_bar(self, percentage, text=""):
  6446. self.ui.progress_bar.setValue(int(percentage))
  6447. def setup_shell(self):
  6448. """
  6449. Creates shell functions. Runs once at startup.
  6450. :return: None
  6451. """
  6452. self.log.debug("setup_shell()")
  6453. def shelp(p=None):
  6454. if not p:
  6455. return _("Available commands:\n") + \
  6456. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  6457. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  6458. if p not in commands:
  6459. return "Unknown command: %s" % p
  6460. return commands[p]["help"]
  6461. # --- Migrated to new architecture ---
  6462. # def options(name):
  6463. # ops = self.collection.get_by_name(str(name)).options
  6464. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  6465. def h(*args):
  6466. """
  6467. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  6468. and standalone parameters into list.
  6469. """
  6470. kwa = {}
  6471. a = []
  6472. n = len(args)
  6473. name = None
  6474. for i in range(n):
  6475. match = re.search(r'^-([a-zA-Z].*)', args[i])
  6476. if match:
  6477. assert name is None
  6478. name = match.group(1)
  6479. continue
  6480. if name is None:
  6481. a.append(args[i])
  6482. else:
  6483. kwa[name] = args[i]
  6484. name = None
  6485. return a, kwa
  6486. @contextmanager
  6487. def wait_signal(signal, timeout=10000):
  6488. """
  6489. Block loop until signal emitted, timeout (ms) elapses
  6490. or unhandled exception happens in a thread.
  6491. :param timeout: time after which the loop is exited
  6492. :param signal: Signal to wait for.
  6493. """
  6494. loop = QtCore.QEventLoop()
  6495. # Normal termination
  6496. signal.connect(loop.quit)
  6497. # Termination by exception in thread
  6498. self.thread_exception.connect(loop.quit)
  6499. status = {'timed_out': False}
  6500. def report_quit():
  6501. status['timed_out'] = True
  6502. loop.quit()
  6503. yield
  6504. # Temporarily change how exceptions are managed.
  6505. oeh = sys.excepthook
  6506. ex = []
  6507. def except_hook(type_, value, traceback_):
  6508. ex.append(value)
  6509. oeh(type_, value, traceback_)
  6510. sys.excepthook = except_hook
  6511. # Terminate on timeout
  6512. if timeout is not None:
  6513. QtCore.QTimer.singleShot(timeout, report_quit)
  6514. # ### Block ####
  6515. loop.exec_()
  6516. # Restore exception management
  6517. sys.excepthook = oeh
  6518. if ex:
  6519. self.raiseTclError(str(ex[0]))
  6520. if status['timed_out']:
  6521. raise Exception('Timed out!')
  6522. def make_docs():
  6523. output = ''
  6524. import collections
  6525. od = collections.OrderedDict(sorted(commands.items()))
  6526. for cmd_, val in od.items():
  6527. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  6528. t = val['help']
  6529. usage_i = t.find('>')
  6530. if usage_i < 0:
  6531. expl = t
  6532. output += expl + '\n\n'
  6533. continue
  6534. expl = t[:usage_i - 1]
  6535. output += expl + '\n\n'
  6536. end_usage_i = t[usage_i:].find('\n')
  6537. if end_usage_i < 0:
  6538. end_usage_i = len(t[usage_i:])
  6539. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  6540. else:
  6541. extras = t[usage_i+end_usage_i+1:]
  6542. parts = [s.strip() for s in extras.split('\n')]
  6543. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  6544. for p in parts:
  6545. output += ' ' + p + '\n\n'
  6546. return output
  6547. '''
  6548. Howto implement TCL shell commands:
  6549. All parameters passed to command should be possible to set as None and test it afterwards.
  6550. This is because we need to see error caused in tcl,
  6551. if None value as default parameter is not allowed TCL will return empty error.
  6552. Use:
  6553. def mycommand(name=None,...):
  6554. Test it like this:
  6555. if name is None:
  6556. self.raise_tcl_error('Argument name is missing.')
  6557. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  6558. otherwise we will miss it and processing will silently continue.
  6559. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  6560. which is catched in exec_command and displayed in TCL shell console with red background.
  6561. Error in console is displayed with TCL trace.
  6562. This behavior works only within main thread,
  6563. errors with promissed tasks can be catched and detected only with log.
  6564. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  6565. TCL shell.
  6566. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  6567. '''
  6568. commands = {
  6569. 'help': {
  6570. 'fcn': shelp,
  6571. 'help': _("Shows list of commands.")
  6572. },
  6573. }
  6574. # Import/overwrite tcl commands as objects of TclCommand descendants
  6575. # This modifies the variable 'commands'.
  6576. tclCommands.register_all_commands(self, commands)
  6577. # Add commands to the tcl interpreter
  6578. for cmd in commands:
  6579. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  6580. # Make the tcl puts function return instead of print to stdout
  6581. self.tcl.eval('''
  6582. rename puts original_puts
  6583. proc puts {args} {
  6584. if {[llength $args] == 1} {
  6585. return "[lindex $args 0]"
  6586. } else {
  6587. eval original_puts $args
  6588. }
  6589. }
  6590. ''')
  6591. def setup_recent_items(self):
  6592. # TODO: Move this to constructor
  6593. icons = {
  6594. "gerber": "share/flatcam_icon16.png",
  6595. "excellon": "share/drill16.png",
  6596. 'geometry': "share/geometry16.png",
  6597. "cncjob": "share/cnc16.png",
  6598. "project": "share/project16.png",
  6599. "svg": "share/geometry16.png",
  6600. "dxf": "share/dxf16.png",
  6601. "pdf": "share/pdf32.png",
  6602. "image": "share/image16.png"
  6603. }
  6604. openers = {
  6605. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  6606. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  6607. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  6608. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  6609. 'project': self.open_project,
  6610. 'svg': self.import_svg,
  6611. 'dxf': self.import_dxf,
  6612. 'image': self.import_image,
  6613. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  6614. }
  6615. # Open file
  6616. try:
  6617. f = open(self.data_path + '/recent.json')
  6618. except IOError:
  6619. App.log.error("Failed to load recent item list.")
  6620. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  6621. return
  6622. try:
  6623. self.recent = json.load(f)
  6624. except json.scanner.JSONDecodeError:
  6625. App.log.error("Failed to parse recent item list.")
  6626. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  6627. f.close()
  6628. return
  6629. f.close()
  6630. # Closure needed to create callbacks in a loop.
  6631. # Otherwise late binding occurs.
  6632. def make_callback(func, fname):
  6633. def opener():
  6634. func(fname)
  6635. return opener
  6636. def reset_recent():
  6637. # Reset menu
  6638. self.ui.recent.clear()
  6639. self.recent = []
  6640. try:
  6641. f = open(self.data_path + '/recent.json', 'w')
  6642. except IOError:
  6643. App.log.error("Failed to open recent items file for writing.")
  6644. return
  6645. json.dump(self.recent, f)
  6646. # Reset menu
  6647. self.ui.recent.clear()
  6648. # Create menu items
  6649. for recent in self.recent:
  6650. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6651. try:
  6652. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6653. # Attach callback
  6654. o = make_callback(openers[recent["kind"]], recent['filename'])
  6655. action.triggered.connect(o)
  6656. self.ui.recent.addAction(action)
  6657. except KeyError:
  6658. App.log.error("Unsupported file type: %s" % recent["kind"])
  6659. # Last action in Recent Files menu is one that Clear the content
  6660. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  6661. clear_action.triggered.connect(reset_recent)
  6662. self.ui.recent.addSeparator()
  6663. self.ui.recent.addAction(clear_action)
  6664. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6665. # self.ui.menufilerecent.set_submenu(recent_menu)
  6666. # recent_menu.show_all()
  6667. # self.ui.recent.show()
  6668. self.log.debug("Recent items list has been populated.")
  6669. def setup_component_editor(self):
  6670. # label = QtWidgets.QLabel("Choose an item from Project")
  6671. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6672. sel_title = QtWidgets.QTextEdit(
  6673. _('<b>Shortcut Key List</b>'))
  6674. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6675. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6676. # font = self.sel_title.font()
  6677. # font.setPointSize(12)
  6678. # self.sel_title.setFont(font)
  6679. selected_text = _('''
  6680. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  6681. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6682. The normal flow when working in FlatCAM is the following:</span></p>
  6683. <ol>
  6684. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  6685. <br />
  6686. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  6687. &nbsp;</li>
  6688. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  6689. <br />
  6690. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  6691. <br />
  6692. You can change the parameters in this screen and the flow direction is like this:<br />
  6693. <br />
  6694. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  6695. </ol>
  6696. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  6697. ''')
  6698. sel_title.setText(selected_text)
  6699. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6700. self.ui.selected_scroll_area.setWidget(sel_title)
  6701. # tool_title = QtWidgets.QTextEdit(
  6702. # '<b>Shortcut Key List</b>')
  6703. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6704. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6705. # # font = self.sel_title.font()
  6706. # # font.setPointSize(12)
  6707. # # self.sel_title.setFont(font)
  6708. #
  6709. # tool_text = '''
  6710. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  6711. #
  6712. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6713. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  6714. #
  6715. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  6716. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  6717. #
  6718. # <ol>
  6719. # </ol>
  6720. #
  6721. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  6722. #
  6723. # '''
  6724. #
  6725. # tool_title.setText(tool_text)
  6726. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6727. #
  6728. # self.ui.tool_scroll_area.setWidget(tool_title)
  6729. def setup_obj_classes(self):
  6730. """
  6731. Sets up application specifics on the FlatCAMObj class.
  6732. :return: None
  6733. """
  6734. FlatCAMObj.app = self
  6735. ObjectCollection.app = self
  6736. FCProcess.app = self
  6737. FCProcessContainer.app = self
  6738. def version_check(self):
  6739. """
  6740. Checks for the latest version of the program. Alerts the
  6741. user if theirs is outdated. This method is meant to be run
  6742. in a separate thread.
  6743. :return: None
  6744. """
  6745. self.log.debug("version_check()")
  6746. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6747. full_url = App.version_url + \
  6748. "?s=" + str(self.defaults['global_serial']) + \
  6749. "&v=" + str(self.version) + \
  6750. "&os=" + str(self.os) + \
  6751. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  6752. else:
  6753. # no_stats dict; just so it won't break things on website
  6754. no_ststs_dict = {}
  6755. no_ststs_dict["global_ststs"] = {}
  6756. full_url = App.version_url + \
  6757. "?s=" + str(self.defaults['global_serial']) + \
  6758. "&v=" + str(self.version) + \
  6759. "&os=" + str(self.os) + \
  6760. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6761. App.log.debug("Checking for updates @ %s" % full_url)
  6762. ### Get the data
  6763. try:
  6764. f = urllib.request.urlopen(full_url)
  6765. except:
  6766. # App.log.warning("Failed checking for latest version. Could not connect.")
  6767. self.log.warning("Failed checking for latest version. Could not connect.")
  6768. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  6769. return
  6770. try:
  6771. data = json.load(f)
  6772. except Exception as e:
  6773. App.log.error("Could not parse information about latest version.")
  6774. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  6775. App.log.debug("json.load(): %s" % str(e))
  6776. f.close()
  6777. return
  6778. f.close()
  6779. ### Latest version?
  6780. if self.version >= data["version"]:
  6781. App.log.debug("FlatCAM is up to date!")
  6782. self.inform.emit(_("[success] FlatCAM is up to date!"))
  6783. return
  6784. App.log.debug("Newer version available.")
  6785. self.message.emit(
  6786. _("Newer Version Available"),
  6787. _("There is a newer version of FlatCAM available for download:\n\n") +
  6788. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  6789. _("info")
  6790. )
  6791. def on_zoom_fit(self, event):
  6792. """
  6793. Callback for zoom-out request. This can be either from the corresponding
  6794. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6795. with axes limits from the geometry bounds of all objects.
  6796. :param event: Ignored.
  6797. :return: None
  6798. """
  6799. self.plotcanvas.fit_view()
  6800. def disable_all_plots(self):
  6801. self.report_usage("disable_all_plots()")
  6802. self.disable_plots(self.collection.get_list())
  6803. self.inform.emit(_("[success] All plots disabled."))
  6804. def disable_other_plots(self):
  6805. self.report_usage("disable_other_plots()")
  6806. self.disable_plots(self.collection.get_non_selected())
  6807. self.inform.emit(_("[success] All non selected plots disabled."))
  6808. def enable_all_plots(self):
  6809. self.report_usage("enable_all_plots()")
  6810. self.enable_plots(self.collection.get_list())
  6811. self.inform.emit(_("[success] All plots enabled."))
  6812. # TODO: FIX THIS
  6813. '''
  6814. By default this is not threaded
  6815. If threaded the app give warnings like this:
  6816. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6817. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6818. '''
  6819. def enable_plots(self, objects, threaded=True):
  6820. if threaded is True:
  6821. def worker_task(app_obj):
  6822. # percentage = 0.1
  6823. # try:
  6824. # delta = 0.9 / len(objects)
  6825. # except ZeroDivisionError:
  6826. # self.progress.emit(0)
  6827. # return
  6828. for obj in objects:
  6829. obj.options['plot'] = True
  6830. # percentage += delta
  6831. # self.progress.emit(int(percentage*100))
  6832. # self.progress.emit(0)
  6833. self.plots_updated.emit()
  6834. # self.collection.update_view()
  6835. # Send to worker
  6836. # self.worker.add_task(worker_task, [self])
  6837. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6838. else:
  6839. for obj in objects:
  6840. obj.options['plot'] = True
  6841. # self.progress.emit(0)
  6842. self.plots_updated.emit()
  6843. # self.collection.update_view()
  6844. # TODO: FIX THIS
  6845. '''
  6846. By default this is not threaded
  6847. If threaded the app give warnings like this:
  6848. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6849. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6850. '''
  6851. def disable_plots(self, objects, threaded=True):
  6852. # TODO: This method is very similar to replot_all. Try to merge.
  6853. """
  6854. Disables plots
  6855. :param objects: list
  6856. Objects to be disabled
  6857. :return:
  6858. """
  6859. if threaded is True:
  6860. # self.progress.emit(10)
  6861. def worker_task(app_obj):
  6862. # percentage = 0.1
  6863. # try:
  6864. # delta = 0.9 / len(objects)
  6865. # except ZeroDivisionError:
  6866. # self.progress.emit(0)
  6867. # return
  6868. for obj in objects:
  6869. obj.options['plot'] = False
  6870. # percentage += delta
  6871. # self.progress.emit(int(percentage*100))
  6872. # self.progress.emit(0)
  6873. self.plots_updated.emit()
  6874. # self.collection.update_view()
  6875. # Send to worker
  6876. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6877. else:
  6878. for obj in objects:
  6879. obj.options['plot'] = False
  6880. self.plots_updated.emit()
  6881. # self.collection.update_view()
  6882. def clear_plots(self):
  6883. objects = self.collection.get_list()
  6884. for obj in objects:
  6885. obj.clear(obj == objects[-1])
  6886. # Clear pool to free memory
  6887. self.clear_pool()
  6888. def generate_cnc_job(self, objects):
  6889. self.report_usage("generate_cnc_job()")
  6890. # for obj in objects:
  6891. # obj.generatecncjob()
  6892. for obj in objects:
  6893. obj.on_generatecnc_button_click()
  6894. def save_project(self, filename, quit=False):
  6895. """
  6896. Saves the current project to the specified file.
  6897. :param filename: Name of the file in which to save.
  6898. :type filename: str
  6899. :return: None
  6900. """
  6901. self.log.debug("save_project()")
  6902. self.save_in_progress = True
  6903. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6904. ## Capture the latest changes
  6905. # Current object
  6906. try:
  6907. self.collection.get_active().read_form()
  6908. except:
  6909. self.log.debug("There was no active object")
  6910. pass
  6911. # Project options
  6912. self.options_read_form()
  6913. # Serialize the whole project
  6914. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6915. "options": self.options,
  6916. "version": self.version}
  6917. if self.defaults["global_save_compressed"] is True:
  6918. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6919. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6920. # # Write
  6921. f.write(g)
  6922. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6923. else:
  6924. # Open file
  6925. try:
  6926. f = open(filename, 'w')
  6927. except IOError:
  6928. App.log.error("Failed to open file for saving: %s", filename)
  6929. return
  6930. # Write
  6931. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6932. f.close()
  6933. # verification of the saved project
  6934. # Open and parse
  6935. try:
  6936. saved_f = open(filename, 'r')
  6937. except IOError:
  6938. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6939. return
  6940. try:
  6941. saved_d = json.load(saved_f, object_hook=dict2obj)
  6942. except:
  6943. self.inform.emit(
  6944. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6945. f.close()
  6946. return
  6947. saved_f.close()
  6948. if 'version' in saved_d:
  6949. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6950. else:
  6951. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6952. # if quit:
  6953. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  6954. # t.start()
  6955. self.start_delayed_quit(delay=500, filename=filename, quit=quit)
  6956. def start_delayed_quit(self, delay, filename, quit=None):
  6957. """
  6958. :param delay: period of checking if project file size is more than zero; in seconds
  6959. :param filename: the name of the project file to be checked periodically for size more than zero
  6960. :return:
  6961. """
  6962. to_quit = quit
  6963. self.save_timer = QtCore.QTimer()
  6964. self.save_timer.setInterval(delay)
  6965. self.save_timer.timeout.connect(lambda : self.check_project_file_size(filename=filename, quit=to_quit))
  6966. self.save_timer.start()
  6967. def check_project_file_size(self, filename, quit=None):
  6968. """
  6969. :param filename: the name of the project file to be checked periodically for size more than zero
  6970. :return:
  6971. """
  6972. try:
  6973. if os.stat(filename).st_size > 0:
  6974. self.save_in_progress = False
  6975. self.save_timer.stop()
  6976. if quit:
  6977. self.app_quit.emit()
  6978. except Exception:
  6979. traceback.print_exc()
  6980. def on_options_app2project(self):
  6981. """
  6982. Callback for Options->Transfer Options->App=>Project. Copies options
  6983. from application defaults to project defaults.
  6984. :return: None
  6985. """
  6986. self.report_usage("on_options_app2project")
  6987. self.defaults_read_form()
  6988. self.options.update(self.defaults)
  6989. self.options_write_form()
  6990. def on_options_project2app(self):
  6991. """
  6992. Callback for Options->Transfer Options->Project=>App. Copies options
  6993. from project defaults to application defaults.
  6994. :return: None
  6995. """
  6996. self.report_usage("on_options_project2app")
  6997. self.options_read_form()
  6998. self.defaults.update(self.options)
  6999. self.defaults_write_form()
  7000. def on_options_project2object(self):
  7001. """
  7002. Callback for Options->Transfer Options->Project=>Object. Copies options
  7003. from project defaults to the currently selected object.
  7004. :return: None
  7005. """
  7006. self.report_usage("on_options_project2object")
  7007. self.options_read_form()
  7008. obj = self.collection.get_active()
  7009. if obj is None:
  7010. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7011. return
  7012. for option in self.options:
  7013. if option.find(obj.kind + "_") == 0:
  7014. oname = option[len(obj.kind) + 1:]
  7015. obj.options[oname] = self.options[option]
  7016. obj.to_form() # Update UI
  7017. def on_options_object2project(self):
  7018. """
  7019. Callback for Options->Transfer Options->Object=>Project. Copies options
  7020. from the currently selected object to project defaults.
  7021. :return: None
  7022. """
  7023. self.report_usage("on_options_object2project")
  7024. obj = self.collection.get_active()
  7025. if obj is None:
  7026. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7027. return
  7028. obj.read_form()
  7029. for option in obj.options:
  7030. if option in ['name']: # TODO: Handle this better...
  7031. continue
  7032. self.options[obj.kind + "_" + option] = obj.options[option]
  7033. self.options_write_form()
  7034. def on_options_object2app(self):
  7035. """
  7036. Callback for Options->Transfer Options->Object=>App. Copies options
  7037. from the currently selected object to application defaults.
  7038. :return: None
  7039. """
  7040. self.report_usage("on_options_object2app")
  7041. obj = self.collection.get_active()
  7042. if obj is None:
  7043. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7044. return
  7045. obj.read_form()
  7046. for option in obj.options:
  7047. if option in ['name']: # TODO: Handle this better...
  7048. continue
  7049. self.defaults[obj.kind + "_" + option] = obj.options[option]
  7050. self.defaults_write_form()
  7051. def on_options_app2object(self):
  7052. """
  7053. Callback for Options->Transfer Options->App=>Object. Copies options
  7054. from application defaults to the currently selected object.
  7055. :return: None
  7056. """
  7057. self.report_usage("on_options_app2object")
  7058. self.defaults_read_form()
  7059. obj = self.collection.get_active()
  7060. if obj is None:
  7061. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7062. return
  7063. for option in self.defaults:
  7064. if option.find(obj.kind + "_") == 0:
  7065. oname = option[len(obj.kind) + 1:]
  7066. obj.options[oname] = self.defaults[option]
  7067. obj.to_form() # Update UI
  7068. # end of file