FlatCAMApp.py 413 KB

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