FlatCAMApp.py 520 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580
  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 ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. if sys.platform == 'win32':
  53. import winreg
  54. fcTranslate.apply_language('strings')
  55. if '_' not in builtins.__dict__:
  56. _ = gettext.gettext
  57. # ########################################
  58. # # App ###
  59. # ########################################
  60. class App(QtCore.QObject):
  61. """
  62. The main application class. The constructor starts the GUI.
  63. """
  64. # Get Cmd Line Options
  65. cmd_line_shellfile = ''
  66. cmd_line_shellvar = ''
  67. cmd_line_headless = None
  68. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  69. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  70. "FlatCam.py --headless=1"
  71. try:
  72. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  73. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  74. "shellvar=",
  75. "headless=",
  76. "multiprocessing-fork="])
  77. except getopt.GetoptError:
  78. print(cmd_line_help)
  79. sys.exit(2)
  80. for opt, arg in cmd_line_options:
  81. if opt == '-h':
  82. print(cmd_line_help)
  83. sys.exit()
  84. elif opt == '--shellfile':
  85. cmd_line_shellfile = arg
  86. elif opt == '--shellvar':
  87. cmd_line_shellvar = arg
  88. elif opt == '--headless':
  89. try:
  90. cmd_line_headless = eval(arg)
  91. except NameError:
  92. pass
  93. # ## Logging ###
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ##########################################################################
  102. # ################## Version and VERSION DATE ##############################
  103. # ##########################################################################
  104. version = 8.97
  105. version_date = "2019/09/22"
  106. beta = True
  107. engine = '3D'
  108. # current date now
  109. date = str(datetime.today()).rpartition('.')[0]
  110. date = ''.join(c for c in date if c not in ':-')
  111. date = date.replace(' ', '_')
  112. # URL for update checks and statistics
  113. version_url = "http://flatcam.org/version"
  114. # App URL
  115. app_url = "http://flatcam.org"
  116. # Manual URL
  117. manual_url = "http://flatcam.org/manual/index.html"
  118. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  119. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  120. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  121. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  122. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  123. # this variable will hold the project status
  124. # if True it will mean that the project was modified and not saved
  125. should_we_save = False
  126. # flag is True if saving action has been triggered
  127. save_in_progress = False
  128. # ###########################################################################
  129. # ############################# Signals ################################
  130. # ###########################################################################
  131. # Inform the user
  132. # Handled by:
  133. # * App.info() --> Print on the status bar
  134. inform = QtCore.pyqtSignal(str)
  135. app_quit = QtCore.pyqtSignal()
  136. # General purpose background task
  137. worker_task = QtCore.pyqtSignal(dict)
  138. # File opened
  139. # Handled by:
  140. # * register_folder()
  141. # * register_recent()
  142. # Note: Setting the parameters to unicode does not seem
  143. # to have an effect. Then are received as Qstring
  144. # anyway.
  145. # File type and filename
  146. file_opened = QtCore.pyqtSignal(str, str)
  147. # File type and filename
  148. file_saved = QtCore.pyqtSignal(str, str)
  149. # Percentage of progress
  150. progress = QtCore.pyqtSignal(int)
  151. plots_updated = QtCore.pyqtSignal()
  152. # Emitted by new_object() and passes the new object as argument, plot flag.
  153. # on_object_created() adds the object to the collection, plots on appropriate flag
  154. # and emits new_object_available.
  155. object_created = QtCore.pyqtSignal(object, bool, bool)
  156. # Emitted when a object has been changed (like scaled, mirrored)
  157. object_changed = QtCore.pyqtSignal(object)
  158. # Emitted after object has been plotted.
  159. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  160. object_plotted = QtCore.pyqtSignal(object)
  161. # Emitted when a new object has been added or deleted from/to the collection
  162. object_status_changed = QtCore.pyqtSignal(object, str)
  163. message = QtCore.pyqtSignal(str, str, str)
  164. # Emmited when shell command is finished(one command only)
  165. shell_command_finished = QtCore.pyqtSignal(object)
  166. # Emitted when multiprocess pool has been recreated
  167. pool_recreated = QtCore.pyqtSignal(object)
  168. # Emitted when an unhandled exception happens
  169. # in the worker task.
  170. thread_exception = QtCore.pyqtSignal(object)
  171. # used to signal that there are arguments for the app
  172. args_at_startup = QtCore.pyqtSignal(list)
  173. # a reusable signal to replot a list of objects
  174. # should be disconnected after use so it can be reused
  175. replot_signal = pyqtSignal(list)
  176. def __init__(self, user_defaults=True, post_gui=None):
  177. """
  178. Starts the application.
  179. :return: app
  180. :rtype: App
  181. """
  182. App.log.info("FlatCAM Starting...")
  183. self.main_thread = QtWidgets.QApplication.instance().thread()
  184. # ############################################################################
  185. # # ################# OS-specific ############################################
  186. # ############################################################################
  187. portable = False
  188. # Folder for user settings.
  189. if sys.platform == 'win32':
  190. # #########################################################################
  191. # Setup the listening thread for another instance launching with args #####
  192. # #########################################################################
  193. # make sure the thread is stored by using a self. otherwise it's garbage collected
  194. self.th = QtCore.QThread()
  195. self.th.start(priority=QtCore.QThread.LowestPriority)
  196. self.new_launch = ArgsThread()
  197. self.new_launch.open_signal[list].connect(self.on_startup_args)
  198. self.new_launch.moveToThread(self.th)
  199. self.new_launch.start.emit()
  200. from win32com.shell import shell, shellcon
  201. if platform.architecture()[0] == '32bit':
  202. App.log.debug("Win32!")
  203. else:
  204. App.log.debug("Win64!")
  205. # #########################################################################
  206. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  207. # #########################################################################
  208. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  209. try:
  210. with open(config_file, 'r'):
  211. pass
  212. except FileNotFoundError:
  213. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  214. try:
  215. with open(config_file, 'r') as f:
  216. try:
  217. for line in f:
  218. param = str(line).replace('\n', '').rpartition('=')
  219. if param[0] == 'portable':
  220. try:
  221. portable = eval(param[2])
  222. except NameError:
  223. portable = False
  224. if param[0] == 'headless':
  225. if param[2].lower() == 'true':
  226. self.cmd_line_headless = 1
  227. else:
  228. self.cmd_line_headless = None
  229. except Exception as e:
  230. log.debug('App.__init__() -->%s' % str(e))
  231. return
  232. except FileNotFoundError as e:
  233. log.debug(str(e))
  234. pass
  235. if portable is False:
  236. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  237. else:
  238. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  239. self.os = 'windows'
  240. else: # Linux/Unix/MacOS
  241. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  242. self.os = 'unix'
  243. # ##########################################################################
  244. # ################## Setup folders and files ###############################
  245. # ##########################################################################
  246. if not os.path.exists(self.data_path):
  247. os.makedirs(self.data_path)
  248. App.log.debug('Created data folder: ' + self.data_path)
  249. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  250. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  251. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  252. if not os.path.exists(self.postprocessorpaths):
  253. os.makedirs(self.postprocessorpaths)
  254. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  255. # create current_defaults.FlatConfig file if there is none
  256. try:
  257. f = open(self.data_path + '/current_defaults.FlatConfig')
  258. f.close()
  259. except IOError:
  260. App.log.debug('Creating empty current_defaults.FlatConfig')
  261. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  262. json.dump({}, f)
  263. f.close()
  264. # create factory_defaults.FlatConfig file if there is none
  265. try:
  266. f = open(self.data_path + '/factory_defaults.FlatConfig')
  267. f.close()
  268. except IOError:
  269. App.log.debug('Creating empty factory_defaults.FlatConfig')
  270. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  271. json.dump({}, f)
  272. f.close()
  273. # create a recent files json file if there is none
  274. try:
  275. f = open(self.data_path + '/recent.json')
  276. f.close()
  277. except IOError:
  278. App.log.debug('Creating empty recent.json')
  279. f = open(self.data_path + '/recent.json', 'w')
  280. json.dump([], f)
  281. f.close()
  282. # create a recent projects json file if there is none
  283. try:
  284. fp = open(self.data_path + '/recent_projects.json')
  285. fp.close()
  286. except IOError:
  287. App.log.debug('Creating empty recent_projects.json')
  288. fp = open(self.data_path + '/recent_projects.json', 'w')
  289. json.dump([], fp)
  290. fp.close()
  291. # Application directory. CHDIR to it. Otherwise, trying to load
  292. # GUI icons will fail as their path is relative.
  293. # This will fail under cx_freeze ...
  294. self.app_home = os.path.dirname(os.path.realpath(__file__))
  295. App.log.debug("Application path is " + self.app_home)
  296. App.log.debug("Started in " + os.getcwd())
  297. # cx_freeze workaround
  298. if os.path.isfile(self.app_home):
  299. self.app_home = os.path.dirname(self.app_home)
  300. os.chdir(self.app_home)
  301. # #############################################################################
  302. # ##################### CREATE MULTIPROCESSING POOL ###########################
  303. # #############################################################################
  304. self.pool = Pool()
  305. # ##########################################################################
  306. # ################## Setting the Splash Screen #############################
  307. # ##########################################################################
  308. settings = QSettings("Open Source", "FlatCAM")
  309. if settings.contains("splash_screen"):
  310. show_splash = settings.value("splash_screen")
  311. else:
  312. settings.setValue('splash_screen', 1)
  313. # This will write the setting to the platform specific storage.
  314. del settings
  315. show_splash = 1
  316. if show_splash and self.cmd_line_headless != 1:
  317. splash_pix = QtGui.QPixmap('share/splash.png')
  318. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  319. # self.splash.setMask(splash_pix.mask())
  320. # move splashscreen to the current monitor
  321. desktop = QtWidgets.QApplication.desktop()
  322. screen = desktop.screenNumber(QtGui.QCursor.pos())
  323. current_screen_center = desktop.availableGeometry(screen).center()
  324. self.splash.move(current_screen_center - self.splash.rect().center())
  325. self.splash.show()
  326. self.splash.showMessage(_("FlatCAM is initializing ..."),
  327. alignment=Qt.AlignBottom | Qt.AlignLeft,
  328. color=QtGui.QColor("gray"))
  329. else:
  330. show_splash = 0
  331. # #############################################################################
  332. # ##################### Initialize GUI ########################################
  333. # #############################################################################
  334. # FlatCAM colors used in plotting
  335. self.FC_light_green = '#BBF268BF'
  336. self.FC_dark_green = '#006E20BF'
  337. self.FC_light_blue = '#a5a5ffbf'
  338. self.FC_dark_blue = '#0000ffbf'
  339. QtCore.QObject.__init__(self)
  340. self.ui = FlatCAMGUI(self.version, self.beta, self)
  341. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  342. self.ui.final_save.connect(self.final_save)
  343. # #############################################################################
  344. # ############################## Data #########################################
  345. # #############################################################################
  346. self.recent = []
  347. self.recent_projects = []
  348. self.clipboard = QtWidgets.QApplication.clipboard()
  349. self.project_filename = None
  350. self.toggle_units_ignore = False
  351. # self.defaults_form = PreferencesUI()
  352. # when adding entries here read the comments in the method found bellow named:
  353. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  354. self.defaults_form_fields = {
  355. # General App
  356. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  357. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  358. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  359. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  360. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  361. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  362. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  363. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  364. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  365. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  366. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  367. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  368. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  369. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  370. # General GUI Preferences
  371. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  372. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  373. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  374. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  375. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  376. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  377. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  378. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  379. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  380. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  381. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  382. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  383. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  384. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  385. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  386. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  387. # General GUI Settings
  388. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  389. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  390. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  391. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  392. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  393. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  394. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  395. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  396. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  397. # Gerber General
  398. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  399. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  400. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  401. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  402. # Gerber Options
  403. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  404. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  405. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  406. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  407. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  408. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  409. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  410. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  411. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  412. # Gerber Advanced Options
  413. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  414. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  415. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  416. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  417. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  418. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  419. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  420. # Gerber Export
  421. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  422. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  423. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  424. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  425. # Gerber Editor
  426. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  427. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  428. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  429. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  430. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  431. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  432. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  433. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  434. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  435. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  436. "gerber_editor_circ_angle":
  437. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  438. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  439. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  440. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  441. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  442. # Excellon General
  443. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  444. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  445. "excellon_format_upper_in":
  446. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  447. "excellon_format_lower_in":
  448. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  449. "excellon_format_upper_mm":
  450. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  451. "excellon_format_lower_mm":
  452. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  453. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  454. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  455. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  456. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  457. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  458. # Excellon Options
  459. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  460. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  461. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  462. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  463. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  464. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  465. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  466. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  467. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  468. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  469. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  470. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  471. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  472. # Excellon Advanced Options
  473. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  474. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  475. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  476. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  477. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  478. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  479. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  480. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  481. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  482. # Excellon Export
  483. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  484. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  485. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  486. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  487. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  488. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  489. # Excellon Editor
  490. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  491. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  492. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  493. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  494. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  495. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  496. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  497. "excellon_editor_circ_angle":
  498. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  499. # Excellon Slots
  500. "excellon_editor_slot_direction":
  501. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  502. "excellon_editor_slot_angle":
  503. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  504. "excellon_editor_slot_length":
  505. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  506. # Excellon Slots
  507. "excellon_editor_slot_array_size":
  508. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  509. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  510. "excellon_editor_slot_lin_pitch":
  511. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  512. "excellon_editor_slot_lin_angle":
  513. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  514. "excellon_editor_slot_circ_dir":
  515. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  516. "excellon_editor_slot_circ_angle":
  517. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  518. # Geometry General
  519. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  520. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  521. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  522. # Geometry Options
  523. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  524. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  525. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  526. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  527. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  528. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  529. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  530. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  531. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  532. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  533. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  534. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  535. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  536. # Geometry Advanced Options
  537. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  538. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  539. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  540. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  541. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  542. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  543. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  544. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  545. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  546. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  547. # Geometry Editor
  548. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  549. # CNCJob General
  550. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  551. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  552. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  553. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  554. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  555. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  556. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  557. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  558. # CNC Job Options
  559. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  560. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  561. # CNC Job Advanced Options
  562. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  563. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  564. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  565. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  566. # NCC Tool
  567. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  568. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  569. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  570. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  571. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  572. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  573. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  574. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  575. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  576. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  577. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  578. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  579. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  580. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  581. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  582. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  583. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  584. # CutOut Tool
  585. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  586. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  587. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  588. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  589. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  590. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  591. # Paint Area Tool
  592. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  593. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  594. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  595. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  596. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  597. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  598. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  599. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  600. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  601. # 2-sided Tool
  602. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  603. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  604. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  605. # Film Tool
  606. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  607. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  608. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  609. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  610. # Panelize Tool
  611. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  612. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  613. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  614. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  615. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  616. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  617. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  618. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  619. # Calculators Tool
  620. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  621. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  622. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  623. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  624. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  625. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  626. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  627. # Transformations Tool
  628. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  629. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  630. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  631. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  632. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  633. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  634. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  635. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  636. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  637. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  638. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  639. # SolderPaste Dispensing Tool
  640. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  641. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  642. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  643. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  644. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  645. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  646. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  647. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  648. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  649. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  650. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  651. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  652. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  653. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  654. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  655. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  656. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  657. # Utilities
  658. # File associations
  659. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  660. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  661. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  662. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  663. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  664. }
  665. # ############################
  666. # ### LOAD POSTPROCESSORS ####
  667. # ############################
  668. self.postprocessors = load_postprocessors(self)
  669. for name in list(self.postprocessors.keys()):
  670. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  671. if name.partition('_')[0] == 'Paste':
  672. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  673. continue
  674. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  675. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  676. if name == 'hpgl':
  677. continue
  678. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  679. # ############################
  680. # ### LOAD LANGUAGES ####
  681. # ############################
  682. self.languages = fcTranslate.load_languages()
  683. for name in sorted(self.languages.values()):
  684. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  685. # #################################################################################
  686. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  687. # #################################################################################
  688. self.defaults = LoudDict()
  689. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  690. self.defaults.update({
  691. # Global APP Preferences
  692. "first_run": True,
  693. "units": "IN",
  694. "global_serial": 0,
  695. "global_stats": {},
  696. "global_tabs_detachable": True,
  697. "global_graphic_engine": '3D',
  698. "global_app_level": 'b',
  699. "global_portable": False,
  700. "global_language": 'English',
  701. "global_version_check": True,
  702. "global_send_stats": True,
  703. "global_pan_button": '2',
  704. "global_mselect_key": 'Control',
  705. "global_project_at_startup": False,
  706. "global_systray_icon": True,
  707. "global_project_autohide": True,
  708. "global_toggle_tooltips": True,
  709. "global_worker_number": 2,
  710. "global_tolerance": 0.005,
  711. "global_open_style": True,
  712. "global_delete_confirmation": True,
  713. "global_compression_level": 3,
  714. "global_save_compressed": True,
  715. # Global GUI Preferences
  716. "global_gridx": 0.0393701,
  717. "global_gridy": 0.0393701,
  718. "global_snap_max": 0.001968504,
  719. "global_workspace": False,
  720. "global_workspaceT": "A4P",
  721. "global_grid_context_menu": {
  722. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  723. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  724. },
  725. "global_plot_fill": '#BBF268BF',
  726. "global_plot_line": '#006E20BF',
  727. "global_sel_fill": '#a5a5ffbf',
  728. "global_sel_line": '#0000ffbf',
  729. "global_alt_sel_fill": '#BBF268BF',
  730. "global_alt_sel_line": '#006E20BF',
  731. "global_draw_color": '#FF0000',
  732. "global_sel_draw_color": '#0000FF',
  733. "global_proj_item_color": '#000000',
  734. "global_proj_item_dis_color": '#b7b7cb',
  735. "global_activity_icon": 'Ball green',
  736. "global_toolbar_view": 511,
  737. "global_background_timeout": 300000, # Default value is 5 minutes
  738. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  739. # (python trace only for unknown errors),
  740. # 1 = show trace(show trace always),
  741. # 2 = (For the future).
  742. # Persistence
  743. "global_last_folder": None,
  744. "global_last_save_folder": None,
  745. # Default window geometry
  746. "global_def_win_x": 100,
  747. "global_def_win_y": 100,
  748. "global_def_win_w": 1024,
  749. "global_def_win_h": 650,
  750. "global_def_notebook_width": 1,
  751. # Constants...
  752. "global_defaults_save_period_ms": 20000, # Time between default saves.
  753. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  754. "global_shell_at_startup": False, # Show the shell at startup.
  755. "global_recent_limit": 10, # Max. items in recent list.
  756. "fit_key": 'V',
  757. "zoom_out_key": '-',
  758. "zoom_in_key": '=',
  759. "grid_toggle_key": 'G',
  760. "global_zoom_ratio": 1.5,
  761. "global_point_clipboard_format": "(%.4f, %.4f)",
  762. "global_zdownrate": None,
  763. # General GUI Settings
  764. "global_hover": False,
  765. "global_selection_shape": True,
  766. "global_layout": "compact",
  767. # Gerber General
  768. "gerber_plot": True,
  769. "gerber_solid": True,
  770. "gerber_multicolored": False,
  771. "gerber_circle_steps": 128,
  772. "gerber_use_buffer_for_union": True,
  773. # Gerber Options
  774. "gerber_isotooldia": 0.00787402,
  775. "gerber_isopasses": 1,
  776. "gerber_isooverlap": 0.00393701,
  777. "gerber_milling_type": "cl",
  778. "gerber_combine_passes": False,
  779. "gerber_noncoppermargin": 0.00393701,
  780. "gerber_noncopperrounded": False,
  781. "gerber_bboxmargin": 0.00393701,
  782. "gerber_bboxrounded": False,
  783. # Gerber Advanced Options
  784. "gerber_aperture_display": False,
  785. "gerber_aperture_scale_factor": 1.0,
  786. "gerber_aperture_buffer_factor": 0.0,
  787. "gerber_follow": False,
  788. "gerber_buffering": "full",
  789. "gerber_simplification": False,
  790. "gerber_simp_tolerance": 0.0005,
  791. # Gerber Export
  792. "gerber_exp_units": 'IN',
  793. "gerber_exp_integer": 2,
  794. "gerber_exp_decimals": 4,
  795. "gerber_exp_zeros": 'L',
  796. # Gerber Editor
  797. "gerber_editor_sel_limit": 30,
  798. "gerber_editor_newcode": 10,
  799. "gerber_editor_newsize": 0.8,
  800. "gerber_editor_newtype": 'C',
  801. "gerber_editor_newdim": "0.5, 0.5",
  802. "gerber_editor_array_size": 5,
  803. "gerber_editor_lin_axis": 'X',
  804. "gerber_editor_lin_pitch": 1,
  805. "gerber_editor_lin_angle": 0.0,
  806. "gerber_editor_circ_dir": 'CW',
  807. "gerber_editor_circ_angle": 0.0,
  808. "gerber_editor_scale_f": 1.0,
  809. "gerber_editor_buff_f": 0.1,
  810. "gerber_editor_ma_low": 0.0,
  811. "gerber_editor_ma_high": 1.0,
  812. # Excellon General
  813. "excellon_plot": True,
  814. "excellon_solid": True,
  815. "excellon_format_upper_in": 2,
  816. "excellon_format_lower_in": 4,
  817. "excellon_format_upper_mm": 3,
  818. "excellon_format_lower_mm": 3,
  819. "excellon_zeros": "L",
  820. "excellon_units": "INCH",
  821. "excellon_update": True,
  822. "excellon_optimization_type": 'B',
  823. "excellon_search_time": 3,
  824. # Excellon Options
  825. "excellon_drillz": -0.0590551,
  826. "excellon_travelz": 0.0787402,
  827. "excellon_endz": 0.5,
  828. "excellon_feedrate": 3.14961,
  829. "excellon_spindlespeed": None,
  830. "excellon_dwell": False,
  831. "excellon_dwelltime": 1,
  832. "excellon_toolchange": False,
  833. "excellon_toolchangez": 0.5,
  834. "excellon_ppname_e": 'default',
  835. "excellon_tooldia": 0.0314961,
  836. "excellon_slot_tooldia": 0.0708661,
  837. "excellon_gcode_type": "drills",
  838. # Excellon Advanced Options
  839. "excellon_offset": 0.0,
  840. "excellon_toolchangexy": "0.0, 0.0",
  841. "excellon_startz": None,
  842. "excellon_feedrate_rapid": 31.4961,
  843. "excellon_z_pdepth": -0.02,
  844. "excellon_feedrate_probe": 3.14961,
  845. "excellon_spindledir": 'CW',
  846. "excellon_f_plunge": False,
  847. "excellon_f_retract": False,
  848. # Excellon Export
  849. "excellon_exp_units": 'INCH',
  850. "excellon_exp_format": 'ndec',
  851. "excellon_exp_integer": 2,
  852. "excellon_exp_decimals": 4,
  853. "excellon_exp_zeros": 'LZ',
  854. "excellon_exp_slot_type": 'routing',
  855. # Excellon Editor
  856. "excellon_editor_sel_limit": 30,
  857. "excellon_editor_newdia": 0.039,
  858. "excellon_editor_array_size": 5,
  859. "excellon_editor_lin_dir": 'X',
  860. "excellon_editor_lin_pitch": 0.1,
  861. "excellon_editor_lin_angle": 0.0,
  862. "excellon_editor_circ_dir": 'CW',
  863. "excellon_editor_circ_angle": 12,
  864. # Excellon Slots
  865. "excellon_editor_slot_direction": 'X',
  866. "excellon_editor_slot_angle": 0.0,
  867. "excellon_editor_slot_length": 5.0,
  868. # Excellon Slot Array
  869. "excellon_editor_slot_array_size": 5,
  870. "excellon_editor_slot_lin_dir": 'X',
  871. "excellon_editor_slot_lin_pitch": 0.1,
  872. "excellon_editor_slot_lin_angle": 0.0,
  873. "excellon_editor_slot_circ_dir": 'CW',
  874. "excellon_editor_slot_circ_angle": 0.0,
  875. # Geometry General
  876. "geometry_plot": True,
  877. "geometry_circle_steps": 128,
  878. "geometry_cnctooldia": "0.0944882",
  879. # Geometry Options
  880. "geometry_cutz": -0.0944882,
  881. "geometry_vtipdia": 0.1,
  882. "geometry_vtipangle": 30,
  883. "geometry_multidepth": False,
  884. "geometry_depthperpass": 0.0314961,
  885. "geometry_travelz": 0.0787402,
  886. "geometry_toolchange": False,
  887. "geometry_toolchangez": 0.5,
  888. "geometry_endz": 0.5,
  889. "geometry_feedrate": 3.14961,
  890. "geometry_feedrate_z": 3.14961,
  891. "geometry_spindlespeed": None,
  892. "geometry_dwell": False,
  893. "geometry_dwelltime": 1,
  894. "geometry_ppname_g": 'default',
  895. # Geometry Advanced Options
  896. "geometry_toolchangexy": "0.0, 0.0",
  897. "geometry_startz": None,
  898. "geometry_feedrate_rapid": 3.14961,
  899. "geometry_extracut": False,
  900. "geometry_z_pdepth": -0.02,
  901. "geometry_f_plunge": False,
  902. "geometry_spindledir": 'CW',
  903. "geometry_feedrate_probe": 3.14961,
  904. "geometry_segx": 0.0,
  905. "geometry_segy": 0.0,
  906. # Geometry Editor
  907. "geometry_editor_sel_limit": 30,
  908. # CNC Job General
  909. "cncjob_plot": True,
  910. "cncjob_plot_kind": 'all',
  911. "cncjob_annotation": True,
  912. "cncjob_tooldia": 0.0393701,
  913. "cncjob_coords_type": "G90",
  914. "cncjob_coords_decimals": 4,
  915. "cncjob_fr_decimals": 2,
  916. "cncjob_steps_per_circle": 128,
  917. # CNC Job Options
  918. "cncjob_prepend": "",
  919. "cncjob_append": "",
  920. # CNC Job Advanced Options
  921. "cncjob_toolchange_macro": "",
  922. "cncjob_toolchange_macro_enable": False,
  923. "cncjob_annotation_fontsize": 9,
  924. "cncjob_annotation_fontcolor": '#990000',
  925. # NCC Tool
  926. "tools_ncctools": "0.0393701, 0.019685",
  927. "tools_nccorder": 'rev',
  928. "tools_nccoverlap": 0.015748,
  929. "tools_nccmargin": 0.0393701,
  930. "tools_nccmethod": "seed",
  931. "tools_nccconnect": True,
  932. "tools_ncccontour": True,
  933. "tools_nccrest": False,
  934. "tools_ncc_offset_choice": False,
  935. "tools_ncc_offset_value": 0.0000,
  936. "tools_nccref": 'itself',
  937. "tools_ncc_plotting": 'normal',
  938. "tools_nccmilling_type": 'cl',
  939. "tools_ncctool_type": 'V',
  940. "tools_ncccutz": -0.001968504,
  941. "tools_ncctipdia": 0.00393701,
  942. "tools_ncctipangle": 30,
  943. # Cutout Tool
  944. "tools_cutouttooldia": 0.0944882,
  945. "tools_cutoutkind": "single",
  946. "tools_cutoutmargin": 0.00393701,
  947. "tools_cutoutgapsize": 0.15748,
  948. "tools_gaps_ff": "4",
  949. "tools_cutout_convexshape": False,
  950. # Paint Tool
  951. "tools_painttooldia": 0.023622,
  952. "tools_paintorder": 'rev',
  953. "tools_paintoverlap": 0.015748,
  954. "tools_paintmargin": 0.0,
  955. "tools_paintmethod": "seed",
  956. "tools_selectmethod": "all",
  957. "tools_pathconnect": True,
  958. "tools_paintcontour": True,
  959. "tools_paint_plotting": 'normal',
  960. # 2-Sided Tool
  961. "tools_2sided_mirror_axis": "X",
  962. "tools_2sided_axis_loc": "point",
  963. "tools_2sided_drilldia": 0.11811,
  964. # Film Tool
  965. "tools_film_type": 'neg',
  966. "tools_film_boundary": 0.0393701,
  967. "tools_film_scale": 0,
  968. "tools_film_color": '#000000',
  969. # Panel Tool
  970. "tools_panelize_spacing_columns": 0,
  971. "tools_panelize_spacing_rows": 0,
  972. "tools_panelize_columns": 1,
  973. "tools_panelize_rows": 1,
  974. "tools_panelize_constrain": False,
  975. "tools_panelize_constrainx": 0.0,
  976. "tools_panelize_constrainy": 0.0,
  977. "tools_panelize_panel_type": 'gerber',
  978. # Calculators Tool
  979. "tools_calc_vshape_tip_dia": 0.007874,
  980. "tools_calc_vshape_tip_angle": 30,
  981. "tools_calc_vshape_cut_z": 0.000787,
  982. "tools_calc_electro_length": 10.0,
  983. "tools_calc_electro_width": 10.0,
  984. "tools_calc_electro_cdensity": 13.0,
  985. "tools_calc_electro_growth": 10.0,
  986. # Transform Tool
  987. "tools_transform_rotate": 90,
  988. "tools_transform_skew_x": 0.0,
  989. "tools_transform_skew_y": 0.0,
  990. "tools_transform_scale_x": 1.0,
  991. "tools_transform_scale_y": 1.0,
  992. "tools_transform_scale_link": True,
  993. "tools_transform_scale_reference": True,
  994. "tools_transform_offset_x": 0.0,
  995. "tools_transform_offset_y": 0.0,
  996. "tools_transform_mirror_reference": False,
  997. "tools_transform_mirror_point": (0, 0),
  998. # SolderPaste Tool
  999. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1000. "tools_solderpaste_new": 0.011811,
  1001. "tools_solderpaste_z_start": 0.00019685039,
  1002. "tools_solderpaste_z_dispense": 0.00393701,
  1003. "tools_solderpaste_z_stop": 0.00019685039,
  1004. "tools_solderpaste_z_travel": 0.00393701,
  1005. "tools_solderpaste_z_toolchange": 0.0393701,
  1006. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1007. "tools_solderpaste_frxy": 3.0,
  1008. "tools_solderpaste_frz": 3.0,
  1009. "tools_solderpaste_frz_dispense": 0.0393701,
  1010. "tools_solderpaste_speedfwd": 20,
  1011. "tools_solderpaste_dwellfwd": 1,
  1012. "tools_solderpaste_speedrev": 10,
  1013. "tools_solderpaste_dwellrev": 1,
  1014. "tools_solderpaste_pp": 'Paste_1',
  1015. # Subtract Tool
  1016. "tools_sub_close_paths": True,
  1017. # Utilities
  1018. # file associations
  1019. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1020. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1021. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1022. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1023. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1024. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1025. # Keyword list
  1026. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1027. 'Repetier, Roland_MDX_20, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1028. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, axisoffset, box, '
  1029. 'center_x, center_y, columns, combine, connect, contour, default, '
  1030. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1031. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1032. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1033. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1034. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1035. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1036. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1037. ,
  1038. })
  1039. # ############################################################
  1040. # ############### Load defaults from file ####################
  1041. # ############################################################
  1042. if user_defaults:
  1043. self.load_defaults(filename='current_defaults')
  1044. # #############################################################
  1045. # ############## APPLY APP LANGUAGE ###########################
  1046. # #############################################################
  1047. ret_val = fcTranslate.apply_language('strings')
  1048. if ret_val == "no language":
  1049. self.inform.emit('[ERROR] %s' %
  1050. _("Could not find the Language files. The App strings are missing."))
  1051. log.debug("Could not find the Language files. The App strings are missing.")
  1052. else:
  1053. # make the current language the current selection on the language combobox
  1054. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1055. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1056. # ##############################################################
  1057. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1058. # ##############################################################
  1059. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1060. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1061. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1062. self.save_defaults(silent=True, first_time=True)
  1063. self.propagate_defaults(silent=True)
  1064. self.restore_main_win_geom()
  1065. # def auto_save_defaults():
  1066. # try:
  1067. # self.save_defaults(silent=True)
  1068. # self.propagate_defaults(silent=True)
  1069. # finally:
  1070. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1071. # the following lines activates automatic defaults save
  1072. # if user_defaults:
  1073. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1074. # self.options_form = PreferencesUI()
  1075. self.options_form_fields = {
  1076. "units": self.ui.general_options_form.general_app_group.units_radio,
  1077. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1078. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1079. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1080. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1081. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1082. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1083. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1084. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1085. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1086. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1087. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1088. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1089. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1090. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1091. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1092. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1093. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1094. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1095. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1096. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1097. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1098. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1099. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1100. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1101. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1102. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1103. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1104. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1105. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1106. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1107. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1108. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1109. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1110. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1111. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1112. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1113. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1114. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1115. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1116. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1117. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1118. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1119. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1120. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1121. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1122. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1123. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1124. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1125. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1126. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1127. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1128. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1129. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1130. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1131. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1132. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1133. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1134. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1135. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1136. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1137. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1138. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1139. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1140. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1141. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1142. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1143. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1144. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1145. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1146. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1147. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1148. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1149. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1150. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1151. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1152. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1153. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1154. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1155. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1156. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1157. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1158. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1159. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1160. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1161. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1162. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1163. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1164. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1165. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1166. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1167. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1168. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1169. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1170. }
  1171. for name in list(self.postprocessors.keys()):
  1172. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1173. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1174. self.options = LoudDict()
  1175. self.options.set_change_callback(self.on_options_dict_change)
  1176. self.options.update({
  1177. "units": "IN",
  1178. "global_gridx": 1.0,
  1179. "global_gridy": 1.0,
  1180. "global_snap_max": 0.05,
  1181. "global_background_timeout": 300000, # Default value is 5 minutes
  1182. "global_verbose_error_level": 0, # Shell verbosity:
  1183. # 0 = default(python trace only for unknown errors),
  1184. # 1 = show trace(show trace allways), 2 = (For the future).
  1185. "gerber_plot": True,
  1186. "gerber_solid": True,
  1187. "gerber_multicolored": False,
  1188. "gerber_isotooldia": 0.016,
  1189. "gerber_isopasses": 1,
  1190. "gerber_isooverlap": 0.15,
  1191. "gerber_combine_passes": True,
  1192. "gerber_noncoppermargin": 0.0,
  1193. "gerber_noncopperrounded": False,
  1194. "gerber_bboxmargin": 0.0,
  1195. "gerber_bboxrounded": False,
  1196. "excellon_plot": True,
  1197. "excellon_solid": False,
  1198. "excellon_format_upper_in": 2,
  1199. "excellon_format_lower_in": 4,
  1200. "excellon_format_upper_mm": 3,
  1201. "excellon_format_lower_mm": 3,
  1202. "excellon_units": 'INCH',
  1203. "excellon_optimization_type": 'B',
  1204. "excellon_search_time": 3,
  1205. "excellon_zeros": "L",
  1206. "excellon_drillz": -0.1,
  1207. "excellon_travelz": 0.1,
  1208. "excellon_feedrate": 3.0,
  1209. "excellon_feedrate_rapid": 3.0,
  1210. "excellon_spindlespeed": None,
  1211. "excellon_spindledir": 'CW',
  1212. "excellon_dwell": True,
  1213. "excellon_dwelltime": 1000,
  1214. "excellon_toolchange": False,
  1215. "excellon_toolchangez": 1.0,
  1216. "excellon_toolchangexy": "0.0, 0.0",
  1217. "excellon_tooldia": 0.016,
  1218. "excellon_ppname_e": 'default',
  1219. "excellon_f_plunge": False,
  1220. "excellon_startz": None,
  1221. "excellon_endz": 2.0,
  1222. "geometry_plot": True,
  1223. "geometry_segx": 0.0,
  1224. "geometry_segy": 0.0,
  1225. "geometry_cutz": -0.002,
  1226. "geometry_vtipdia": 0.1,
  1227. "geometry_vtipangle": 30,
  1228. "geometry_travelz": 0.1,
  1229. "geometry_feedrate": 3.0,
  1230. "geometry_feedrate_z": 3.0,
  1231. "geometry_feedrate_rapid": 3.0,
  1232. "geometry_spindlespeed": None,
  1233. "geometry_spindledir": 'CW',
  1234. "geometry_dwell": True,
  1235. "geometry_dwelltime": 1000,
  1236. "geometry_cnctooldia": 0.016,
  1237. "geometry_toolchange": False,
  1238. "geometry_toolchangez": 2.0,
  1239. "geometry_toolchangexy": "0.0, 0.0",
  1240. "geometry_startz": None,
  1241. "geometry_endz": 2.0,
  1242. "geometry_ppname_g": "default",
  1243. "geometry_f_plunge": False,
  1244. "geometry_depthperpass": 0.002,
  1245. "geometry_multidepth": False,
  1246. "geometry_extracut": False,
  1247. "cncjob_plot": True,
  1248. "cncjob_tooldia": 0.016,
  1249. "cncjob_prepend": "",
  1250. "cncjob_append": "",
  1251. "tools_ncctools": "1.0, 0.5",
  1252. "tools_nccoverlap": 0.4,
  1253. "tools_nccmargin": 1,
  1254. "tools_cutouttooldia": 0.07,
  1255. "tools_cutoutmargin": 0.1,
  1256. "tools_cutoutgapsize": 0.15,
  1257. "tools_gaps_ff": "8",
  1258. "tools_painttooldia": 0.07,
  1259. "tools_paintoverlap": 0.15,
  1260. "tools_paintmargin": 0.0,
  1261. "tools_paintmethod": "seed",
  1262. "tools_selectmethod": "single",
  1263. "tools_pathconnect": True,
  1264. "tools_paintcontour": True,
  1265. "tools_2sided_mirror_axis": "X",
  1266. "tools_2sided_axis_loc": 'point',
  1267. "tools_2sided_drilldia": 1,
  1268. "tools_film_type": 'neg',
  1269. "tools_film_boundary": 1,
  1270. "tools_film_scale": 0,
  1271. "tools_panelize_spacing_columns": 0,
  1272. "tools_panelize_spacing_rows": 0,
  1273. "tools_panelize_columns": 1,
  1274. "tools_panelize_rows": 1,
  1275. "tools_panelize_constrain": False,
  1276. "tools_panelize_constrainx": 0.0,
  1277. "tools_panelize_constrainy": 0.0
  1278. })
  1279. self.options.update(self.defaults) # Copy app defaults to project options
  1280. self.gen_form = None
  1281. self.ger_form = None
  1282. self.exc_form = None
  1283. self.geo_form = None
  1284. self.cnc_form = None
  1285. self.tools_form = None
  1286. self.fa_form = None
  1287. self.on_options_combo_change(0) # Will show the initial form
  1288. # ################################
  1289. # ### Initialize the color box's color in Preferences -> Global -> Color
  1290. # Init Plot Colors
  1291. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1292. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1293. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1294. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1295. int(self.defaults['global_plot_fill'][7:9], 16))
  1296. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1297. int(self.defaults['global_plot_fill'][7:9], 16))
  1298. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1299. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1300. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1301. # Init Left-Right Selection colors
  1302. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1303. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1304. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1305. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1306. int(self.defaults['global_sel_fill'][7:9], 16))
  1307. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1308. int(self.defaults['global_sel_fill'][7:9], 16))
  1309. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1310. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1311. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1312. # Init Right-Left Selection colors
  1313. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1314. self.defaults['global_alt_sel_fill'])
  1315. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1316. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1317. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1318. int(self.defaults['global_sel_fill'][7:9], 16))
  1319. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1320. int(self.defaults['global_sel_fill'][7:9], 16))
  1321. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1322. self.defaults['global_alt_sel_line'])
  1323. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1324. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1325. # Init Draw color and Selection Draw Color
  1326. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1327. self.defaults['global_draw_color'])
  1328. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1329. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1330. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1331. self.defaults['global_sel_draw_color'])
  1332. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1333. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1334. # Init Project Items color
  1335. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1336. self.defaults['global_proj_item_color'])
  1337. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1338. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1339. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1340. self.defaults['global_proj_item_dis_color'])
  1341. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1342. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1343. # Init the Annotation CNC Job color
  1344. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1345. self.defaults['cncjob_annotation_fontcolor'])
  1346. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1347. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1348. # Init the Tool Film color
  1349. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1350. self.defaults['tools_film_color'])
  1351. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1352. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1353. # ### End of Data ####
  1354. # ##############################################
  1355. # ######### SETUP OBJECT COLLECTION ############
  1356. # ##############################################
  1357. self.collection = ObjectCollection(self)
  1358. self.ui.project_tab_layout.addWidget(self.collection.view)
  1359. # ### Adjust tabs width ## ##
  1360. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1361. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1362. self.collection.view.setMinimumWidth(290)
  1363. self.log.debug("Finished creating Object Collection.")
  1364. # ###############################################
  1365. # ############# SETUP Plot Area #################
  1366. # ###############################################
  1367. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1368. if self.defaults["global_graphic_engine"] == '3D':
  1369. self.is_legacy = False
  1370. else:
  1371. self.is_legacy = True
  1372. # Matplotlib axis
  1373. self.axes = None
  1374. if show_splash:
  1375. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1376. "Canvas initialization started."),
  1377. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1378. color=QtGui.QColor("gray"))
  1379. start_plot_time = time.time() # debug
  1380. self.plotcanvas = None
  1381. self.app_cursor = None
  1382. self.hover_shapes = None
  1383. self.on_plotcanvas_setup()
  1384. end_plot_time = time.time()
  1385. self.used_time = end_plot_time - start_plot_time
  1386. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1387. if show_splash:
  1388. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1389. "Canvas initialization started.\n"
  1390. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1391. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1392. color=QtGui.QColor("gray"))
  1393. self.ui.splitter.setStretchFactor(1, 2)
  1394. # #################################################################
  1395. # ####################### SYS TRAY ################################
  1396. # #################################################################
  1397. if self.defaults["global_systray_icon"]:
  1398. self.parent_w = QtWidgets.QWidget()
  1399. if self.cmd_line_headless == 1:
  1400. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1401. headless=True,
  1402. parent=self.parent_w)
  1403. else:
  1404. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1405. parent=self.parent_w)
  1406. # ###############################################
  1407. # ############# Worker SETUP ####################
  1408. # ###############################################
  1409. if self.defaults["global_worker_number"]:
  1410. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1411. else:
  1412. self.workers = WorkerStack(workers_number=2)
  1413. self.worker_task.connect(self.workers.add_task)
  1414. self.log.debug("Finished creating Workers crew.")
  1415. # ################################################
  1416. # ############### Activity Monitor ###############
  1417. # ################################################
  1418. if self.defaults["global_activity_icon"] == "Ball green":
  1419. icon = 'share/active_2_static.png'
  1420. movie = "share/active_2.gif"
  1421. elif self.defaults["global_activity_icon"] == "Ball black":
  1422. icon = 'share/active_static.png'
  1423. movie = "share/active.gif"
  1424. elif self.defaults["global_activity_icon"] == "Arrow green":
  1425. icon = 'share/active_3_static.png'
  1426. movie = "share/active_3.gif"
  1427. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1428. icon = 'share/active_4_static.png'
  1429. movie = "share/active_4.gif"
  1430. else:
  1431. icon = 'share/active_static.png'
  1432. movie = "share/active.gif"
  1433. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1434. self.ui.infobar.addWidget(self.activity_view)
  1435. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1436. # ################################################
  1437. # ############### Signal handling ################
  1438. # ################################################
  1439. # ############# Custom signals ##################
  1440. # signal for displaying messages in status bar
  1441. self.inform.connect(self.info)
  1442. # signal to be called when the app is quiting
  1443. self.app_quit.connect(self.quit_application)
  1444. self.message.connect(self.message_dialog)
  1445. self.progress.connect(self.set_progress_bar)
  1446. # signals that are emitted when object state changes
  1447. self.object_created.connect(self.on_object_created)
  1448. self.object_changed.connect(self.on_object_changed)
  1449. self.object_plotted.connect(self.on_object_plotted)
  1450. self.plots_updated.connect(self.on_plots_updated)
  1451. # signals emitted when file state change
  1452. self.file_opened.connect(self.register_recent)
  1453. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1454. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1455. # ############# Standard signals ###################
  1456. # ### Menu
  1457. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1458. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1459. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1460. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1461. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1462. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1463. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1464. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1465. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1466. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1467. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1468. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1469. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1470. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1471. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1472. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1473. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1474. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1475. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1476. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1477. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1478. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1479. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1480. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1481. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1482. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1483. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1484. self.ui.menufile_exit.triggered.connect(self.final_save)
  1485. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1486. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1487. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1488. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1489. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1490. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1491. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1492. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1493. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1494. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1495. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1496. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1497. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1498. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1499. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1500. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1501. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1502. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1503. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1504. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1505. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1506. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1507. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1508. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1509. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1510. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1511. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1512. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1513. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1514. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1515. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1516. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1517. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1518. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1519. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1520. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1521. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1522. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1523. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1524. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1525. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1526. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1527. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1528. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1529. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1530. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1531. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1532. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1533. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1534. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1535. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1536. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1537. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1538. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1539. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1540. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1541. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1542. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1543. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1544. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1545. # ToolBar signals
  1546. self.connect_toolbar_signals()
  1547. # Notebook signals
  1548. # make the right click on the notebook tab connect to a function
  1549. self.ui.notebook.setupContextMenu()
  1550. self.ui.notebook.addContextMenu(
  1551. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1552. initial_checked=self.defaults["global_tabs_detachable"])
  1553. # activate initial state
  1554. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1555. # Context Menu
  1556. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1557. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1558. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1559. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1560. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1561. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1562. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1563. self.ui.clearplot.triggered.connect(self.clear_plots)
  1564. self.ui.replot.triggered.connect(self.plot_all)
  1565. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1566. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1567. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1568. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1569. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1570. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1571. # Preferences Plot Area TAB
  1572. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1573. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1574. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1575. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1576. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1577. # ##############################
  1578. # ### GUI PREFERENCES SIGNALS ##
  1579. # ##############################
  1580. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(
  1581. lambda: fcTranslate.restart_program(app=self)
  1582. )
  1583. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1584. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1585. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1586. )
  1587. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1588. lambda: self.on_toggle_units(no_pref=False))
  1589. # ###############################################################
  1590. # ################### GUI COLORS SIGNALS ########################
  1591. # ###############################################################
  1592. # Setting plot colors signals
  1593. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1594. self.on_pf_color_entry)
  1595. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1596. self.on_pf_color_button)
  1597. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1598. self.on_pf_color_spinner)
  1599. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1600. self.on_pf_color_slider)
  1601. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1602. self.on_pl_color_entry)
  1603. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1604. self.on_pl_color_button)
  1605. # Setting selection (left - right) colors signals
  1606. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1607. self.on_sf_color_entry)
  1608. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1609. self.on_sf_color_button)
  1610. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1611. self.on_sf_color_spinner)
  1612. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1613. self.on_sf_color_slider)
  1614. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1615. self.on_sl_color_entry)
  1616. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1617. self.on_sl_color_button)
  1618. # Setting selection (right - left) colors signals
  1619. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1620. self.on_alt_sf_color_entry)
  1621. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1622. self.on_alt_sf_color_button)
  1623. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1624. self.on_alt_sf_color_spinner)
  1625. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1626. self.on_alt_sf_color_slider)
  1627. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1628. self.on_alt_sl_color_entry)
  1629. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1630. self.on_alt_sl_color_button)
  1631. # Setting Editor Draw colors signals
  1632. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1633. self.on_draw_color_entry)
  1634. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1635. self.on_draw_color_button)
  1636. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1637. self.on_sel_draw_color_entry)
  1638. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1639. self.on_sel_draw_color_button)
  1640. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1641. self.on_proj_color_entry)
  1642. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1643. self.on_proj_color_button)
  1644. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1645. self.on_proj_color_dis_entry)
  1646. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1647. self.on_proj_color_dis_button)
  1648. # ########## workspace setting signals ###########
  1649. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1650. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1651. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1652. # ########## CNC Job related signals #############
  1653. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1654. self.on_cnc_custom_parameters)
  1655. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1656. self.on_annotation_fontcolor_entry)
  1657. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1658. self.on_annotation_fontcolor_button)
  1659. # ########## Tools related signals #############
  1660. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1661. self.on_film_color_entry)
  1662. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1663. self.on_film_color_button)
  1664. # ########## Modify G-CODE Plot Area TAB ###########
  1665. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1666. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1667. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1668. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1669. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1670. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1671. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1672. # portability changed signal
  1673. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1674. # Object list
  1675. self.collection.view.activated.connect(self.on_row_activated)
  1676. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1677. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1678. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1679. # Export Excellon parameters.
  1680. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1681. self.on_update_exc_export
  1682. )
  1683. # call it once to make sure it is updated at startup
  1684. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1685. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1686. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1687. self.on_excellon_defaults_button)
  1688. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1689. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1690. self.on_excellon_options_button)
  1691. # when there are arguments at application startup this get launched
  1692. self.args_at_startup[list].connect(self.on_startup_args)
  1693. # ##############################################################
  1694. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1695. # ##############################################################
  1696. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1697. lambda: self.restore_extensions(ext_type='excellon'))
  1698. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1699. lambda: self.restore_extensions(ext_type='gcode'))
  1700. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1701. lambda: self.restore_extensions(ext_type='gerber'))
  1702. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1703. lambda: self.delete_all_extensions(ext_type='excellon'))
  1704. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1705. lambda: self.delete_all_extensions(ext_type='gcode'))
  1706. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1707. lambda: self.delete_all_extensions(ext_type='gerber'))
  1708. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1709. lambda: self.add_extension(ext_type='excellon'))
  1710. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1711. lambda: self.add_extension(ext_type='gcode'))
  1712. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1713. lambda: self.add_extension(ext_type='gerber'))
  1714. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1715. lambda: self.del_extension(ext_type='excellon'))
  1716. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1717. lambda: self.del_extension(ext_type='gcode'))
  1718. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1719. lambda: self.del_extension(ext_type='gerber'))
  1720. # connect the 'Apply' buttons from the Preferences/File Associations
  1721. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1722. lambda: self.on_register_files(obj_type='excellon'))
  1723. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1724. lambda: self.on_register_files(obj_type='gcode'))
  1725. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1726. lambda: self.on_register_files(obj_type='gerber'))
  1727. # ##############################################################
  1728. # ###################### KEYWORDS SIGNALS ######################
  1729. # ##############################################################
  1730. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1731. lambda: self.restore_extensions(ext_type='keyword'))
  1732. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1733. lambda: self.delete_all_extensions(ext_type='keyword'))
  1734. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1735. lambda: self.add_extension(ext_type='keyword'))
  1736. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1737. lambda: self.del_extension(ext_type='keyword'))
  1738. # splash screen button signal
  1739. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1740. # connect the abort_all_tasks related slots to the related signals
  1741. self.proc_container.idle_flag.connect(self.app_is_idle)
  1742. # #####################################################################################
  1743. # ########### FINISHED CONNECTING SIGNALS #############################################
  1744. # #####################################################################################
  1745. self.log.debug("Finished connecting Signals.")
  1746. # #####################################################################################
  1747. # ########################## Other setups #############################################
  1748. # #####################################################################################
  1749. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1750. # depending on from where those tools are called different actions can be done
  1751. self.call_source = 'app'
  1752. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1753. self.tool_tab_locked = False
  1754. # decide if to show or hide the Notebook side of the screen at startup
  1755. if self.defaults["global_project_at_startup"] is True:
  1756. self.ui.splitter.setSizes([1, 1])
  1757. else:
  1758. self.ui.splitter.setSizes([0, 1])
  1759. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1760. self.setup_obj_classes()
  1761. self.setup_recent_items()
  1762. self.setup_component_editor()
  1763. # this does not work in Legacy Mode
  1764. if self.is_legacy is True:
  1765. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1766. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1767. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1768. # #####################################################################################
  1769. # ######################### Auto-complete KEYWORDS ####################################
  1770. # #####################################################################################
  1771. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1772. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1773. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1774. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1775. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1776. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1777. 'mirror', 'ncc',
  1778. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1779. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1780. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1781. 'save', 'save_project',
  1782. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1783. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1784. 'version', 'write_gcode'
  1785. ]
  1786. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1787. 'Repetier', 'Roland_MDX_20', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1788. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset',
  1789. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1790. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1791. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1792. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1793. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1794. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1795. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1796. 'spacing_columns',
  1797. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1798. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1799. ]
  1800. self.tcl_keywords = [
  1801. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1802. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1803. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1804. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1805. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1806. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1807. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1808. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1809. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1810. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1811. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1812. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1813. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1814. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1815. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1816. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1817. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1818. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1819. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1820. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1821. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1822. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1823. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1824. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1825. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1826. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1827. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1828. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1829. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1830. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1831. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1832. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1833. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1834. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1835. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1836. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1837. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1838. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1839. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1840. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1841. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1842. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1843. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1844. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1845. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1846. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1847. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1848. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1849. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1850. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1851. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1852. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1853. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1854. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1855. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1856. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1857. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1858. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1859. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1860. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1861. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1862. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1863. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1864. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1865. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1866. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1867. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1868. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1869. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1870. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1871. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1872. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1873. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1874. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1875. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1876. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1877. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1878. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1879. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1880. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1881. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1882. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1883. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1884. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1885. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1886. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1887. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1888. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1889. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1890. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1891. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1892. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1893. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1894. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1895. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1896. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1897. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1898. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1899. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1900. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1901. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1902. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1903. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1904. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1905. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1906. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1907. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1908. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1909. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1910. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1911. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1912. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1913. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1914. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1915. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1916. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1917. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1918. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1919. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1920. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1921. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1922. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1923. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1924. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1925. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1926. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1927. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1928. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1929. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1930. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1931. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1932. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1933. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1934. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1935. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1936. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1937. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1938. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1939. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1940. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1941. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1942. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1943. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1944. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1945. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1946. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1947. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1948. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1949. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1950. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1951. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1952. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1953. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1954. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1955. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1956. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1957. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1958. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1959. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1960. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1961. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1962. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1963. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1964. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1965. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1966. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1967. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1968. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1969. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1970. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1971. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1972. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1973. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1974. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1975. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1976. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1977. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1978. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1979. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1980. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1981. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1982. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1983. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1984. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1985. ]
  1986. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1987. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1988. # ####################################################################################
  1989. # ####################### Shell SETUP ################################################
  1990. # ####################################################################################
  1991. self.shell = FCShell(self, version=self.version)
  1992. self.shell._edit.set_model_data(self.myKeywords)
  1993. self.ui.code_editor.set_model_data(self.myKeywords)
  1994. self.shell.setWindowIcon(self.ui.app_icon)
  1995. self.shell.setWindowTitle("FlatCAM Shell")
  1996. self.shell.resize(*self.defaults["global_shell_shape"])
  1997. self.shell.append_output("FlatCAM %s - " % self.version)
  1998. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1999. self.init_tcl()
  2000. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2001. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2002. self.ui.shell_dock.setWidget(self.shell)
  2003. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2004. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2005. QtWidgets.QDockWidget.DockWidgetFloatable |
  2006. QtWidgets.QDockWidget.DockWidgetClosable)
  2007. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2008. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2009. if self.defaults["global_shell_at_startup"]:
  2010. self.ui.shell_dock.show()
  2011. else:
  2012. self.ui.shell_dock.hide()
  2013. # ##################################################################################
  2014. # ###################### Tools and Plugins #########################################
  2015. # ##################################################################################
  2016. self.dblsidedtool = None
  2017. self.measurement_tool = None
  2018. self.panelize_tool = None
  2019. self.film_tool = None
  2020. self.paste_tool = None
  2021. self.calculator_tool = None
  2022. self.sub_tool = None
  2023. self.move_tool = None
  2024. self.cutout_tool = None
  2025. self.ncclear_tool = None
  2026. self.paint_tool = None
  2027. self.transform_tool = None
  2028. self.properties_tool = None
  2029. self.pdf_tool = None
  2030. self.image_tool = None
  2031. self.pcb_wizard_tool = None
  2032. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2033. self.install_tools()
  2034. # ### System Font Parsing ###
  2035. # self.f_parse = ParseFont(self)
  2036. # self.parse_system_fonts()
  2037. # #####################################################################################
  2038. # ######################## Check for updates ##########################################
  2039. # #####################################################################################
  2040. # Separate thread (Not worker)
  2041. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2042. if (self.beta is False or self.beta is None) and \
  2043. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2044. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2045. self.thr2 = QtCore.QThread()
  2046. self.worker_task.emit({'fcn': self.version_check,
  2047. 'params': []})
  2048. self.thr2.start(QtCore.QThread.LowPriority)
  2049. # #####################################################################################
  2050. # ######################### Register files with FlatCAM; #############################
  2051. # ######################### It works only for Windows for now ########################
  2052. # #####################################################################################
  2053. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2054. self.on_register_files()
  2055. # #####################################################################################
  2056. # ###################### Variables for global usage ###################################
  2057. # #####################################################################################
  2058. # coordinates for relative position display
  2059. self.rel_point1 = (0, 0)
  2060. self.rel_point2 = (0, 0)
  2061. # variable to store coordinates
  2062. self.pos = (0, 0)
  2063. self.pos_jump = (0, 0)
  2064. # variable to store mouse coordinates
  2065. self.mouse = [0, 0]
  2066. # decide if we have a double click or single click
  2067. self.doubleclick = False
  2068. # variable to store if a command is active (then the var is not None) and which one it is
  2069. self.command_active = None
  2070. # variable to store the status of moving selection action
  2071. # None value means that it's not an selection action
  2072. # True value = a selection from left to right
  2073. # False value = a selection from right to left
  2074. self.selection_type = None
  2075. # List to store the objects that are currently loaded in FlatCAM
  2076. # This list is updated on each object creation or object delete
  2077. self.all_objects_list = list()
  2078. # List to store the objects that are selected
  2079. self.sel_objects_list = list()
  2080. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2081. self.key_modifiers = None
  2082. # Variable to hold the status of the axis
  2083. self.toggle_axis = True
  2084. # Variable to store the status of the fullscreen event
  2085. self.toggle_fscreen = False
  2086. # Variable to store the status of the code editor
  2087. self.toggle_codeeditor = False
  2088. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2089. self.click_noproject = False
  2090. self.cursor = None
  2091. # Variable to store the GCODE that was edited
  2092. self.gcode_edited = ""
  2093. # reference for the self.ui.code_editor
  2094. self.reference_code_editor = None
  2095. self.script_code = ''
  2096. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2097. self.preferences_changed_flag = False
  2098. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2099. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2100. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2101. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2102. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2103. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2104. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2105. 'tap', 'xpi']
  2106. self.svg_list = ['svg']
  2107. self.dxf_list = ['dxf']
  2108. self.pdf_list = ['pdf']
  2109. self.prj_list = ['flatprj']
  2110. self.conf_list = ['flatconfig']
  2111. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2112. # flag for polygons not cleared
  2113. self.poly_not_cleared = False
  2114. # VisPy visuals
  2115. self.isHovering = False
  2116. self.notHovering = True
  2117. # Event signals disconnect id holders
  2118. self.mp = None
  2119. self.mm = None
  2120. self.mr = None
  2121. self.mp_zc = None
  2122. # when True, the app has to return from any thread
  2123. self.abort_flag = False
  2124. # set the value used in the Windows Title
  2125. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2126. # ###############################################################################
  2127. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2128. # ############# It's done only once after install ###############
  2129. # ###############################################################################
  2130. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2131. fac_def_from_file = factory_file.read()
  2132. factory_defaults = json.loads(fac_def_from_file)
  2133. # if the file contain an empty dictionary then save the factory defaults into the file
  2134. if not factory_defaults:
  2135. self.save_factory_defaults(silent=False)
  2136. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2137. initial_lay = 'compact'
  2138. self.on_layout(lay=initial_lay)
  2139. # Set the combobox in Preferences to the current layout
  2140. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2141. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2142. factory_file.close()
  2143. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2144. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2145. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2146. # after the first run, this object should be False
  2147. self.defaults["first_run"] = False
  2148. # ###############################################################################
  2149. # ################# ADDING FlatCAM EDITORS section ##############################
  2150. # ###############################################################################
  2151. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2152. # at the first launch of the App , the editors will not be functional.
  2153. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2154. self.exc_editor = FlatCAMExcEditor(self)
  2155. self.grb_editor = FlatCAMGrbEditor(self)
  2156. self.log.debug("Finished adding FlatCAM Editor's.")
  2157. self.set_ui_title(name=_("New Project - Not saved"))
  2158. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2159. current_platform = platform.architecture()[0]
  2160. if current_platform != '64bit':
  2161. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2162. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2163. # ###############################################################################
  2164. # ####################### Finished the CONSTRUCTOR ##############################
  2165. # ###############################################################################
  2166. App.log.debug("END of constructor. Releasing control.")
  2167. # #####################################################################################
  2168. # ########################## SHOW GUI #################################################
  2169. # #####################################################################################
  2170. # if the app is not started as headless, show it
  2171. if self.cmd_line_headless != 1:
  2172. # finish the splash
  2173. self.splash.finish(self.ui)
  2174. settings = QSettings("Open Source", "FlatCAM")
  2175. if settings.contains("maximized_gui"):
  2176. maximized_ui = settings.value('maximized_gui', type=bool)
  2177. if maximized_ui is True:
  2178. self.ui.showMaximized()
  2179. else:
  2180. self.ui.show()
  2181. else:
  2182. self.ui.show()
  2183. if self.defaults["global_systray_icon"]:
  2184. self.trayIcon.show()
  2185. else:
  2186. log.warning("******************* RUNNING HEADLESS *******************")
  2187. # #####################################################################################
  2188. # ########################## START-UP ARGUMENTS #######################################
  2189. # #####################################################################################
  2190. # test if the program was started with a script as parameter
  2191. if self.cmd_line_shellvar:
  2192. try:
  2193. cnt = 0
  2194. command_tcl = 0
  2195. for i in self.cmd_line_shellvar.split(','):
  2196. if i is not None:
  2197. try:
  2198. command_tcl = eval(i)
  2199. except:
  2200. command_tcl = i
  2201. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2202. cnt += 1
  2203. # if there are Windows paths then replace the path separator with a Unix like one
  2204. if sys.platform == 'win32':
  2205. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2206. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2207. except Exception as ext:
  2208. print("ERROR: ", ext)
  2209. sys.exit(2)
  2210. if self.cmd_line_shellfile:
  2211. try:
  2212. if self.ui.shell_dock.isHidden():
  2213. self.ui.shell_dock.show()
  2214. with open(self.cmd_line_shellfile, "r") as myfile:
  2215. if show_splash:
  2216. self.splash.showMessage('%s: %ssec\n%s' % (
  2217. _("Canvas initialization started.\n"
  2218. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2219. _("Executing Tcl Script ...")),
  2220. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2221. color=QtGui.QColor("gray"))
  2222. cmd_line_shellfile_text = myfile.read()
  2223. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2224. except Exception as ext:
  2225. print("ERROR: ", ext)
  2226. sys.exit(2)
  2227. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2228. # the path/file_name must be enclosed in quotes if it contain spaces
  2229. if App.args:
  2230. self.args_at_startup.emit(App.args)
  2231. @staticmethod
  2232. def copy_and_overwrite(from_path, to_path):
  2233. """
  2234. From here:
  2235. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2236. :param from_path: source path
  2237. :param to_path: destination path
  2238. :return: None
  2239. """
  2240. if os.path.exists(to_path):
  2241. shutil.rmtree(to_path)
  2242. try:
  2243. shutil.copytree(from_path, to_path)
  2244. except FileNotFoundError:
  2245. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2246. shutil.copytree(from_new_path, to_path)
  2247. def on_startup_args(self, args, silent=False):
  2248. """
  2249. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2250. :param args: a list containing the application args at startup
  2251. :return: None
  2252. """
  2253. if args is not None:
  2254. args_to_process = args
  2255. else:
  2256. args_to_process = App.args
  2257. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2258. for argument in args_to_process:
  2259. if '.FlatPrj'.lower() in argument.lower():
  2260. try:
  2261. project_name = str(argument)
  2262. if project_name == "":
  2263. if silent is False:
  2264. self.inform.emit(_("Open cancelled."))
  2265. else:
  2266. # self.open_project(project_name)
  2267. run_from_arg = True
  2268. # self.worker_task.emit({'fcn': self.open_project,
  2269. # 'params': [project_name, run_from_arg]})
  2270. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2271. except Exception as e:
  2272. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2273. elif '.FlatConfig'.lower() in argument.lower():
  2274. try:
  2275. file_name = str(argument)
  2276. if file_name == "":
  2277. if silent is False:
  2278. self.inform.emit(_("Open Config file failed."))
  2279. else:
  2280. run_from_arg = True
  2281. # self.worker_task.emit({'fcn': self.open_config_file,
  2282. # 'params': [file_name, run_from_arg]})
  2283. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2284. except Exception as e:
  2285. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2286. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2287. try:
  2288. file_name = str(argument)
  2289. if file_name == "":
  2290. if silent is False:
  2291. self.inform.emit(_("Open Script file failed."))
  2292. else:
  2293. if silent is False:
  2294. self.on_fileopenscript(name=file_name)
  2295. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2296. self.on_filerunscript(name=file_name)
  2297. except Exception as e:
  2298. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2299. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2300. log.debug("App.on_startup_args() --> Quit event.")
  2301. sys.exit()
  2302. elif 'save'.lower() in argument.lower():
  2303. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2304. self.save_defaults()
  2305. else:
  2306. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2307. proc_arg = argument.lower()
  2308. for ext in exc_list:
  2309. proc_ext = ext.replace(' ', '')
  2310. proc_ext = '.%s' % proc_ext
  2311. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2312. file_name = str(argument)
  2313. if file_name == "":
  2314. if silent is False:
  2315. self.inform.emit(_("Open Excellon file failed."))
  2316. else:
  2317. self.on_fileopenexcellon(name=file_name)
  2318. return
  2319. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2320. for ext in gco_list:
  2321. proc_ext = ext.replace(' ', '')
  2322. proc_ext = '.%s' % proc_ext
  2323. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2324. print(proc_ext, proc_arg)
  2325. file_name = str(argument)
  2326. if file_name == "":
  2327. if silent is False:
  2328. self.inform.emit(_("Open GCode file failed."))
  2329. else:
  2330. self.on_fileopengcode(name=file_name)
  2331. return
  2332. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2333. for ext in grb_list:
  2334. proc_ext = ext.replace(' ', '')
  2335. proc_ext = '.%s' % proc_ext
  2336. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2337. file_name = str(argument)
  2338. if file_name == "":
  2339. if silent is False:
  2340. self.inform.emit(_("Open Gerber file failed."))
  2341. else:
  2342. self.on_fileopengerber(name=file_name)
  2343. return
  2344. # if it reached here without already returning then the app was registered with a file that it does not
  2345. # recognize therefore we must quit
  2346. sys.exit(2)
  2347. def set_ui_title(self, name):
  2348. """
  2349. Sets the title of the main window.
  2350. :param name: String that store the project path and project name
  2351. :return: None
  2352. """
  2353. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2354. (self.version,
  2355. ('BETA' if self.beta else ''),
  2356. platform.architecture()[0],
  2357. self.engine,
  2358. name)
  2359. )
  2360. def defaults_read_form(self):
  2361. """
  2362. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2363. :return: None
  2364. """
  2365. for option in self.defaults_form_fields:
  2366. try:
  2367. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2368. except Exception as e:
  2369. log.debug("App.defaults_read_form() --> %s" % str(e))
  2370. def defaults_write_form(self, factor=None, fl_units=None):
  2371. """
  2372. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2373. self.defaults dictionary.
  2374. :param factor: will apply a factor to the values that written in the GUI elements
  2375. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2376. :return: None
  2377. """
  2378. for option in self.defaults:
  2379. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2380. # try:
  2381. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2382. # except KeyError:
  2383. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2384. # # TODO: Rethink this?
  2385. # pass
  2386. def defaults_write_form_field(self, field, factor=None, units=None):
  2387. """
  2388. Basically it is the worker in the self.defaults_write_form()
  2389. :param field: the GUI element in Preferences GUI to be updated
  2390. :param factor: factor to be applied to the field parameter
  2391. :param units: current FLatCAM measuring units
  2392. :return: None, it updates GUI elements
  2393. """
  2394. try:
  2395. if factor is None:
  2396. if units is None:
  2397. self.defaults_form_fields[field].set_value(self.defaults[field])
  2398. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2399. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2400. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2401. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2402. else:
  2403. if units is None:
  2404. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2405. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2406. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2407. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2408. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2409. except KeyError:
  2410. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2411. # TODO: Rethink this?
  2412. pass
  2413. except AttributeError:
  2414. log.debug(field)
  2415. def clear_pool(self):
  2416. """
  2417. Clear the multiprocessing pool and calls garbage collector.
  2418. :return: None
  2419. """
  2420. self.pool.close()
  2421. self.pool = Pool()
  2422. self.pool_recreated.emit(self.pool)
  2423. gc.collect()
  2424. def install_tools(self):
  2425. """
  2426. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2427. Instantiation of the Tools classes.
  2428. The order that the tools are installed is important as they can depend on each other install position.
  2429. :return: None
  2430. """
  2431. self.dblsidedtool = DblSidedTool(self)
  2432. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2433. self.measurement_tool = Measurement(self)
  2434. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2435. self.panelize_tool = Panelize(self)
  2436. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2437. self.film_tool = Film(self)
  2438. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2439. self.paste_tool = SolderPaste(self)
  2440. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2441. self.calculator_tool = ToolCalculator(self)
  2442. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2443. self.sub_tool = ToolSub(self)
  2444. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2445. self.move_tool = ToolMove(self)
  2446. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2447. before=self.ui.menueditorigin)
  2448. self.cutout_tool = CutOut(self)
  2449. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2450. before=self.measurement_tool.menuAction)
  2451. self.ncclear_tool = NonCopperClear(self)
  2452. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2453. before=self.measurement_tool.menuAction, separator=True)
  2454. self.paint_tool = ToolPaint(self)
  2455. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2456. before=self.measurement_tool.menuAction, separator=True)
  2457. self.transform_tool = ToolTransform(self)
  2458. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2459. self.properties_tool = Properties(self)
  2460. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2461. self.pdf_tool = ToolPDF(self)
  2462. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2463. separator=True)
  2464. self.image_tool = ToolImage(self)
  2465. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2466. separator=True)
  2467. self.pcb_wizard_tool = PcbWizard(self)
  2468. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2469. self.log.debug("Tools are installed.")
  2470. def remove_tools(self):
  2471. """
  2472. Will remove all the actions in the Tool menu.
  2473. :return: None
  2474. """
  2475. for act in self.ui.menutool.actions():
  2476. self.ui.menutool.removeAction(act)
  2477. def init_tools(self):
  2478. """
  2479. Initialize the Tool tab in the notebook side of the central widget.
  2480. Remove the actions in the Tools menu.
  2481. Instantiate again the FlatCAM tools (plugins).
  2482. All this is required when changing the layout: standard, compact etc.
  2483. :return: None
  2484. """
  2485. log.debug("init_tools()")
  2486. # delete the data currently in the Tools Tab and the Tab itself
  2487. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2488. if widget is not None:
  2489. widget.deleteLater()
  2490. self.ui.notebook.removeTab(2)
  2491. # rebuild the Tools Tab
  2492. self.ui.tool_tab = QtWidgets.QWidget()
  2493. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2494. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2495. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2496. self.ui.tool_scroll_area = VerticalScrollArea()
  2497. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2498. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2499. # first remove all of them
  2500. self.remove_tools()
  2501. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2502. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2503. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2504. # third install all of them
  2505. self.install_tools()
  2506. self.log.debug("Tools are initialized.")
  2507. # def parse_system_fonts(self):
  2508. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2509. # 'params': []})
  2510. def connect_toolbar_signals(self):
  2511. """
  2512. Reconnect the signals to the actions in the toolbar.
  2513. This has to be done each time after the FlatCAM tools are removed/installed.
  2514. :return: None
  2515. """
  2516. # Toolbar
  2517. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2518. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2519. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2520. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2521. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2522. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2523. self.ui.replot_btn.triggered.connect(self.plot_all)
  2524. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2525. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2526. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2527. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2528. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2529. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2530. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2531. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2532. self.ui.delete_btn.triggered.connect(self.on_delete)
  2533. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2534. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2535. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2536. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2537. # Tools Toolbar Signals
  2538. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2539. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2540. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2541. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2542. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2543. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2544. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2545. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2546. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2547. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2548. def object2editor(self):
  2549. """
  2550. Send the current Geometry or Excellon object (if any) into the it's editor.
  2551. :return: None
  2552. """
  2553. self.report_usage("object2editor()")
  2554. edited_object = self.collection.get_active()
  2555. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2556. isinstance(edited_object, FlatCAMExcellon):
  2557. pass
  2558. else:
  2559. self.inform.emit('[WARNING_NOTCL] %s' %
  2560. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2561. return
  2562. if isinstance(edited_object, FlatCAMGeometry):
  2563. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2564. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2565. # we set the notebook to hidden
  2566. self.ui.splitter.setSizes([0, 1])
  2567. if edited_object.multigeo is True:
  2568. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2569. if len(edited_tools) > 1:
  2570. self.inform.emit('[WARNING_NOTCL] %s' %
  2571. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2572. "is not possible.\n"
  2573. "Edit only one geometry at a time."))
  2574. # determine the tool dia of the selected tool
  2575. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2576. # now find the key in the edited_object.tools that has this tooldia
  2577. multi_tool = 1
  2578. for tool in edited_object.tools:
  2579. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2580. multi_tool = tool
  2581. break
  2582. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2583. else:
  2584. self.geo_editor.edit_fcgeometry(edited_object)
  2585. # set call source to the Editor we go into
  2586. self.call_source = 'geo_editor'
  2587. elif isinstance(edited_object, FlatCAMExcellon):
  2588. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2589. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2590. if self.ui.splitter.sizes()[0] == 0:
  2591. self.ui.splitter.setSizes([1, 1])
  2592. self.exc_editor.edit_fcexcellon(edited_object)
  2593. # set call source to the Editor we go into
  2594. self.call_source = 'exc_editor'
  2595. elif isinstance(edited_object, FlatCAMGerber):
  2596. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2597. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2598. if self.ui.splitter.sizes()[0] == 0:
  2599. self.ui.splitter.setSizes([1, 1])
  2600. self.grb_editor.edit_fcgerber(edited_object)
  2601. # set call source to the Editor we go into
  2602. self.call_source = 'grb_editor'
  2603. # make sure that we can't select another object while in Editor Mode:
  2604. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2605. self.ui.project_frame.setDisabled(True)
  2606. # delete any selection shape that might be active as they are not relevant in Editor
  2607. self.delete_selection_shape()
  2608. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2609. self.ui.plot_tab_area.protectTab(0)
  2610. self.inform.emit('[WARNING_NOTCL] %s' %
  2611. _("Editor is activated ..."))
  2612. self.should_we_save = True
  2613. def editor2object(self, cleanup=None):
  2614. """
  2615. Transfers the Geometry or Excellon from it's editor to the current object.
  2616. :return: None
  2617. """
  2618. self.report_usage("editor2object()")
  2619. # do not update a geometry or excellon object unless it comes out of an editor
  2620. if self.call_source != 'app':
  2621. edited_obj = self.collection.get_active()
  2622. if cleanup is None:
  2623. msgbox = QtWidgets.QMessageBox()
  2624. msgbox.setText(_("Do you want to save the edited object?"))
  2625. msgbox.setWindowTitle(_("Close Editor"))
  2626. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2627. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2628. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2629. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2630. msgbox.setDefaultButton(bt_yes)
  2631. msgbox.exec_()
  2632. response = msgbox.clickedButton()
  2633. if response == bt_yes:
  2634. # clean the Tools Tab
  2635. self.ui.tool_scroll_area.takeWidget()
  2636. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2637. self.ui.notebook.setTabText(2, "Tool")
  2638. if isinstance(edited_obj, FlatCAMGeometry):
  2639. obj_type = "Geometry"
  2640. if cleanup is None:
  2641. self.geo_editor.update_fcgeometry(edited_obj)
  2642. self.geo_editor.update_options(edited_obj)
  2643. self.geo_editor.deactivate()
  2644. # update the geo object options so it is including the bounding box values
  2645. try:
  2646. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2647. edited_obj.options['xmin'] = xmin
  2648. edited_obj.options['ymin'] = ymin
  2649. edited_obj.options['xmax'] = xmax
  2650. edited_obj.options['ymax'] = ymax
  2651. except AttributeError as e:
  2652. self.inform.emit('[WARNING] %s' %
  2653. _("Object empty after edit."))
  2654. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2655. elif isinstance(edited_obj, FlatCAMGerber):
  2656. obj_type = "Gerber"
  2657. if cleanup is None:
  2658. self.grb_editor.update_fcgerber()
  2659. self.grb_editor.update_options(edited_obj)
  2660. self.grb_editor.deactivate_grb_editor()
  2661. # delete the old object (the source object) if it was an empty one
  2662. if len(edited_obj.solid_geometry) == 0:
  2663. old_name = edited_obj.options['name']
  2664. self.collection.set_active(old_name)
  2665. self.collection.delete_active()
  2666. # restore GUI to the Selected TAB
  2667. # Remove anything else in the GUI
  2668. self.ui.selected_scroll_area.takeWidget()
  2669. # Switch notebook to Selected page
  2670. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2671. elif isinstance(edited_obj, FlatCAMExcellon):
  2672. obj_type = "Excellon"
  2673. if cleanup is None:
  2674. self.exc_editor.update_fcexcellon(edited_obj)
  2675. self.exc_editor.update_options(edited_obj)
  2676. self.exc_editor.deactivate()
  2677. # delete the old object (the source object) if it was an empty one
  2678. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2679. old_name = edited_obj.options['name']
  2680. self.collection.set_active(old_name)
  2681. self.collection.delete_active()
  2682. # restore GUI to the Selected TAB
  2683. # Remove anything else in the GUI
  2684. self.ui.tool_scroll_area.takeWidget()
  2685. # Switch notebook to Selected page
  2686. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2687. else:
  2688. self.inform.emit('[WARNING_NOTCL] %s' %
  2689. _("Select a Gerber, Geometry or Excellon Object to update."))
  2690. return
  2691. self.inform.emit('[selected] %s %s' %
  2692. (obj_type, _("is updated, returning to App...")))
  2693. elif response == bt_no:
  2694. # clean the Tools Tab
  2695. self.ui.tool_scroll_area.takeWidget()
  2696. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2697. self.ui.notebook.setTabText(2, "Tool")
  2698. if isinstance(edited_obj, FlatCAMGeometry):
  2699. self.geo_editor.deactivate()
  2700. elif isinstance(edited_obj, FlatCAMGerber):
  2701. self.grb_editor.deactivate_grb_editor()
  2702. elif isinstance(edited_obj, FlatCAMExcellon):
  2703. self.exc_editor.deactivate()
  2704. # set focus on the project tab
  2705. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2706. else:
  2707. self.inform.emit('[WARNING_NOTCL] %s' %
  2708. _("Select a Gerber, Geometry or Excellon Object to update."))
  2709. return
  2710. elif response == bt_cancel:
  2711. return
  2712. else:
  2713. if isinstance(edited_obj, FlatCAMGeometry):
  2714. self.geo_editor.deactivate()
  2715. elif isinstance(edited_obj, FlatCAMGerber):
  2716. self.grb_editor.deactivate_grb_editor()
  2717. elif isinstance(edited_obj, FlatCAMExcellon):
  2718. self.exc_editor.deactivate()
  2719. else:
  2720. self.inform.emit('[WARNING_NOTCL] %s' %
  2721. _("Select a Gerber, Geometry or Excellon Object to update."))
  2722. return
  2723. # if notebook is hidden we show it
  2724. if self.ui.splitter.sizes()[0] == 0:
  2725. self.ui.splitter.setSizes([1, 1])
  2726. # restore the call_source to app
  2727. self.call_source = 'app'
  2728. edited_obj.plot()
  2729. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2730. self.ui.plot_tab_area.protectTab(0)
  2731. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2732. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2733. self.ui.project_frame.setDisabled(False)
  2734. def get_last_folder(self):
  2735. """
  2736. Get the folder path from where the last file was opened.
  2737. :return: String, last opened folder path
  2738. """
  2739. return self.defaults["global_last_folder"]
  2740. def get_last_save_folder(self):
  2741. """
  2742. Get the folder path from where the last file was saved.
  2743. :return: String, last saved folder path
  2744. """
  2745. loc = self.defaults["global_last_save_folder"]
  2746. if loc is None:
  2747. loc = self.defaults["global_last_folder"]
  2748. if loc is None:
  2749. loc = os.path.dirname(__file__)
  2750. return loc
  2751. def report_usage(self, resource):
  2752. """
  2753. Increments usage counter for the given resource
  2754. in self.defaults['global_stats'].
  2755. :param resource: Name of the resource.
  2756. :return: None
  2757. """
  2758. if resource in self.defaults['global_stats']:
  2759. self.defaults['global_stats'][resource] += 1
  2760. else:
  2761. self.defaults['global_stats'][resource] = 1
  2762. def init_tcl(self):
  2763. """
  2764. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2765. :return: None
  2766. """
  2767. if hasattr(self, 'tcl'):
  2768. # self.tcl = None
  2769. # TODO we need to clean non default variables and procedures here
  2770. # new object cannot be used here as it will not remember values created for next passes,
  2771. # because tcl was execudted in old instance of TCL
  2772. pass
  2773. else:
  2774. self.tcl = tk.Tcl()
  2775. self.setup_shell()
  2776. self.log.debug("TCL Shell has been initialized.")
  2777. # TODO: This shouldn't be here.
  2778. class TclErrorException(Exception):
  2779. """
  2780. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2781. """
  2782. pass
  2783. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2784. """
  2785. Shows a message on the FlatCAM Shell
  2786. :param msg: Message to display.
  2787. :param show: Opens the shell.
  2788. :param error: Shows the message as an error.
  2789. :param warning: Shows the message as an warning.
  2790. :param success: Shows the message as an success.
  2791. :param selected: Indicate that something was selected on canvas
  2792. :return: None
  2793. """
  2794. if show:
  2795. self.ui.shell_dock.show()
  2796. try:
  2797. if error:
  2798. self.shell.append_error(msg + "\n")
  2799. elif warning:
  2800. self.shell.append_warning(msg + "\n")
  2801. elif success:
  2802. self.shell.append_success(msg + "\n")
  2803. elif selected:
  2804. self.shell.append_selected(msg + "\n")
  2805. else:
  2806. self.shell.append_output(msg + "\n")
  2807. except AttributeError:
  2808. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2809. def raise_tcl_unknown_error(self, unknownException):
  2810. """
  2811. Raise exception if is different type than TclErrorException
  2812. this is here mainly to show unknown errors inside TCL shell console.
  2813. :param unknownException:
  2814. :return:
  2815. """
  2816. if not isinstance(unknownException, self.TclErrorException):
  2817. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2818. else:
  2819. raise unknownException
  2820. def display_tcl_error(self, error, error_info=None):
  2821. """
  2822. Escape bracket [ with '\' otherwise there is error
  2823. "ERROR: missing close-bracket" instead of real error
  2824. :param error: it may be text or exception
  2825. :param error_info: Some informations about the error
  2826. :return: None
  2827. """
  2828. if isinstance(error, Exception):
  2829. exc_type, exc_value, exc_traceback = error_info
  2830. if not isinstance(error, self.TclErrorException):
  2831. show_trace = 1
  2832. else:
  2833. show_trace = int(self.defaults['global_verbose_error_level'])
  2834. if show_trace > 0:
  2835. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2836. trc_formated = []
  2837. for a in reversed(trc):
  2838. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2839. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2840. else:
  2841. text = "%s" % error
  2842. else:
  2843. text = error
  2844. text = text.replace('[', '\\[').replace('"', '\\"')
  2845. self.tcl.eval('return -code error "%s"' % text)
  2846. def raise_tcl_error(self, text):
  2847. """
  2848. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2849. :param text: text of error
  2850. :return: raise exception
  2851. """
  2852. self.display_tcl_error(text)
  2853. raise self.TclErrorException(text)
  2854. def exec_command(self, text, no_echo=False):
  2855. """
  2856. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2857. Also handles execution in separated threads
  2858. :param text: FlatCAM TclCommand with parameters
  2859. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2860. will create crashes of the _Expandable_Edit widget
  2861. :return: output if there was any
  2862. """
  2863. self.report_usage('exec_command')
  2864. result = self.exec_command_test(text, False, no_echo=no_echo)
  2865. # MS: added this method call so the geometry is updated once the TCL command is executed
  2866. # if no_plot is None:
  2867. # self.plot_all()
  2868. return result
  2869. def exec_command_test(self, text, reraise=True, no_echo=False):
  2870. """
  2871. Same as exec_command(...) with additional control over exceptions.
  2872. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2873. :param text: Input command
  2874. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2875. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2876. will create crashes of the _Expandable_Edit widget
  2877. :return: Output from the command
  2878. """
  2879. tcl_command_string = str(text)
  2880. try:
  2881. if no_echo is False:
  2882. self.shell.open_proccessing() # Disables input box.
  2883. result = self.tcl.eval(str(tcl_command_string))
  2884. if result != 'None' and no_echo is False:
  2885. self.shell.append_output(result + '\n')
  2886. except tk.TclError as e:
  2887. # This will display more precise answer if something in TCL shell fails
  2888. result = self.tcl.eval("set errorInfo")
  2889. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2890. if no_echo is False:
  2891. self.shell.append_error('ERROR: ' + result + '\n')
  2892. # Show error in console and just return or in test raise exception
  2893. if reraise:
  2894. raise e
  2895. finally:
  2896. if no_echo is False:
  2897. self.shell.close_proccessing()
  2898. pass
  2899. return result
  2900. # """
  2901. # Code below is unsused. Saved for later.
  2902. # """
  2903. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2904. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2905. # self.log.debug(parts)
  2906. # try:
  2907. # if parts[0] not in commands:
  2908. # self.shell.append_error("Unknown command\n")
  2909. # return
  2910. #
  2911. # #import inspect
  2912. # #inspect.getargspec(someMethod)
  2913. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2914. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2915. # self.shell.append_error(
  2916. # "Command %s takes %d arguments. %d given.\n" %
  2917. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2918. # )
  2919. # return
  2920. #
  2921. # cmdfcn = commands[parts[0]]["fcn"]
  2922. # cmdconv = commands[parts[0]]["converters"]
  2923. # if len(parts) - 1 > 0:
  2924. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2925. # else:
  2926. # retval = cmdfcn()
  2927. # retfcn = commands[parts[0]]["retfcn"]
  2928. # if retval and retfcn(retval):
  2929. # self.shell.append_output(retfcn(retval) + "\n")
  2930. #
  2931. # except Exception as e:
  2932. # #self.shell.append_error(''.join(traceback.format_exc()))
  2933. # #self.shell.append_error("?\n")
  2934. # self.shell.append_error(str(e) + "\n")
  2935. def info(self, msg):
  2936. """
  2937. Informs the user. Normally on the status bar, optionally
  2938. also on the shell.
  2939. :param msg: Text to write.
  2940. :return: None
  2941. """
  2942. # Type of message in brackets at the beginning of the message.
  2943. match = re.search("\[([^\]]+)\](.*)", msg)
  2944. if match:
  2945. level = match.group(1)
  2946. msg_ = match.group(2)
  2947. self.ui.fcinfo.set_status(str(msg_), level=level)
  2948. if level.lower() == "error":
  2949. self.shell_message(msg, error=True, show=True)
  2950. elif level.lower() == "warning":
  2951. self.shell_message(msg, warning=True, show=True)
  2952. elif level.lower() == "error_notcl":
  2953. self.shell_message(msg, error=True, show=False)
  2954. elif level.lower() == "warning_notcl":
  2955. self.shell_message(msg, warning=True, show=False)
  2956. elif level.lower() == "success":
  2957. self.shell_message(msg, success=True, show=False)
  2958. elif level.lower() == "selected":
  2959. self.shell_message(msg, selected=True, show=False)
  2960. else:
  2961. self.shell_message(msg, show=False)
  2962. else:
  2963. self.ui.fcinfo.set_status(str(msg), level="info")
  2964. # make sure that if the message is to clear the infobar with a space
  2965. # is not printed over and over on the shell
  2966. if msg != '':
  2967. self.shell_message(msg)
  2968. def restore_toolbar_view(self):
  2969. """
  2970. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2971. was saved in the defaults dictionary.
  2972. :return: None
  2973. """
  2974. tb = self.defaults["global_toolbar_view"]
  2975. if tb & 1:
  2976. self.ui.toolbarfile.setVisible(True)
  2977. else:
  2978. self.ui.toolbarfile.setVisible(False)
  2979. if tb & 2:
  2980. self.ui.toolbargeo.setVisible(True)
  2981. else:
  2982. self.ui.toolbargeo.setVisible(False)
  2983. if tb & 4:
  2984. self.ui.toolbarview.setVisible(True)
  2985. else:
  2986. self.ui.toolbarview.setVisible(False)
  2987. if tb & 8:
  2988. self.ui.toolbartools.setVisible(True)
  2989. else:
  2990. self.ui.toolbartools.setVisible(False)
  2991. if tb & 16:
  2992. self.ui.exc_edit_toolbar.setVisible(True)
  2993. else:
  2994. self.ui.exc_edit_toolbar.setVisible(False)
  2995. if tb & 32:
  2996. self.ui.geo_edit_toolbar.setVisible(True)
  2997. else:
  2998. self.ui.geo_edit_toolbar.setVisible(False)
  2999. if tb & 64:
  3000. self.ui.grb_edit_toolbar.setVisible(True)
  3001. else:
  3002. self.ui.grb_edit_toolbar.setVisible(False)
  3003. if tb & 128:
  3004. self.ui.snap_toolbar.setVisible(True)
  3005. else:
  3006. self.ui.snap_toolbar.setVisible(False)
  3007. if tb & 256:
  3008. self.ui.toolbarshell.setVisible(True)
  3009. else:
  3010. self.ui.toolbarshell.setVisible(False)
  3011. def load_defaults(self, filename):
  3012. """
  3013. Loads the aplication's default settings from current_defaults.FlatConfig into
  3014. ``self.defaults``.
  3015. :return: None
  3016. """
  3017. try:
  3018. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3019. options = f.read()
  3020. f.close()
  3021. except IOError:
  3022. self.log.error("Could not load defaults file.")
  3023. self.inform.emit('[ERROR] %s' %
  3024. _("Could not load defaults file."))
  3025. # in case the defaults file can't be loaded, show all toolbars
  3026. self.defaults["global_toolbar_view"] = 511
  3027. return
  3028. try:
  3029. defaults = json.loads(options)
  3030. except:
  3031. # in case the defaults file can't be loaded, show all toolbars
  3032. self.defaults["global_toolbar_view"] = 511
  3033. e = sys.exc_info()[0]
  3034. App.log.error(str(e))
  3035. self.inform.emit('[ERROR] %s' %
  3036. _("Failed to parse defaults file."))
  3037. return
  3038. self.defaults.update(defaults)
  3039. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3040. # restore the toolbar view
  3041. self.restore_toolbar_view()
  3042. def on_import_preferences(self):
  3043. """
  3044. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3045. ``self.defaults``.
  3046. :return: None
  3047. """
  3048. self.report_usage("on_import_preferences")
  3049. App.log.debug("on_import_preferences()")
  3050. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3051. try:
  3052. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3053. directory=self.data_path,
  3054. filter=filter_)
  3055. except TypeError:
  3056. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3057. filter=filter_)
  3058. filename = str(filename)
  3059. if filename == "":
  3060. self.inform.emit('[WARNING_NOTCL] %s' %
  3061. _("FlatCAM preferences import cancelled."))
  3062. else:
  3063. try:
  3064. f = open(filename)
  3065. options = f.read()
  3066. f.close()
  3067. except IOError:
  3068. self.log.error("Could not load defaults file.")
  3069. self.inform.emit('[ERROR_NOTCL] %s' %
  3070. _("Could not load defaults file."))
  3071. return
  3072. try:
  3073. defaults_from_file = json.loads(options)
  3074. except Exception as e:
  3075. e = sys.exc_info()[0]
  3076. App.log.error(str(e))
  3077. self.inform.emit('[ERROR_NOTCL] %s' %
  3078. _("Failed to parse defaults file."))
  3079. return
  3080. self.defaults.update(defaults_from_file)
  3081. self.on_preferences_edited()
  3082. self.inform.emit('[success] %s: %s' %
  3083. (_("Imported Defaults from"), filename))
  3084. def on_export_preferences(self):
  3085. """
  3086. Save the defaults dictionary to a file.
  3087. :return: None
  3088. """
  3089. self.report_usage("on_export_preferences")
  3090. App.log.debug("on_export_preferences()")
  3091. defaults_file_content = None
  3092. self.date = str(datetime.today()).rpartition('.')[0]
  3093. self.date = ''.join(c for c in self.date if c not in ':-')
  3094. self.date = self.date.replace(' ', '_')
  3095. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3096. try:
  3097. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3098. caption=_("Export FlatCAM Preferences"),
  3099. directory=self.data_path + '/preferences_' + self.date,
  3100. filter=filter__
  3101. )
  3102. except TypeError:
  3103. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3104. filter=filter__)
  3105. filename = str(filename)
  3106. defaults_from_file = {}
  3107. if filename == "":
  3108. self.inform.emit('[WARNING_NOTCL] %s' %
  3109. _("FlatCAM preferences export cancelled."))
  3110. return
  3111. else:
  3112. try:
  3113. f = open(filename, 'w')
  3114. defaults_file_content = f.read()
  3115. f.close()
  3116. except PermissionError:
  3117. self.inform.emit('[WARNING] %s' %
  3118. _("Permission denied, saving not possible.\n"
  3119. "Most likely another app is holding the file open and not accessible."))
  3120. return
  3121. except IOError:
  3122. App.log.debug('Creating a new preferences file ...')
  3123. f = open(filename, 'w')
  3124. json.dump({}, f)
  3125. f.close()
  3126. except:
  3127. e = sys.exc_info()[0]
  3128. App.log.error("Could not load defaults file.")
  3129. App.log.error(str(e))
  3130. self.inform.emit('[ERROR_NOTCL] %s' %
  3131. _("Could not load preferences file."))
  3132. return
  3133. try:
  3134. defaults_from_file = json.loads(defaults_file_content)
  3135. except:
  3136. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3137. # Update options
  3138. self.defaults_read_form()
  3139. defaults_from_file.update(self.defaults)
  3140. self.propagate_defaults(silent=True)
  3141. # Save update options
  3142. try:
  3143. f = open(filename, "w")
  3144. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3145. f.close()
  3146. except:
  3147. self.inform.emit('[ERROR_NOTCL] %s' %
  3148. _("Failed to write defaults to file."))
  3149. return
  3150. if self.defaults["global_open_style"] is False:
  3151. self.file_opened.emit("preferences", filename)
  3152. self.file_saved.emit("preferences", filename)
  3153. self.inform.emit('[success] %s: %s' %
  3154. (_("Exported preferences to"), filename))
  3155. def on_preferences_open_folder(self):
  3156. """
  3157. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3158. :return: None
  3159. """
  3160. self.report_usage("on_preferences_open_folder()")
  3161. if sys.platform == 'win32':
  3162. subprocess.Popen('explorer %s' % self.data_path)
  3163. elif sys.platform == 'darwin':
  3164. os.system('open "%s"' % self.data_path)
  3165. else:
  3166. subprocess.Popen(['xdg-open', self.data_path])
  3167. self.inform.emit('[success] %s' %
  3168. _("FlatCAM Preferences Folder opened."))
  3169. def save_geometry(self, x, y, width, height, notebook_width):
  3170. """
  3171. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3172. launch of the application.
  3173. :param x: X position of the main window
  3174. :param y: Y position of the main window
  3175. :param width: width of the main window
  3176. :param height: height of the main window
  3177. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3178. :return: None
  3179. """
  3180. self.defaults["global_def_win_x"] = x
  3181. self.defaults["global_def_win_y"] = y
  3182. self.defaults["global_def_win_w"] = width
  3183. self.defaults["global_def_win_h"] = height
  3184. self.defaults["global_def_notebook_width"] = notebook_width
  3185. self.save_defaults()
  3186. def message_dialog(self, title, message, kind="info"):
  3187. """
  3188. Builds and show a custom QMessageBox to be used in FlatCAM.
  3189. :param title: title of the QMessageBox
  3190. :param message: message to be displayed
  3191. :param kind: type of QMessageBox; will display a specific icon.
  3192. :return:
  3193. """
  3194. icon = {"info": QtWidgets.QMessageBox.Information,
  3195. "warning": QtWidgets.QMessageBox.Warning,
  3196. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3197. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3198. dlg.setText(message)
  3199. dlg.exec_()
  3200. def register_recent(self, kind, filename):
  3201. """
  3202. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3203. dictionary.
  3204. :param kind: type of file that was opened
  3205. :param filename: the path and file name for the file that was opened
  3206. :return:
  3207. """
  3208. self.log.debug("register_recent()")
  3209. self.log.debug(" %s" % kind)
  3210. self.log.debug(" %s" % filename)
  3211. record = {'kind': str(kind), 'filename': str(filename)}
  3212. if record in self.recent:
  3213. return
  3214. if record in self.recent_projects:
  3215. return
  3216. if record['kind'] == 'project':
  3217. self.recent_projects.insert(0, record)
  3218. else:
  3219. self.recent.insert(0, record)
  3220. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3221. self.recent.pop()
  3222. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3223. self.recent_projects.pop()
  3224. try:
  3225. f = open(self.data_path + '/recent.json', 'w')
  3226. except IOError:
  3227. App.log.error("Failed to open recent items file for writing.")
  3228. self.inform.emit('[ERROR_NOTCL] %s' %
  3229. _('Failed to open recent files file for writing.'))
  3230. return
  3231. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3232. f.close()
  3233. try:
  3234. fp = open(self.data_path + '/recent_projects.json', 'w')
  3235. except IOError:
  3236. App.log.error("Failed to open recent items file for writing.")
  3237. self.inform.emit('[ERROR_NOTCL] %s' %
  3238. _('Failed to open recent projects file for writing.'))
  3239. return
  3240. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3241. fp.close()
  3242. # Re-build the recent items menu
  3243. self.setup_recent_items()
  3244. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3245. """
  3246. Creates a new specialized FlatCAMObj and attaches it to the application,
  3247. this is, updates the GUI accordingly, any other records and plots it.
  3248. This method is thread-safe.
  3249. Notes:
  3250. * If the name is in use, the self.collection will modify it
  3251. when appending it to the collection. There is no need to handle
  3252. name conflicts here.
  3253. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3254. :type kind: str
  3255. :param name: Name for the object.
  3256. :type name: str
  3257. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3258. The function is called with 2 parameters: the new object and the App instance.
  3259. :type initialize: function
  3260. :param active:
  3261. :param fit:
  3262. :param plot: If to plot the resulting object
  3263. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3264. self.colleaction
  3265. :return: None
  3266. :rtype: None
  3267. """
  3268. App.log.debug("new_object()")
  3269. obj_plot = plot
  3270. obj_autoselected = autoselected
  3271. t0 = time.time() # Debug
  3272. # ## Create object
  3273. classdict = {
  3274. "gerber": FlatCAMGerber,
  3275. "excellon": FlatCAMExcellon,
  3276. "cncjob": FlatCAMCNCjob,
  3277. "geometry": FlatCAMGeometry
  3278. }
  3279. App.log.debug("Calling object constructor...")
  3280. obj = classdict[kind](name)
  3281. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3282. # Set options from "Project options" form
  3283. self.options_read_form()
  3284. # IMPORTANT
  3285. # The key names in defaults and options dictionary's are not random:
  3286. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3287. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3288. # the options from project options form into the self.options. After that, below, depending on the type of
  3289. # object that is created, it will strip the name of the object and the underline (if the original key was
  3290. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3291. # "toolchange"
  3292. for option in self.options:
  3293. if option.find(kind + "_") == 0:
  3294. oname = option[len(kind) + 1:]
  3295. obj.options[oname] = self.options[option]
  3296. obj.isHovering = False
  3297. obj.notHovering = True
  3298. # Initialize as per user request
  3299. # User must take care to implement initialize
  3300. # in a thread-safe way as is is likely that we
  3301. # have been invoked in a separate thread.
  3302. t1 = time.time()
  3303. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3304. try:
  3305. return_value = initialize(obj, self)
  3306. except Exception as e:
  3307. msg = '[ERROR_NOTCL] %s' % \
  3308. _("An internal error has ocurred. See shell.\n")
  3309. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3310. msg += traceback.format_exc()
  3311. self.inform.emit(msg)
  3312. # if str(e) == "Empty Geometry":
  3313. # self.inform.emit("[ERROR_NOTCL] )
  3314. # else:
  3315. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3316. return "fail"
  3317. t2 = time.time()
  3318. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3319. if return_value == 'fail':
  3320. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3321. return "fail"
  3322. # Check units and convert if necessary
  3323. # This condition CAN be true because initialize() can change obj.units
  3324. if self.options["units"].upper() != obj.units.upper():
  3325. self.inform.emit('%s: %s' %
  3326. (_("Converting units to "), self.options["units"]))
  3327. obj.convert_units(self.options["units"])
  3328. t3 = time.time()
  3329. self.log.debug("%f seconds converting units." % (t3 - t2))
  3330. # Create the bounding box for the object and then add the results to the obj.options
  3331. try:
  3332. xmin, ymin, xmax, ymax = obj.bounds()
  3333. obj.options['xmin'] = xmin
  3334. obj.options['ymin'] = ymin
  3335. obj.options['xmax'] = xmax
  3336. obj.options['ymax'] = ymax
  3337. except Exception as e:
  3338. log.warning("The object has no bounds properties. %s" % str(e))
  3339. return "fail"
  3340. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3341. # Move the object to the main thread and let the app know that it is available.
  3342. obj.moveToThread(self.main_thread)
  3343. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3344. return obj
  3345. def new_excellon_object(self):
  3346. """
  3347. Creates a new, blank Excellon object.
  3348. :return: None
  3349. """
  3350. self.report_usage("new_excellon_object()")
  3351. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3352. def new_geometry_object(self):
  3353. """
  3354. Creates a new, blank and single-tool Geometry object.
  3355. :return: None
  3356. """
  3357. self.report_usage("new_geometry_object()")
  3358. def initialize(obj, self):
  3359. obj.multitool = False
  3360. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3361. def new_gerber_object(self):
  3362. """
  3363. Creates a new, blank Gerber object.
  3364. :return: None
  3365. """
  3366. self.report_usage("new_gerber_object()")
  3367. def initialize(grb_obj, self):
  3368. grb_obj.multitool = False
  3369. grb_obj.source_file = []
  3370. grb_obj.multigeo = False
  3371. grb_obj.follow = False
  3372. grb_obj.apertures = {}
  3373. grb_obj.solid_geometry = []
  3374. try:
  3375. grb_obj.options['xmin'] = 0
  3376. grb_obj.options['ymin'] = 0
  3377. grb_obj.options['xmax'] = 0
  3378. grb_obj.options['ymax'] = 0
  3379. except KeyError:
  3380. pass
  3381. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3382. def on_object_created(self, obj, plot, autoselect):
  3383. """
  3384. Event callback for object creation.
  3385. It will add the new object to the collection. After that it will plot the object in a threaded way
  3386. :param obj: The newly created FlatCAM object.
  3387. :param plot: if the newly create object t obe plotted
  3388. :param autoselect: if the newly created object to be autoselected after creation
  3389. :return: None
  3390. """
  3391. t0 = time.time() # DEBUG
  3392. self.log.debug("on_object_created()")
  3393. # The Collection might change the name if there is a collision
  3394. self.collection.append(obj)
  3395. # after adding the object to the collection always update the list of objects that are in the collection
  3396. self.all_objects_list = self.collection.get_list()
  3397. # self.inform.emit('[selected] %s created & selected: %s' %
  3398. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3399. if obj.kind == 'gerber':
  3400. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3401. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3402. elif obj.kind == 'excellon':
  3403. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3404. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3405. elif obj.kind == 'cncjob':
  3406. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3407. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3408. elif obj.kind == 'geometry':
  3409. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3410. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3411. # update the SHELL auto-completer model with the name of the new object
  3412. self.myKeywords.append(obj.options['name'])
  3413. self.shell._edit.set_model_data(self.myKeywords)
  3414. self.ui.code_editor.set_model_data(self.myKeywords)
  3415. if autoselect:
  3416. # select the just opened object but deselect the previous ones
  3417. self.collection.set_all_inactive()
  3418. self.collection.set_active(obj.options["name"])
  3419. else:
  3420. self.collection.set_all_inactive()
  3421. # here it is done the object plotting
  3422. def worker_task(t_obj):
  3423. with self.proc_container.new(_("Plotting")):
  3424. if isinstance(t_obj, FlatCAMCNCjob):
  3425. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3426. else:
  3427. t_obj.plot()
  3428. t1 = time.time() # DEBUG
  3429. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3430. self.object_plotted.emit(t_obj)
  3431. # Send to worker
  3432. # self.worker.add_task(worker_task, [self])
  3433. if plot is True:
  3434. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3435. def on_object_changed(self, obj):
  3436. """
  3437. Called whenever the geometry of the object was changed in some way.
  3438. This require the update of it's bounding values so it can be the selected on canvas.
  3439. Update the bounding box data from obj.options
  3440. :param obj: the object that was changed
  3441. :return: None
  3442. """
  3443. xmin, ymin, xmax, ymax = obj.bounds()
  3444. obj.options['xmin'] = xmin
  3445. obj.options['ymin'] = ymin
  3446. obj.options['xmax'] = xmax
  3447. obj.options['ymax'] = ymax
  3448. log.debug("Object changed, updating the bounding box data on self.options")
  3449. # delete the old selection shape
  3450. self.delete_selection_shape()
  3451. self.should_we_save = True
  3452. def on_object_plotted(self, obj):
  3453. """
  3454. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3455. :param obj: object to be fit into view
  3456. :return: None
  3457. """
  3458. self.on_zoom_fit(None)
  3459. def options_read_form(self):
  3460. """
  3461. Same as it's equivalent from the defaults.
  3462. self.options use to store the preferences per project. No longer used.
  3463. :return: None
  3464. """
  3465. for option in self.options_form_fields:
  3466. self.options[option] = self.options_form_fields[option].get_value()
  3467. def options_write_form(self):
  3468. """
  3469. Same as it's equivalent from the defaults.
  3470. self.options use to store the preferences per project. No longer used.
  3471. :return: None
  3472. """
  3473. for option in self.options:
  3474. self.options_write_form_field(option)
  3475. def options_write_form_field(self, field):
  3476. """
  3477. Same as it's equivalent from the defaults.
  3478. self.options use to store the preferences per project. No longer used.
  3479. :return: None
  3480. """
  3481. try:
  3482. self.options_form_fields[field].set_value(self.options[field])
  3483. except KeyError:
  3484. # Changed from error to debug. This allows to have data stored
  3485. # which is not user-editable.
  3486. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3487. pass
  3488. def on_about(self):
  3489. """
  3490. Displays the "about" dialog found in the Menu --> Help.
  3491. :return: None
  3492. """
  3493. self.report_usage("on_about")
  3494. version = self.version
  3495. version_date = self.version_date
  3496. beta = self.beta
  3497. class AboutDialog(QtWidgets.QDialog):
  3498. def __init__(self, parent=None):
  3499. QtWidgets.QDialog.__init__(self, parent)
  3500. # Icon and title
  3501. self.setWindowIcon(parent.app_icon)
  3502. self.setWindowTitle(_("About FlatCAM"))
  3503. self.resize(600, 200)
  3504. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3505. # self.setStyleSheet(
  3506. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3507. # "background-attachment: fixed"
  3508. # )
  3509. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3510. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3511. # palette = QtGui.QPalette()
  3512. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3513. # self.setPalette(palette)
  3514. logo = QtWidgets.QLabel()
  3515. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3516. title = QtWidgets.QLabel(
  3517. "<font size=8><B>FlatCAM</B></font><BR>"
  3518. "{title}<BR>"
  3519. "<BR>"
  3520. "<BR>"
  3521. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3522. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3523. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3524. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3525. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3526. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3527. "<B>{issue}</B></a><BR>".format(
  3528. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3529. devel=_("Development"),
  3530. down=_("DOWNLOAD"),
  3531. issue=_("Issue tracker"))
  3532. )
  3533. title.setOpenExternalLinks(True)
  3534. closebtn = QtWidgets.QPushButton(_("Close"))
  3535. tab_widget = QtWidgets.QTabWidget()
  3536. description_label = QtWidgets.QLabel(
  3537. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3538. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3539. version=version,
  3540. beta=('BETA' if beta else ''),
  3541. date=version_date,
  3542. arch=platform.architecture()[0])
  3543. )
  3544. description_label.setOpenExternalLinks(True)
  3545. license_label = QtWidgets.QLabel(
  3546. _(
  3547. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3548. 'Licensed under the MIT license:\n'
  3549. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3550. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3551. 'of this software and associated documentation files (the "Software"), to deal\n'
  3552. 'in the Software without restriction, including without limitation the rights\n'
  3553. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3554. 'copies of the Software, and to permit persons to whom the Software is\n'
  3555. ' furnished to do so, subject to the following conditions:\n\n'
  3556. 'The above copyright notice and this permission notice shall be included in\n'
  3557. 'all copies or substantial portions of the Software.\n\n'
  3558. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3559. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3560. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3561. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3562. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3563. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3564. 'THE SOFTWARE.'
  3565. )
  3566. )
  3567. license_label.setOpenExternalLinks(True)
  3568. # layouts
  3569. layout1 = QtWidgets.QVBoxLayout()
  3570. layout1_1 = QtWidgets.QHBoxLayout()
  3571. layout1_2 = QtWidgets.QHBoxLayout()
  3572. layout2 = QtWidgets.QHBoxLayout()
  3573. layout3 = QtWidgets.QHBoxLayout()
  3574. self.setLayout(layout1)
  3575. layout1.addLayout(layout1_1)
  3576. layout1.addLayout(layout1_2)
  3577. layout1.addLayout(layout2)
  3578. layout1.addLayout(layout3)
  3579. layout1_1.addStretch()
  3580. layout1_1.addWidget(description_label)
  3581. layout1_2.addWidget(tab_widget)
  3582. self.splash_tab = QtWidgets.QWidget()
  3583. self.splash_tab.setObjectName("splash_about")
  3584. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3585. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3586. tab_widget.addTab(self.splash_tab, _("Splash"))
  3587. self.programmmers_tab = QtWidgets.QWidget()
  3588. self.programmmers_tab.setObjectName("programmers_about")
  3589. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3590. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3591. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3592. self.translators_tab = QtWidgets.QWidget()
  3593. self.translators_tab.setObjectName("translators_about")
  3594. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3595. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3596. tab_widget.addTab(self.translators_tab, _("Translators"))
  3597. self.license_tab = QtWidgets.QWidget()
  3598. self.license_tab.setObjectName("license_about")
  3599. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3600. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3601. tab_widget.addTab(self.license_tab, _("License"))
  3602. self.splash_tab_layout.addWidget(logo, stretch=0)
  3603. self.splash_tab_layout.addWidget(title, stretch=1)
  3604. pal = QtGui.QPalette()
  3605. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3606. self.prog_form_lay = QtWidgets.QFormLayout()
  3607. self.prog_form_lay.setHorizontalSpacing(20)
  3608. prog_widget = QtWidgets.QWidget()
  3609. prog_widget.setLayout(self.prog_form_lay)
  3610. prog_scroll = QtWidgets.QScrollArea()
  3611. prog_scroll.setWidget(prog_widget)
  3612. prog_scroll.setWidgetResizable(True)
  3613. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3614. prog_scroll.setPalette(pal)
  3615. self.programmmers_tab_layout.addWidget(prog_scroll)
  3616. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3617. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3618. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3619. QtWidgets.QLabel('%s' % _("Program Author")))
  3620. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3621. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3622. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3623. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3624. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3625. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3626. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3627. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3628. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3629. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3630. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3631. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3632. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3633. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3634. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3635. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3636. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3637. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3638. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3639. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3640. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3641. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3642. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3643. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3644. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3645. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3646. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3647. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3648. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3649. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3650. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3651. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3652. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3653. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3654. self.translator_grid_lay = QtWidgets.QGridLayout()
  3655. # trans_widget = QtWidgets.QWidget()
  3656. # trans_widget.setLayout(self.translator_grid_lay)
  3657. # self.translators_tab_layout.addWidget(trans_widget)
  3658. # self.translators_tab_layout.addStretch()
  3659. trans_widget = QtWidgets.QWidget()
  3660. trans_widget.setLayout(self.translator_grid_lay)
  3661. trans_scroll = QtWidgets.QScrollArea()
  3662. trans_scroll.setWidget(trans_widget)
  3663. trans_scroll.setWidgetResizable(True)
  3664. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3665. trans_scroll.setPalette(pal)
  3666. self.translators_tab_layout.addWidget(trans_scroll)
  3667. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3668. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3669. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3670. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3671. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3672. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3673. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3674. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3675. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3676. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3677. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3678. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3679. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3680. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3681. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3682. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3683. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3684. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3685. self.translator_grid_lay.setColumnStretch(0, 0)
  3686. self.translators_tab_layout.addStretch()
  3687. self.license_tab_layout.addWidget(license_label)
  3688. self.license_tab_layout.addStretch()
  3689. layout3.addStretch()
  3690. layout3.addWidget(closebtn)
  3691. closebtn.clicked.connect(self.accept)
  3692. AboutDialog(self.ui).exec_()
  3693. def on_file_savedefaults(self):
  3694. """
  3695. Callback for menu item File->Save Defaults. Saves application default options
  3696. ``self.defaults`` to current_defaults.FlatConfig.
  3697. :return: None
  3698. """
  3699. self.save_defaults()
  3700. # def on_app_exit(self):
  3701. # self.report_usage("on_app_exit()")
  3702. #
  3703. # if self.collection.get_list():
  3704. # msgbox = QtWidgets.QMessageBox()
  3705. # # msgbox.setText("<B>Save changes ...</B>")
  3706. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3707. # "\n"
  3708. # "Do you want to Save the project?")
  3709. # msgbox.setWindowTitle("Save changes")
  3710. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3711. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3712. # QtWidgets.QMessageBox.Cancel)
  3713. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3714. #
  3715. # response = msgbox.exec_()
  3716. #
  3717. # if response == QtWidgets.QMessageBox.Yes:
  3718. # self.on_file_saveprojectas(thread=False)
  3719. # elif response == QtWidgets.QMessageBox.Cancel:
  3720. # return
  3721. # self.save_defaults()
  3722. # else:
  3723. # self.save_defaults()
  3724. # log.debug("Application defaults saved ... Exit event.")
  3725. # QtWidgets.qApp.quit()
  3726. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3727. """
  3728. Saves application default options
  3729. ``self.defaults`` to current_defaults.FlatConfig file.
  3730. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3731. used at the next launch of the application.
  3732. :param silent: whether to display a message in status bar or not; boolean
  3733. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3734. When the application is portable it should be a mobile location.
  3735. :return: None
  3736. """
  3737. self.report_usage("save_defaults")
  3738. if data_path is None:
  3739. data_path = self.data_path
  3740. # Read options from file
  3741. try:
  3742. f = open(data_path + "/current_defaults.FlatConfig")
  3743. defaults_file_content = f.read()
  3744. f.close()
  3745. except:
  3746. e = sys.exc_info()[0]
  3747. App.log.error("Could not load defaults file.")
  3748. App.log.error(str(e))
  3749. self.inform.emit('[ERROR_NOTCL] %s' %
  3750. _("Could not load defaults file."))
  3751. return
  3752. try:
  3753. defaults = json.loads(defaults_file_content)
  3754. except:
  3755. e = sys.exc_info()[0]
  3756. App.log.error("Failed to parse defaults file.")
  3757. App.log.error(str(e))
  3758. self.inform.emit('[ERROR_NOTCL] %s' %
  3759. _("Failed to parse defaults file."))
  3760. return
  3761. # Update options
  3762. self.defaults_read_form()
  3763. defaults.update(self.defaults)
  3764. self.propagate_defaults(silent=True)
  3765. # Save the toolbar view
  3766. tb_status = 0
  3767. if self.ui.toolbarfile.isVisible():
  3768. tb_status += 1
  3769. if self.ui.toolbargeo.isVisible():
  3770. tb_status += 2
  3771. if self.ui.toolbarview.isVisible():
  3772. tb_status += 4
  3773. if self.ui.toolbartools.isVisible():
  3774. tb_status += 8
  3775. if self.ui.exc_edit_toolbar.isVisible():
  3776. tb_status += 16
  3777. if self.ui.geo_edit_toolbar.isVisible():
  3778. tb_status += 32
  3779. if self.ui.grb_edit_toolbar.isVisible():
  3780. tb_status += 64
  3781. if self.ui.snap_toolbar.isVisible():
  3782. tb_status += 128
  3783. if self.ui.toolbarshell.isVisible():
  3784. tb_status += 256
  3785. if first_time is False:
  3786. self.defaults["global_toolbar_view"] = tb_status
  3787. # Save update options
  3788. try:
  3789. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3790. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3791. f.close()
  3792. except:
  3793. self.inform.emit('[ERROR_NOTCL] %s' %
  3794. _("Failed to write defaults to file."))
  3795. return
  3796. if not silent:
  3797. self.inform.emit('[success] %s' %
  3798. _("Preferences saved."))
  3799. def save_factory_defaults(self, silent=False, data_path=None):
  3800. """
  3801. Saves application factory default options
  3802. ``self.defaults`` to factory_defaults.FlatConfig.
  3803. It's a one time job done just after the first install.
  3804. :param silent: whether to display a message in status bar or not; boolean
  3805. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3806. When the application is portable it should be a mobile location.
  3807. :return: None
  3808. """
  3809. self.report_usage("save_factory_defaults")
  3810. if data_path is None:
  3811. data_path = self.data_path
  3812. # Read options from file
  3813. try:
  3814. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3815. factory_defaults_file_content = f_f_def.read()
  3816. f_f_def.close()
  3817. except:
  3818. e = sys.exc_info()[0]
  3819. App.log.error("Could not load factory defaults file.")
  3820. App.log.error(str(e))
  3821. self.inform.emit('[ERROR_NOTCL] %s' %
  3822. _("Could not load factory defaults file."))
  3823. return
  3824. try:
  3825. factory_defaults = json.loads(factory_defaults_file_content)
  3826. except:
  3827. e = sys.exc_info()[0]
  3828. App.log.error("Failed to parse factory defaults file.")
  3829. App.log.error(str(e))
  3830. self.inform.emit('[ERROR_NOTCL] %s' %
  3831. _("Failed to parse factory defaults file."))
  3832. return
  3833. # Update options
  3834. self.defaults_read_form()
  3835. factory_defaults.update(self.defaults)
  3836. self.propagate_defaults(silent=True)
  3837. # Save update options
  3838. try:
  3839. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3840. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3841. f_f_def_s.close()
  3842. except:
  3843. self.inform.emit('[ERROR_NOTCL] %s' %
  3844. _("Failed to write factory defaults to file."))
  3845. return
  3846. if silent is False:
  3847. self.inform.emit(_("Factory defaults saved."))
  3848. def final_save(self):
  3849. """
  3850. Callback for doing a preferences save to file whenever the application is about to quit.
  3851. If the project has changes, it will ask the user to save the project.
  3852. :return: None
  3853. """
  3854. if self.save_in_progress:
  3855. self.inform.emit('[WARNING_NOTCL] %s' %
  3856. _("Application is saving the project. Please wait ..."))
  3857. return
  3858. if self.should_we_save and self.collection.get_list():
  3859. msgbox = QtWidgets.QMessageBox()
  3860. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3861. "\n"
  3862. "Do you want to Save the project?"))
  3863. msgbox.setWindowTitle(_("Save changes"))
  3864. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3865. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3866. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3867. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3868. msgbox.setDefaultButton(bt_yes)
  3869. msgbox.exec_()
  3870. response = msgbox.clickedButton()
  3871. if response == bt_yes:
  3872. try:
  3873. self.trayIcon.hide()
  3874. except:
  3875. pass
  3876. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3877. elif response == bt_no:
  3878. try:
  3879. self.trayIcon.hide()
  3880. except:
  3881. pass
  3882. self.quit_application()
  3883. elif response == bt_cancel:
  3884. return
  3885. else:
  3886. try:
  3887. self.trayIcon.hide()
  3888. except:
  3889. pass
  3890. self.quit_application()
  3891. def quit_application(self):
  3892. """
  3893. Called (as a pyslot or not) when the application is quit.
  3894. :return: None
  3895. """
  3896. self.save_defaults()
  3897. log.debug("App.final_save() --> App Defaults saved.")
  3898. if self.cmd_line_headless != 1:
  3899. # save app state to file
  3900. settings = QSettings("Open Source", "FlatCAM")
  3901. settings.setValue('saved_gui_state', self.ui.saveState())
  3902. settings.setValue('maximized_gui', self.ui.isMaximized())
  3903. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3904. settings.setValue(
  3905. 'notebook_font_size',
  3906. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3907. )
  3908. settings.setValue('axis_font_size',
  3909. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3910. settings.setValue(
  3911. 'textbox_font_size',
  3912. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  3913. )
  3914. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3915. # This will write the setting to the platform specific storage.
  3916. del settings
  3917. log.debug("App.final_save() --> App UI state saved.")
  3918. QtWidgets.qApp.quit()
  3919. def on_portable_checked(self, state):
  3920. """
  3921. Callback called when the checkbox in Preferences GUI is checked.
  3922. It will set the application as portable by creating the preferences and recent files in the
  3923. 'config' folder found in the FlatCAM installation folder.
  3924. :param state: boolean, the state of the checkbox when clicked/checked
  3925. :return:
  3926. """
  3927. line_no = 0
  3928. data = None
  3929. if sys.platform != 'win32':
  3930. # this won't work in Linux or MacOS
  3931. return
  3932. # test if the app was frozen and choose the path for the configuration file
  3933. if getattr(sys, "frozen", False) is True:
  3934. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3935. else:
  3936. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3937. config_file = current_data_path + '\\configuration.txt'
  3938. try:
  3939. with open(config_file, 'r') as f:
  3940. try:
  3941. data = f.readlines()
  3942. except Exception as e:
  3943. log.debug('App.__init__() -->%s' % str(e))
  3944. return
  3945. except FileNotFoundError:
  3946. pass
  3947. for line in data:
  3948. line = line.strip('\n')
  3949. param = str(line).rpartition('=')
  3950. if param[0] == 'portable':
  3951. break
  3952. line_no += 1
  3953. if state:
  3954. data[line_no] = 'portable=True\n'
  3955. # create the new defauults files
  3956. # create current_defaults.FlatConfig file if there is none
  3957. try:
  3958. f = open(current_data_path + '/current_defaults.FlatConfig')
  3959. f.close()
  3960. except IOError:
  3961. App.log.debug('Creating empty current_defaults.FlatConfig')
  3962. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3963. json.dump({}, f)
  3964. f.close()
  3965. # create factory_defaults.FlatConfig file if there is none
  3966. try:
  3967. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3968. f.close()
  3969. except IOError:
  3970. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3971. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3972. json.dump({}, f)
  3973. f.close()
  3974. try:
  3975. f = open(current_data_path + '/recent.json')
  3976. f.close()
  3977. except IOError:
  3978. App.log.debug('Creating empty recent.json')
  3979. f = open(current_data_path + '/recent.json', 'w')
  3980. json.dump([], f)
  3981. f.close()
  3982. try:
  3983. fp = open(current_data_path + '/recent_projects.json')
  3984. fp.close()
  3985. except IOError:
  3986. App.log.debug('Creating empty recent_projects.json')
  3987. fp = open(current_data_path + '/recent_projects.json', 'w')
  3988. json.dump([], fp)
  3989. fp.close()
  3990. # save the current defaults to the new defaults file
  3991. self.save_defaults(silent=True, data_path=current_data_path)
  3992. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3993. else:
  3994. data[line_no] = 'portable=False\n'
  3995. with open(config_file, 'w') as f:
  3996. f.writelines(data)
  3997. def on_toggle_shell(self):
  3998. """
  3999. Toggle shell: if is visible close it, if it is closed then open it
  4000. :return:
  4001. """
  4002. self.report_usage("on_toggle_shell()")
  4003. if self.ui.shell_dock.isVisible():
  4004. self.ui.shell_dock.hide()
  4005. else:
  4006. self.ui.shell_dock.show()
  4007. def on_register_files(self, obj_type=None):
  4008. """
  4009. Called whenever there is a need to register file extensions with FlatCAM.
  4010. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4011. :param obj_type: the type of object to be register for.
  4012. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4013. :return: None
  4014. """
  4015. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4016. new_reg_path = 'Software\\Classes\\'
  4017. # find if the current user is admin
  4018. try:
  4019. is_admin = os.getuid() == 0
  4020. except AttributeError:
  4021. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4022. if is_admin is True:
  4023. root_path = winreg.HKEY_LOCAL_MACHINE
  4024. else:
  4025. root_path = winreg.HKEY_CURRENT_USER
  4026. # create the keys
  4027. def set_reg(name, root_path, new_reg_path, value):
  4028. try:
  4029. winreg.CreateKey(root_path, new_reg_path)
  4030. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4031. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4032. return True
  4033. except WindowsError:
  4034. return False
  4035. # delete key in registry
  4036. def delete_reg(root_path, reg_path, key_to_del):
  4037. key_to_del_path = reg_path + key_to_del
  4038. try:
  4039. winreg.DeleteKey(root_path, key_to_del_path)
  4040. return True
  4041. except WindowsError:
  4042. return False
  4043. if obj_type is None or obj_type == 'excellon':
  4044. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4045. exc_list = [x for x in exc_list if x != '']
  4046. # register all keys in the Preferences window
  4047. for ext in exc_list:
  4048. new_k = new_reg_path + '.%s' % ext
  4049. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4050. # and unregister those that are no longer in the Preferences windows but are in the file
  4051. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4052. if ext not in exc_list:
  4053. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4054. # now write the updated extensions to the self.defaults
  4055. # new_ext = ''
  4056. # for ext in exc_list:
  4057. # new_ext = new_ext + ext + ', '
  4058. # self.defaults["fa_excellon"] = new_ext
  4059. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4060. if obj_type is None or obj_type == 'gcode':
  4061. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4062. gco_list = [x for x in gco_list if x != '']
  4063. # register all keys in the Preferences window
  4064. for ext in gco_list:
  4065. new_k = new_reg_path + '.%s' % ext
  4066. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4067. # and unregister those that are no longer in the Preferences windows but are in the file
  4068. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4069. if ext not in gco_list:
  4070. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4071. # now write the updated extensions to the self.defaults
  4072. # new_ext = ''
  4073. # for ext in gco_list:
  4074. # new_ext = new_ext + ext + ', '
  4075. # self.defaults["fa_gcode"] = new_ext
  4076. self.inform.emit('[success] %s' %
  4077. _("Selected GCode file extensions registered with FlatCAM."))
  4078. if obj_type is None or obj_type == 'gerber':
  4079. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4080. grb_list = [x for x in grb_list if x != '']
  4081. # register all keys in the Preferences window
  4082. for ext in grb_list:
  4083. new_k = new_reg_path + '.%s' % ext
  4084. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4085. # and unregister those that are no longer in the Preferences windows but are in the file
  4086. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4087. if ext not in grb_list:
  4088. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4089. # now write the updated extensions to the self.defaults
  4090. # new_ext = ''
  4091. # for ext in grb_list:
  4092. # new_ext = new_ext + ext + ', '
  4093. # self.defaults["fa_gerber"] = new_ext
  4094. self.inform.emit('[success] %s' %
  4095. _("Selected Gerber file extensions registered with FlatCAM."))
  4096. def add_extension(self, ext_type):
  4097. if ext_type == 'excellon':
  4098. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4099. if new_ext == '':
  4100. return
  4101. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4102. if new_ext in old_val:
  4103. return
  4104. old_val.append(new_ext)
  4105. old_val.sort()
  4106. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4107. if ext_type == 'gcode':
  4108. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4109. if new_ext == '':
  4110. return
  4111. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4112. if new_ext in old_val:
  4113. return
  4114. old_val.append(new_ext)
  4115. old_val.sort()
  4116. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4117. if ext_type == 'gerber':
  4118. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4119. if new_ext == '':
  4120. return
  4121. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4122. if new_ext in old_val:
  4123. return
  4124. old_val.append(new_ext)
  4125. old_val.sort()
  4126. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4127. if ext_type == 'keyword':
  4128. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4129. if new_kw == '':
  4130. return
  4131. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4132. if new_kw in old_val:
  4133. return
  4134. old_val.append(new_kw)
  4135. old_val.sort()
  4136. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4137. # update the self.myKeywords so the model is updated
  4138. self.autocomplete_kw_list = \
  4139. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4140. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4141. self.shell._edit.set_model_data(self.myKeywords)
  4142. self.ui.code_editor.set_model_data(self.myKeywords)
  4143. def del_extension(self, ext_type):
  4144. if ext_type == 'excellon':
  4145. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4146. if new_ext == '':
  4147. return
  4148. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4149. if new_ext not in old_val:
  4150. return
  4151. old_val.remove(new_ext)
  4152. old_val.sort()
  4153. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4154. if ext_type == 'gcode':
  4155. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4156. if new_ext == '':
  4157. return
  4158. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4159. if new_ext not in old_val:
  4160. return
  4161. old_val.remove(new_ext)
  4162. old_val.sort()
  4163. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4164. if ext_type == 'gerber':
  4165. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4166. if new_ext == '':
  4167. return
  4168. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4169. if new_ext not in old_val:
  4170. return
  4171. old_val.remove(new_ext)
  4172. old_val.sort()
  4173. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4174. if ext_type == 'keyword':
  4175. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4176. if new_kw == '':
  4177. return
  4178. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4179. if new_kw not in old_val:
  4180. return
  4181. old_val.remove(new_kw)
  4182. old_val.sort()
  4183. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4184. # update the self.myKeywords so the model is updated
  4185. self.autocomplete_kw_list = \
  4186. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4187. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4188. self.shell._edit.set_model_data(self.myKeywords)
  4189. self.ui.code_editor.set_model_data(self.myKeywords)
  4190. def restore_extensions(self, ext_type):
  4191. if ext_type == 'excellon':
  4192. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4193. # for the ability to open Excellon files with .txt extension
  4194. new_exc_list = deepcopy(self.exc_list)
  4195. try:
  4196. new_exc_list.remove('txt')
  4197. except ValueError:
  4198. pass
  4199. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4200. if ext_type == 'gcode':
  4201. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4202. if ext_type == 'gerber':
  4203. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4204. if ext_type == 'keyword':
  4205. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4206. # update the self.myKeywords so the model is updated
  4207. self.autocomplete_kw_list = self.default_keywords
  4208. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4209. self.shell._edit.set_model_data(self.myKeywords)
  4210. self.ui.code_editor.set_model_data(self.myKeywords)
  4211. def delete_all_extensions(self, ext_type):
  4212. if ext_type == 'excellon':
  4213. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4214. if ext_type == 'gcode':
  4215. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4216. if ext_type == 'gerber':
  4217. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4218. if ext_type == 'keyword':
  4219. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4220. # update the self.myKeywords so the model is updated
  4221. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4222. self.shell._edit.set_model_data(self.myKeywords)
  4223. self.ui.code_editor.set_model_data(self.myKeywords)
  4224. def on_edit_join(self, name=None):
  4225. """
  4226. Callback for Edit->Join. Joins the selected geometry objects into
  4227. a new one.
  4228. :return: None
  4229. """
  4230. self.report_usage("on_edit_join()")
  4231. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4232. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4233. tooldias = []
  4234. geo_type_list = set()
  4235. objs = self.collection.get_selected()
  4236. if len(objs) < 2:
  4237. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4238. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4239. return 'fail'
  4240. for obj in objs:
  4241. geo_type_list.add(obj.multigeo)
  4242. # if len(geo_type_list) == 1 means that all list elements are the same
  4243. if len(geo_type_list) != 1:
  4244. self.inform.emit('[ERROR] %s' %
  4245. _("Failed join. The Geometry objects are of different types.\n"
  4246. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4247. "convert from one to another and retry joining \n"
  4248. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4249. "the result may not be what was expected. \n"
  4250. "Check the generated GCODE."))
  4251. return
  4252. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4253. if True in geo_type_list:
  4254. def initialize(obj, app):
  4255. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4256. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4257. for v in obj.tools.values():
  4258. v['data']['name'] = obj_name_multi
  4259. self.new_object("geometry", obj_name_multi, initialize)
  4260. else:
  4261. def initialize(obj, app):
  4262. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4263. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4264. for v in obj.tools.values():
  4265. v['data']['name'] = obj_name_single
  4266. self.new_object("geometry", obj_name_single, initialize)
  4267. self.should_we_save = True
  4268. def on_edit_join_exc(self):
  4269. """
  4270. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4271. a new Excellon.
  4272. :return: None
  4273. """
  4274. self.report_usage("on_edit_join_exc()")
  4275. objs = self.collection.get_selected()
  4276. for obj in objs:
  4277. if not isinstance(obj, FlatCAMExcellon):
  4278. self.inform.emit('[ERROR_NOTCL] %s' %
  4279. _("Failed. Excellon joining works only on Excellon objects."))
  4280. return
  4281. if len(objs) < 2:
  4282. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4283. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4284. return 'fail'
  4285. def initialize(obj, app):
  4286. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4287. self.new_object("excellon", 'Combo_Excellon', initialize)
  4288. self.should_we_save = True
  4289. def on_edit_join_grb(self):
  4290. """
  4291. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4292. a new Gerber object.
  4293. :return: None
  4294. """
  4295. self.report_usage("on_edit_join_grb()")
  4296. objs = self.collection.get_selected()
  4297. for obj in objs:
  4298. if not isinstance(obj, FlatCAMGerber):
  4299. self.inform.emit('[ERROR_NOTCL] %s' %
  4300. _("Failed. Gerber joining works only on Gerber objects."))
  4301. return
  4302. if len(objs) < 2:
  4303. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4304. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4305. return 'fail'
  4306. def initialize(obj, app):
  4307. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4308. self.new_object("gerber", 'Combo_Gerber', initialize)
  4309. self.should_we_save = True
  4310. def on_convert_singlegeo_to_multigeo(self):
  4311. """
  4312. Called for converting a Geometry object from single-geo to multi-geo.
  4313. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4314. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4315. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4316. the solid-geometry of that tool.
  4317. :return: None
  4318. """
  4319. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4320. obj = self.collection.get_active()
  4321. if obj is None:
  4322. self.inform.emit('[ERROR_NOTCL] %s' %
  4323. _("Failed. Select a Geometry Object and try again."))
  4324. return
  4325. if not isinstance(obj, FlatCAMGeometry):
  4326. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4327. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4328. return
  4329. obj.multigeo = True
  4330. for tooluid, dict_value in obj.tools.items():
  4331. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4332. if not isinstance(obj.solid_geometry, list):
  4333. obj.solid_geometry = [obj.solid_geometry]
  4334. obj.solid_geometry[:] = []
  4335. obj.plot()
  4336. self.should_we_save = True
  4337. self.inform.emit('[success] %s' %
  4338. _("A Geometry object was converted to MultiGeo type."))
  4339. def on_convert_multigeo_to_singlegeo(self):
  4340. """
  4341. Called for converting a Geometry object from multi-geo to single-geo.
  4342. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4343. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4344. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4345. the solid-geometry of that tool.
  4346. :return: None
  4347. """
  4348. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4349. obj = self.collection.get_active()
  4350. if obj is None:
  4351. self.inform.emit('[ERROR_NOTCL] %s' %
  4352. _("Failed. Select a Geometry Object and try again."))
  4353. return
  4354. if not isinstance(obj, FlatCAMGeometry):
  4355. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4356. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4357. return
  4358. obj.multigeo = False
  4359. total_solid_geometry = []
  4360. for tooluid, dict_value in obj.tools.items():
  4361. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4362. # clear the original geometry
  4363. dict_value['solid_geometry'][:] = []
  4364. obj.solid_geometry = deepcopy(total_solid_geometry)
  4365. obj.plot()
  4366. self.should_we_save = True
  4367. self.inform.emit('[success] %s' %
  4368. _("A Geometry object was converted to SingleGeo type."))
  4369. def on_options_dict_change(self, field):
  4370. """
  4371. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4372. current project. This feature is no longer used.
  4373. :param field:
  4374. :return:
  4375. """
  4376. self.options_write_form_field(field)
  4377. if field == "units":
  4378. self.set_screen_units(self.options['units'])
  4379. def on_defaults_dict_change(self, field):
  4380. """
  4381. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4382. Edit -> Preferences tab window.
  4383. :param field: the key of the self.defaults dictionary that was changed.
  4384. :return: None
  4385. """
  4386. self.defaults_write_form_field(field)
  4387. if field == "units":
  4388. self.set_screen_units(self.defaults['units'])
  4389. def set_screen_units(self, units):
  4390. """
  4391. Set the FlatCAM units on the status bar.
  4392. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4393. :return: None
  4394. """
  4395. self.ui.units_label.setText("[" + units.lower() + "]")
  4396. def on_toggle_units(self, no_pref=False):
  4397. """
  4398. Callback for the Units radio-button change in the Preferences tab.
  4399. Changes the application's default units adn for the project too.
  4400. If changing the project's units, the change propagates to all of
  4401. the objects in the project.
  4402. :return: None
  4403. """
  4404. self.report_usage("on_toggle_units")
  4405. if self.toggle_units_ignore:
  4406. return
  4407. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4408. # If option is the same, then ignore
  4409. if new_units == self.defaults["units"].upper():
  4410. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4411. return
  4412. # Options to scale
  4413. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4414. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4415. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4416. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4417. "excellon_z_pdepth",
  4418. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4419. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4420. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4421. "geometry_feedrate_probe",
  4422. 'cncjob_tooldia',
  4423. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4424. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4425. "tools_2sided_drilldia", "tools_film_boundary",
  4426. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4427. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4428. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4429. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4430. "tools_transform_offset_y",
  4431. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4432. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4433. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4434. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4435. 'global_gridx', 'global_gridy', 'global_snap_max']
  4436. def scale_options(sfactor):
  4437. for dim in dimensions:
  4438. if dim == 'excellon_toolchangexy':
  4439. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4440. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4441. coords_xy[0] *= sfactor
  4442. coords_xy[1] *= sfactor
  4443. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4444. elif dim == 'geometry_toolchangexy':
  4445. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4446. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4447. coords_xy[0] *= sfactor
  4448. coords_xy[1] *= sfactor
  4449. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4450. elif dim == 'geometry_cnctooldia':
  4451. tools_diameters = []
  4452. try:
  4453. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4454. tools_diameters = [eval(a) for a in tools_string if a != '']
  4455. except Exception as e:
  4456. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4457. self.options['geometry_cnctooldia'] = ''
  4458. for t in range(len(tools_diameters)):
  4459. tools_diameters[t] *= sfactor
  4460. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4461. elif dim == 'tools_ncctools':
  4462. ncctools = []
  4463. try:
  4464. tools_string = self.defaults["tools_ncctools"].split(",")
  4465. ncctools = [eval(a) for a in tools_string if a != '']
  4466. except Exception as e:
  4467. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4468. self.options['tools_ncctools'] = ''
  4469. for t in range(len(ncctools)):
  4470. ncctools[t] *= sfactor
  4471. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4472. elif dim == 'tools_solderpaste_tools':
  4473. sptools = []
  4474. try:
  4475. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4476. sptools = [eval(a) for a in tools_string if a != '']
  4477. except Exception as e:
  4478. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4479. self.options['tools_solderpaste_tools'] = ""
  4480. for t in range(len(sptools)):
  4481. sptools[t] *= sfactor
  4482. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4483. elif dim == 'tools_solderpaste_xy_toolchange':
  4484. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4485. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4486. sp_coords[0] *= sfactor
  4487. sp_coords[1] *= sfactor
  4488. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4489. elif dim == 'global_gridx' or dim == 'global_gridy':
  4490. if new_units == 'IN':
  4491. val = 0.1
  4492. try:
  4493. val = float(self.defaults[dim]) * sfactor
  4494. except Exception as e:
  4495. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4496. self.options[dim] = float('%.6f' % val)
  4497. else:
  4498. val = 0.1
  4499. try:
  4500. val = float(self.defaults[dim]) * sfactor
  4501. except Exception as e:
  4502. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4503. self.options[dim] = float('%.4f' % val)
  4504. else:
  4505. val = 0.1
  4506. try:
  4507. val = float(self.options[dim]) * sfactor
  4508. except Exception as e:
  4509. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4510. self.options[dim] = val
  4511. def scale_defaults(sfactor):
  4512. for dim in dimensions:
  4513. if dim == 'excellon_toolchangexy':
  4514. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4515. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4516. coords_xy[0] *= sfactor
  4517. coords_xy[1] *= sfactor
  4518. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4519. elif dim == 'geometry_toolchangexy':
  4520. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4521. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4522. coords_xy[0] *= sfactor
  4523. coords_xy[1] *= sfactor
  4524. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4525. elif dim == 'geometry_cnctooldia':
  4526. tools_diameters = []
  4527. try:
  4528. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4529. tools_diameters = [eval(a) for a in tools_string if a != '']
  4530. except Exception as e:
  4531. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4532. self.defaults['geometry_cnctooldia'] = ''
  4533. for t in range(len(tools_diameters)):
  4534. tools_diameters[t] *= sfactor
  4535. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4536. elif dim == 'tools_ncctools':
  4537. ncctools = []
  4538. try:
  4539. tools_string = self.defaults["tools_ncctools"].split(",")
  4540. ncctools = [eval(a) for a in tools_string if a != '']
  4541. except Exception as e:
  4542. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4543. self.defaults['tools_ncctools'] = ''
  4544. for t in range(len(ncctools)):
  4545. ncctools[t] *= sfactor
  4546. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4547. elif dim == 'tools_solderpaste_tools':
  4548. sptools = []
  4549. try:
  4550. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4551. sptools = [eval(a) for a in tools_string if a != '']
  4552. except Exception as e:
  4553. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4554. self.defaults['tools_solderpaste_tools'] = ""
  4555. for t in range(len(sptools)):
  4556. sptools[t] *= sfactor
  4557. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4558. elif dim == 'tools_solderpaste_xy_toolchange':
  4559. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4560. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4561. sp_coords[0] *= sfactor
  4562. sp_coords[1] *= sfactor
  4563. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4564. elif dim == 'global_gridx' or dim == 'global_gridy':
  4565. if new_units == 'IN':
  4566. val = 0.1
  4567. try:
  4568. val = float(self.defaults[dim]) * sfactor
  4569. except Exception as e:
  4570. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4571. self.defaults[dim] = float('%.6f' % val)
  4572. else:
  4573. val = 0.1
  4574. try:
  4575. val = float(self.defaults[dim]) * sfactor
  4576. except Exception as e:
  4577. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4578. self.defaults[dim] = float('%.4f' % val)
  4579. else:
  4580. val = 0.1
  4581. try:
  4582. val = float(self.defaults[dim]) * sfactor
  4583. except Exception as e:
  4584. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4585. self.defaults[dim] = val
  4586. # The scaling factor depending on choice of units.
  4587. factor = 1/25.4
  4588. if new_units == 'MM':
  4589. factor = 25.4
  4590. # Changing project units. Warn user.
  4591. msgbox = QtWidgets.QMessageBox()
  4592. msgbox.setWindowTitle(_("Toggle Units"))
  4593. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4594. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4595. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4596. "properties of all objects to be scaled accordingly.\nContinue?"))
  4597. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4598. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4599. msgbox.setDefaultButton(bt_ok)
  4600. msgbox.exec_()
  4601. response = msgbox.clickedButton()
  4602. if response == bt_ok:
  4603. if no_pref is False:
  4604. self.options_read_form()
  4605. scale_options(factor)
  4606. self.options_write_form()
  4607. self.defaults_read_form()
  4608. scale_defaults(factor)
  4609. self.defaults_write_form(fl_units=new_units)
  4610. # save the defaults to file, some may assume that the conversion is enough and it's not
  4611. self.on_save_button()
  4612. self.should_we_save = True
  4613. # change this only if the workspace is active
  4614. if self.defaults['global_workspace'] is True:
  4615. self.plotcanvas.draw_workspace()
  4616. # adjust the grid values on the main toolbar
  4617. dec = 6 if new_units == 'IN'else 4
  4618. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4619. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4620. if not self.ui.grid_gap_link_cb.isChecked():
  4621. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4622. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4623. for obj in self.collection.get_list():
  4624. obj.convert_units(new_units)
  4625. # make that the properties stored in the object are also updated
  4626. self.object_changed.emit(obj)
  4627. obj.build_ui()
  4628. current = self.collection.get_active()
  4629. if current is not None:
  4630. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4631. if not isinstance(current, FlatCAMGeometry):
  4632. current.to_form()
  4633. self.plot_all()
  4634. self.inform.emit('[success] %s: %s' %
  4635. (_("Converted units to"), new_units))
  4636. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4637. self.set_screen_units(new_units)
  4638. else:
  4639. # Undo toggling
  4640. self.toggle_units_ignore = True
  4641. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4642. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4643. else:
  4644. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4645. self.toggle_units_ignore = False
  4646. self.inform.emit('[WARNING_NOTCL]%s' %
  4647. _(" Units conversion cancelled."))
  4648. self.options_read_form()
  4649. self.defaults_read_form()
  4650. def on_toggle_units_click(self):
  4651. try:
  4652. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4653. except (TypeError, AttributeError):
  4654. pass
  4655. if self.defaults["units"] == 'MM':
  4656. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4657. else:
  4658. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4659. self.on_toggle_units(no_pref=True)
  4660. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4661. lambda: self.on_toggle_units(no_pref=False))
  4662. def on_fullscreen(self):
  4663. self.report_usage("on_fullscreen()")
  4664. if self.toggle_fscreen is False:
  4665. if sys.platform == 'win32':
  4666. self.ui.showFullScreen()
  4667. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4668. tb.setVisible(False)
  4669. self.ui.splitter_left.setVisible(False)
  4670. self.toggle_fscreen = True
  4671. else:
  4672. if sys.platform == 'win32':
  4673. self.ui.showNormal()
  4674. self.restore_toolbar_view()
  4675. self.ui.splitter_left.setVisible(True)
  4676. self.toggle_fscreen = False
  4677. def on_toggle_plotarea(self):
  4678. self.report_usage("on_toggle_plotarea()")
  4679. try:
  4680. name = self.ui.plot_tab_area.widget(0).objectName()
  4681. except AttributeError:
  4682. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4683. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4684. self.ui.plot_tab_area.protectTab(0)
  4685. return
  4686. if name != 'plotarea':
  4687. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4688. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4689. self.ui.plot_tab_area.protectTab(0)
  4690. else:
  4691. self.ui.plot_tab_area.closeTab(0)
  4692. def on_toggle_notebook(self):
  4693. if self.ui.splitter.sizes()[0] == 0:
  4694. self.ui.splitter.setSizes([1, 1])
  4695. else:
  4696. self.ui.splitter.setSizes([0, 1])
  4697. def on_toggle_axis(self):
  4698. self.report_usage("on_toggle_axis()")
  4699. if self.toggle_axis is False:
  4700. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4701. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4702. self.plotcanvas.redraw()
  4703. self.toggle_axis = True
  4704. else:
  4705. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4706. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4707. self.plotcanvas.redraw()
  4708. self.toggle_axis = False
  4709. def on_toggle_grid(self):
  4710. self.report_usage("on_toggle_grid()")
  4711. self.ui.grid_snap_btn.trigger()
  4712. def on_options_combo_change(self, sel):
  4713. """
  4714. Called when the combo box to choose between application defaults and
  4715. project option changes value. The corresponding variables are
  4716. copied to the UI.
  4717. :param sel: The option index that was chosen.
  4718. :return: None
  4719. """
  4720. # combo_sel = self.ui.notebook.combo_options.get_active()
  4721. App.log.debug("Options --> %s" % sel)
  4722. # form = [self.defaults_form, self.options_form][sel]
  4723. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4724. if sel == 0:
  4725. self.gen_form = self.ui.general_defaults_form
  4726. self.ger_form = self.ui.gerber_defaults_form
  4727. self.exc_form = self.ui.excellon_defaults_form
  4728. self.geo_form = self.ui.geometry_defaults_form
  4729. self.cnc_form = self.ui.cncjob_defaults_form
  4730. self.tools_form = self.ui.tools_defaults_form
  4731. self.fa_form = self.ui.util_defaults_form
  4732. elif sel == 1:
  4733. self.gen_form = self.ui.general_options_form
  4734. self.ger_form = self.ui.gerber_options_form
  4735. self.exc_form = self.ui.excellon_options_form
  4736. self.geo_form = self.ui.geometry_options_form
  4737. self.cnc_form = self.ui.cncjob_options_form
  4738. self.tools_form = self.ui.tools_options_form
  4739. self.fa_form = self.ui.util_options_form
  4740. else:
  4741. return
  4742. try:
  4743. self.ui.general_scroll_area.takeWidget()
  4744. except:
  4745. self.log.debug("Nothing to remove")
  4746. self.ui.general_scroll_area.setWidget(self.gen_form)
  4747. self.gen_form.show()
  4748. try:
  4749. self.ui.gerber_scroll_area.takeWidget()
  4750. except:
  4751. self.log.debug("Nothing to remove")
  4752. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4753. self.ger_form.show()
  4754. try:
  4755. self.ui.excellon_scroll_area.takeWidget()
  4756. except:
  4757. self.log.debug("Nothing to remove")
  4758. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4759. self.exc_form.show()
  4760. try:
  4761. self.ui.geometry_scroll_area.takeWidget()
  4762. except:
  4763. self.log.debug("Nothing to remove")
  4764. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4765. self.geo_form.show()
  4766. try:
  4767. self.ui.cncjob_scroll_area.takeWidget()
  4768. except:
  4769. self.log.debug("Nothing to remove")
  4770. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4771. self.cnc_form.show()
  4772. try:
  4773. self.ui.tools_scroll_area.takeWidget()
  4774. except:
  4775. self.log.debug("Nothing to remove")
  4776. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4777. self.tools_form.show()
  4778. try:
  4779. self.ui.fa_scroll_area.takeWidget()
  4780. except:
  4781. self.log.debug("Nothing to remove")
  4782. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4783. self.fa_form.show()
  4784. self.log.debug("Finished GUI form initialization.")
  4785. # self.options2form()
  4786. def on_excellon_defaults_button(self):
  4787. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4788. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4789. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4790. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4791. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4792. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4793. log.debug("Excellon app defaults loaded ...")
  4794. def on_excellon_options_button(self):
  4795. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4796. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4797. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4798. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4799. self.options_form_fields["excellon_zeros"].set_value('L')
  4800. self.options_form_fields["excellon_units"].set_value('INCH')
  4801. log.debug("Excellon options defaults loaded ...")
  4802. def on_update_exc_export(self, state):
  4803. """
  4804. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4805. if the update_excellon_cb checkbox is checked
  4806. :param state: state of the checkbox whose signals is tied to his slot
  4807. :return:
  4808. """
  4809. if state:
  4810. # first try to disconnect
  4811. try:
  4812. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4813. disconnect(self.on_excellon_format_changed)
  4814. except TypeError:
  4815. pass
  4816. try:
  4817. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4818. disconnect(self.on_excellon_format_changed)
  4819. except TypeError:
  4820. pass
  4821. try:
  4822. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4823. disconnect(self.on_excellon_format_changed)
  4824. except TypeError:
  4825. pass
  4826. try:
  4827. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4828. disconnect(self.on_excellon_format_changed)
  4829. except TypeError:
  4830. pass
  4831. try:
  4832. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4833. disconnect(self.on_excellon_zeros_changed)
  4834. except TypeError:
  4835. pass
  4836. try:
  4837. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4838. disconnect(self.on_excellon_zeros_changed)
  4839. except TypeError:
  4840. pass
  4841. # the connect them
  4842. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4843. self.on_excellon_format_changed)
  4844. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4845. self.on_excellon_format_changed)
  4846. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4847. self.on_excellon_format_changed)
  4848. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4849. self.on_excellon_format_changed)
  4850. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4851. self.on_excellon_zeros_changed)
  4852. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4853. self.on_excellon_units_changed)
  4854. else:
  4855. # disconnect the signals
  4856. try:
  4857. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4858. disconnect(self.on_excellon_format_changed)
  4859. except TypeError:
  4860. pass
  4861. try:
  4862. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4863. disconnect(self.on_excellon_format_changed)
  4864. except TypeError:
  4865. pass
  4866. try:
  4867. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4868. disconnect(self.on_excellon_format_changed)
  4869. except TypeError:
  4870. pass
  4871. try:
  4872. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4873. disconnect(self.on_excellon_format_changed)
  4874. except TypeError:
  4875. pass
  4876. try:
  4877. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4878. disconnect(self.on_excellon_zeros_changed)
  4879. except TypeError:
  4880. pass
  4881. try:
  4882. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4883. disconnect(self.on_excellon_zeros_changed)
  4884. except TypeError:
  4885. pass
  4886. def on_excellon_format_changed(self):
  4887. """
  4888. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4889. :return: None
  4890. """
  4891. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4892. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4893. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4894. )
  4895. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4896. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4897. )
  4898. else:
  4899. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4900. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4901. )
  4902. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4903. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4904. )
  4905. def on_excellon_zeros_changed(self):
  4906. """
  4907. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4908. :return: None
  4909. """
  4910. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4911. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4912. )
  4913. def on_excellon_units_changed(self):
  4914. """
  4915. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4916. :return: None
  4917. """
  4918. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4919. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4920. )
  4921. self.on_excellon_format_changed()
  4922. # Setting plot colors handlers
  4923. def on_pf_color_entry(self):
  4924. self.defaults['global_plot_fill'] = \
  4925. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4926. self.defaults['global_plot_fill'][7:9]
  4927. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4928. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4929. def on_pf_color_button(self):
  4930. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4931. c_dialog = QtWidgets.QColorDialog()
  4932. plot_fill_color = c_dialog.getColor(initial=current_color)
  4933. if plot_fill_color.isValid() is False:
  4934. return
  4935. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4936. "background-color:%s" % str(plot_fill_color.name()))
  4937. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4938. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4939. self.defaults['global_plot_fill'] = new_val
  4940. def on_pf_color_spinner(self):
  4941. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4942. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4943. self.defaults['global_plot_fill'] = \
  4944. self.defaults['global_plot_fill'][:7] + \
  4945. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4946. self.defaults['global_plot_line'] = \
  4947. self.defaults['global_plot_line'][:7] + \
  4948. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4949. def on_pf_color_slider(self):
  4950. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4951. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4952. def on_pl_color_entry(self):
  4953. self.defaults['global_plot_line'] = \
  4954. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4955. self.defaults['global_plot_line'][7:9]
  4956. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4957. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4958. def on_pl_color_button(self):
  4959. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4960. # print(current_color)
  4961. c_dialog = QtWidgets.QColorDialog()
  4962. plot_line_color = c_dialog.getColor(initial=current_color)
  4963. if plot_line_color.isValid() is False:
  4964. return
  4965. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4966. "background-color:%s" % str(plot_line_color.name()))
  4967. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4968. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4969. self.defaults['global_plot_line'] = new_val_line
  4970. # Setting selection colors (left - right) handlers
  4971. def on_sf_color_entry(self):
  4972. self.defaults['global_sel_fill'] = \
  4973. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4974. self.defaults['global_sel_fill'][7:9]
  4975. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4976. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4977. def on_sf_color_button(self):
  4978. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4979. c_dialog = QtWidgets.QColorDialog()
  4980. plot_fill_color = c_dialog.getColor(initial=current_color)
  4981. if plot_fill_color.isValid() is False:
  4982. return
  4983. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4984. "background-color:%s" % str(plot_fill_color.name()))
  4985. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4986. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4987. self.defaults['global_sel_fill'] = new_val
  4988. def on_sf_color_spinner(self):
  4989. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4990. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4991. self.defaults['global_sel_fill'] = \
  4992. self.defaults['global_sel_fill'][:7] + \
  4993. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4994. self.defaults['global_sel_line'] = \
  4995. self.defaults['global_sel_line'][:7] + \
  4996. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4997. def on_sf_color_slider(self):
  4998. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4999. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5000. def on_sl_color_entry(self):
  5001. self.defaults['global_sel_line'] = \
  5002. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5003. self.defaults['global_sel_line'][7:9]
  5004. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5005. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5006. def on_sl_color_button(self):
  5007. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5008. c_dialog = QtWidgets.QColorDialog()
  5009. plot_line_color = c_dialog.getColor(initial=current_color)
  5010. if plot_line_color.isValid() is False:
  5011. return
  5012. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5013. "background-color:%s" % str(plot_line_color.name()))
  5014. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5015. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5016. self.defaults['global_sel_line'] = new_val_line
  5017. # Setting selection colors (right - left) handlers
  5018. def on_alt_sf_color_entry(self):
  5019. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5020. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5021. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5022. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5023. def on_alt_sf_color_button(self):
  5024. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5025. c_dialog = QtWidgets.QColorDialog()
  5026. plot_fill_color = c_dialog.getColor(initial=current_color)
  5027. if plot_fill_color.isValid() is False:
  5028. return
  5029. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5030. "background-color:%s" % str(plot_fill_color.name()))
  5031. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5032. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5033. self.defaults['global_alt_sel_fill'] = new_val
  5034. def on_alt_sf_color_spinner(self):
  5035. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5036. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5037. self.defaults['global_alt_sel_fill'] = \
  5038. self.defaults['global_alt_sel_fill'][:7] + \
  5039. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5040. self.defaults['global_alt_sel_line'] = \
  5041. self.defaults['global_alt_sel_line'][:7] + \
  5042. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5043. def on_alt_sf_color_slider(self):
  5044. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5045. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5046. def on_alt_sl_color_entry(self):
  5047. self.defaults['global_alt_sel_line'] = \
  5048. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5049. self.defaults['global_alt_sel_line'][7:9]
  5050. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5051. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5052. def on_alt_sl_color_button(self):
  5053. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5054. c_dialog = QtWidgets.QColorDialog()
  5055. plot_line_color = c_dialog.getColor(initial=current_color)
  5056. if plot_line_color.isValid() is False:
  5057. return
  5058. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5059. "background-color:%s" % str(plot_line_color.name()))
  5060. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5061. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5062. self.defaults['global_alt_sel_line'] = new_val_line
  5063. # Setting Editor colors
  5064. def on_draw_color_entry(self):
  5065. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5066. .draw_color_entry.get_value()
  5067. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5068. "background-color:%s" % str(self.defaults['global_draw_color']))
  5069. def on_draw_color_button(self):
  5070. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5071. c_dialog = QtWidgets.QColorDialog()
  5072. draw_color = c_dialog.getColor(initial=current_color)
  5073. if draw_color.isValid() is False:
  5074. return
  5075. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5076. "background-color:%s" % str(draw_color.name()))
  5077. new_val = str(draw_color.name())
  5078. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5079. self.defaults['global_draw_color'] = new_val
  5080. def on_sel_draw_color_entry(self):
  5081. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5082. .sel_draw_color_entry.get_value()
  5083. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5084. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5085. def on_sel_draw_color_button(self):
  5086. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5087. c_dialog = QtWidgets.QColorDialog()
  5088. sel_draw_color = c_dialog.getColor(initial=current_color)
  5089. if sel_draw_color.isValid() is False:
  5090. return
  5091. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5092. "background-color:%s" % str(sel_draw_color.name()))
  5093. new_val_sel = str(sel_draw_color.name())
  5094. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5095. self.defaults['global_sel_draw_color'] = new_val_sel
  5096. def on_proj_color_entry(self):
  5097. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5098. .proj_color_entry.get_value()
  5099. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5100. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5101. def on_proj_color_button(self):
  5102. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5103. c_dialog = QtWidgets.QColorDialog()
  5104. proj_color = c_dialog.getColor(initial=current_color)
  5105. if proj_color.isValid() is False:
  5106. return
  5107. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5108. "background-color:%s" % str(proj_color.name()))
  5109. new_val_sel = str(proj_color.name())
  5110. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5111. self.defaults['global_proj_item_color'] = new_val_sel
  5112. def on_proj_color_dis_entry(self):
  5113. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5114. .proj_color_dis_entry.get_value()
  5115. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5116. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5117. def on_proj_color_dis_button(self):
  5118. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5119. c_dialog = QtWidgets.QColorDialog()
  5120. proj_color = c_dialog.getColor(initial=current_color)
  5121. if proj_color.isValid() is False:
  5122. return
  5123. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5124. "background-color:%s" % str(proj_color.name()))
  5125. new_val_sel = str(proj_color.name())
  5126. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5127. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5128. def on_annotation_fontcolor_entry(self):
  5129. self.defaults['cncjob_annotation_fontcolor'] = \
  5130. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5131. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5132. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5133. def on_annotation_fontcolor_button(self):
  5134. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5135. c_dialog = QtWidgets.QColorDialog()
  5136. annotation_color = c_dialog.getColor(initial=current_color)
  5137. if annotation_color.isValid() is False:
  5138. return
  5139. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5140. "background-color:%s" % str(annotation_color.name()))
  5141. new_val_sel = str(annotation_color.name())
  5142. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5143. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5144. def on_film_color_entry(self):
  5145. self.defaults['tools_film_color'] = \
  5146. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5147. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5148. "background-color:%s" % str(self.defaults['tools_film_color']))
  5149. def on_film_color_button(self):
  5150. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5151. c_dialog = QtWidgets.QColorDialog()
  5152. film_color = c_dialog.getColor(initial=current_color)
  5153. if film_color.isValid() is False:
  5154. return
  5155. # if new color is different then mark that the Preferences are changed
  5156. if film_color != current_color:
  5157. self.on_preferences_edited()
  5158. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5159. "background-color:%s" % str(film_color.name()))
  5160. new_val_sel = str(film_color.name())
  5161. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5162. self.defaults['tools_film_color'] = new_val_sel
  5163. def on_splash_changed(self, state):
  5164. settings = QSettings("Open Source", "FlatCAM")
  5165. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5166. # This will write the setting to the platform specific storage.
  5167. del settings
  5168. def on_notebook_tab_rmb_click(self, checked):
  5169. self.ui.notebook.set_detachable(val=checked)
  5170. self.defaults["global_tabs_detachable"] = checked
  5171. self.ui.plot_tab_area.set_detachable(val=checked)
  5172. self.defaults["global_tabs_detachable"] = checked
  5173. def on_deselect_all(self):
  5174. self.collection.set_all_inactive()
  5175. self.delete_selection_shape()
  5176. def on_workspace_modified(self):
  5177. self.save_defaults(silent=True)
  5178. self.plotcanvas.draw_workspace()
  5179. def on_workspace(self):
  5180. self.report_usage("on_workspace()")
  5181. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5182. self.plotcanvas.restore_workspace()
  5183. else:
  5184. self.plotcanvas.delete_workspace()
  5185. self.save_defaults(silent=True)
  5186. def on_workspace_menu(self):
  5187. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5188. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5189. else:
  5190. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5191. self.on_workspace()
  5192. def on_layout(self, index=None, lay=None):
  5193. self.report_usage("on_layout()")
  5194. if lay:
  5195. current_layout = lay
  5196. else:
  5197. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5198. settings = QSettings("Open Source", "FlatCAM")
  5199. settings.setValue('layout', current_layout)
  5200. # This will write the setting to the platform specific storage.
  5201. del settings
  5202. # first remove the toolbars:
  5203. try:
  5204. self.ui.removeToolBar(self.ui.toolbarfile)
  5205. self.ui.removeToolBar(self.ui.toolbargeo)
  5206. self.ui.removeToolBar(self.ui.toolbarview)
  5207. self.ui.removeToolBar(self.ui.toolbarshell)
  5208. self.ui.removeToolBar(self.ui.toolbartools)
  5209. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5210. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5211. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5212. self.ui.removeToolBar(self.ui.snap_toolbar)
  5213. self.ui.removeToolBar(self.ui.toolbarshell)
  5214. except Exception as e:
  5215. pass
  5216. if current_layout == 'standard':
  5217. # ## TOOLBAR INSTALLATION # ##
  5218. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5219. self.ui.toolbarfile.setObjectName('File_TB')
  5220. self.ui.addToolBar(self.ui.toolbarfile)
  5221. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5222. self.ui.toolbargeo.setObjectName('Edit_TB')
  5223. self.ui.addToolBar(self.ui.toolbargeo)
  5224. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5225. self.ui.toolbarview.setObjectName('View_TB')
  5226. self.ui.addToolBar(self.ui.toolbarview)
  5227. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5228. self.ui.toolbarshell.setObjectName('Shell_TB')
  5229. self.ui.addToolBar(self.ui.toolbarshell)
  5230. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5231. self.ui.toolbartools.setObjectName('Tools_TB')
  5232. self.ui.addToolBar(self.ui.toolbartools)
  5233. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5234. # self.ui.exc_edit_toolbar.setVisible(False)
  5235. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5236. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5237. self.ui.addToolBarBreak()
  5238. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5239. # self.ui.geo_edit_toolbar.setVisible(False)
  5240. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5241. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5242. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5243. # self.ui.grb_edit_toolbar.setVisible(False)
  5244. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5245. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5246. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5247. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5248. # self.ui.snap_toolbar.setMaximumHeight(30)
  5249. self.ui.addToolBar(self.ui.snap_toolbar)
  5250. self.ui.corner_snap_btn.setVisible(False)
  5251. self.ui.snap_magnet.setVisible(False)
  5252. elif current_layout == 'compact':
  5253. # ## TOOLBAR INSTALLATION # ##
  5254. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5255. self.ui.toolbarfile.setObjectName('File_TB')
  5256. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5257. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5258. self.ui.toolbargeo.setObjectName('Edit_TB')
  5259. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5260. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5261. self.ui.toolbarshell.setObjectName('Shell_TB')
  5262. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5263. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5264. self.ui.toolbartools.setObjectName('Tools_TB')
  5265. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5266. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5267. # self.ui.geo_edit_toolbar.setVisible(False)
  5268. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5269. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5270. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5271. self.ui.toolbarview.setObjectName('View_TB')
  5272. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5273. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5274. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5275. # self.ui.grb_edit_toolbar.setVisible(False)
  5276. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5277. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5278. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5279. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5280. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5281. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5282. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5283. self.ui.snap_toolbar.setMaximumHeight(30)
  5284. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5285. self.ui.corner_snap_btn.setVisible(True)
  5286. self.ui.snap_magnet.setVisible(True)
  5287. # add all the actions to the toolbars
  5288. self.ui.populate_toolbars()
  5289. # reconnect all the signals to the toolbar actions
  5290. self.connect_toolbar_signals()
  5291. self.ui.grid_snap_btn.setChecked(True)
  5292. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5293. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5294. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5295. self.ui.grid_gap_link_cb.setChecked(True)
  5296. def on_cnc_custom_parameters(self, signal_text):
  5297. if signal_text == 'Parameters':
  5298. return
  5299. else:
  5300. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5301. def on_save_button(self):
  5302. log.debug("App.on_save_button() --> Saving preferences to file.")
  5303. self.preferences_changed_flag = False
  5304. self.save_defaults(silent=False)
  5305. # load the defaults so they are updated into the app
  5306. self.load_defaults(filename='current_defaults')
  5307. # Re-fresh project options
  5308. self.on_options_app2project()
  5309. settings = QSettings("Open Source", "FlatCAM")
  5310. # save the notebook font size
  5311. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5312. settings.setValue('notebook_font_size', fsize)
  5313. # save the axis font size
  5314. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5315. settings.setValue('axis_font_size', g_fsize)
  5316. # save the textbox font size
  5317. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5318. settings.setValue('textbox_font_size', tb_fsize)
  5319. # This will write the setting to the platform specific storage.
  5320. del settings
  5321. def handlePrint(self):
  5322. self.report_usage("handlePrint()")
  5323. dialog = QtPrintSupport.QPrintDialog()
  5324. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5325. self.ui.code_editor.document().print_(dialog.printer())
  5326. def handlePreview(self):
  5327. self.report_usage("handlePreview()")
  5328. dialog = QtPrintSupport.QPrintPreviewDialog()
  5329. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5330. dialog.exec_()
  5331. def handleTextChanged(self):
  5332. # enable = not self.ui.code_editor.document().isEmpty()
  5333. # self.ui.buttonPrint.setEnabled(enable)
  5334. # self.ui.buttonPreview.setEnabled(enable)
  5335. pass
  5336. def handleOpen(self, filt=None):
  5337. self.report_usage("handleOpen()")
  5338. if filt:
  5339. _filter_ = filt
  5340. else:
  5341. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5342. "All Files (*.*)"
  5343. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5344. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5345. if path:
  5346. file = QtCore.QFile(path)
  5347. if file.open(QtCore.QIODevice.ReadOnly):
  5348. stream = QtCore.QTextStream(file)
  5349. self.gcode_edited = stream.readAll()
  5350. self.ui.code_editor.setPlainText(self.gcode_edited)
  5351. file.close()
  5352. def handleSaveGCode(self, name=None, filt=None):
  5353. self.report_usage("handleSaveGCode()")
  5354. if filt:
  5355. _filter_ = filt
  5356. else:
  5357. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5358. "All Files (*.*)"
  5359. if name:
  5360. obj_name = name
  5361. else:
  5362. try:
  5363. obj_name = self.collection.get_active().options['name']
  5364. except AttributeError:
  5365. obj_name = 'file'
  5366. if filt is None:
  5367. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5368. try:
  5369. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5370. caption=_("Export G-Code ..."),
  5371. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5372. filter=_filter_
  5373. )[0])
  5374. except TypeError:
  5375. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5376. if filename == "":
  5377. self.inform.emit('[WARNING_NOTCL] %s' %
  5378. _("Export Code cancelled."))
  5379. return
  5380. else:
  5381. try:
  5382. my_gcode = self.ui.code_editor.toPlainText()
  5383. with open(filename, 'w') as f:
  5384. for line in my_gcode:
  5385. f.write(line)
  5386. except FileNotFoundError:
  5387. self.inform.emit('[WARNING] %s' %
  5388. _("No such file or directory"))
  5389. return
  5390. except PermissionError:
  5391. self.inform.emit('[WARNING] %s' %
  5392. _("Permission denied, saving not possible.\n"
  5393. "Most likely another app is holding the file open and not accessible."))
  5394. return
  5395. # Just for adding it to the recent files list.
  5396. if self.defaults["global_open_style"] is False:
  5397. self.file_opened.emit("cncjob", filename)
  5398. self.file_saved.emit("cncjob", filename)
  5399. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5400. def handleFindGCode(self):
  5401. self.report_usage("handleFindGCode()")
  5402. flags = QtGui.QTextDocument.FindCaseSensitively
  5403. text_to_be_found = self.ui.entryFind.get_value()
  5404. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5405. if r is False:
  5406. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5407. def handleReplaceGCode(self):
  5408. self.report_usage("handleReplaceGCode()")
  5409. old = self.ui.entryFind.get_value()
  5410. new = self.ui.entryReplace.get_value()
  5411. if self.ui.sel_all_cb.isChecked():
  5412. while True:
  5413. cursor = self.ui.code_editor.textCursor()
  5414. cursor.beginEditBlock()
  5415. flags = QtGui.QTextDocument.FindCaseSensitively
  5416. # self.ui.editor is the QPlainTextEdit
  5417. r = self.ui.code_editor.find(str(old), flags)
  5418. if r:
  5419. qc = self.ui.code_editor.textCursor()
  5420. if qc.hasSelection():
  5421. qc.insertText(new)
  5422. else:
  5423. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5424. break
  5425. # Mark end of undo block
  5426. cursor.endEditBlock()
  5427. else:
  5428. cursor = self.ui.code_editor.textCursor()
  5429. cursor.beginEditBlock()
  5430. qc = self.ui.code_editor.textCursor()
  5431. if qc.hasSelection():
  5432. qc.insertText(new)
  5433. # Mark end of undo block
  5434. cursor.endEditBlock()
  5435. def handleRunCode(self):
  5436. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5437. # tries to print on a hidden widget, therefore show the dock if hidden
  5438. if self.ui.shell_dock.isHidden():
  5439. self.ui.shell_dock.show()
  5440. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5441. # self.shell._sysShell.exec_command(script_code)
  5442. old_line = ''
  5443. for tcl_command_line in self.script_code.splitlines():
  5444. # do not process lines starting with '#' = comment and empty lines
  5445. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5446. # id FlatCAM is run in Windows then replace all the slashes with
  5447. # the UNIX style slash that TCL understands
  5448. if sys.platform == 'win32':
  5449. if "open" in tcl_command_line:
  5450. tcl_command_line = tcl_command_line.replace('\\', '/')
  5451. if old_line != '':
  5452. new_command = old_line + tcl_command_line + '\n'
  5453. else:
  5454. new_command = tcl_command_line
  5455. # execute the actual Tcl command
  5456. try:
  5457. self.shell.open_proccessing() # Disables input box.
  5458. result = self.tcl.eval(str(new_command))
  5459. if result != 'None':
  5460. self.shell.append_output(result + '\n')
  5461. old_line = ''
  5462. except tk.TclError:
  5463. old_line = old_line + tcl_command_line + '\n'
  5464. except Exception as e:
  5465. log.debug("App.handleRunCode() --> %s" % str(e))
  5466. if old_line != '':
  5467. # it means that the script finished with an error
  5468. result = self.tcl.eval("set errorInfo")
  5469. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5470. self.shell.append_error('ERROR: ' + result + '\n')
  5471. self.shell.close_proccessing()
  5472. def on_tool_add_keypress(self):
  5473. # ## Current application units in Upper Case
  5474. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5475. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5476. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5477. if notebook_widget_name == 'selected_tab':
  5478. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5479. # Tool add works for Geometry only if Advanced is True in Preferences
  5480. if self.defaults["global_app_level"] == 'a':
  5481. tool_add_popup = FCInputDialog(title="New Tool ...",
  5482. text='Enter a Tool Diameter:',
  5483. min=0.0000, max=99.9999, decimals=4)
  5484. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5485. val, ok = tool_add_popup.get_value()
  5486. if ok:
  5487. if float(val) == 0:
  5488. self.inform.emit('[WARNING_NOTCL] %s' %
  5489. _("Please enter a tool diameter with non-zero value, in Float format."))
  5490. return
  5491. self.collection.get_active().on_tool_add(dia=float(val))
  5492. else:
  5493. self.inform.emit('[WARNING_NOTCL] %s...' %
  5494. _("Adding Tool cancelled"))
  5495. else:
  5496. msgbox = QtWidgets.QMessageBox()
  5497. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5498. "Go to Preferences -> General - Show Advanced Options."))
  5499. msgbox.setWindowTitle("Tool adding ...")
  5500. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5501. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5502. msgbox.setDefaultButton(bt_ok)
  5503. msgbox.exec_()
  5504. # work only if the notebook tab on focus is the Tools_Tab
  5505. if notebook_widget_name == 'tool_tab':
  5506. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5507. tool_add_popup = FCInputDialog(title="New Tool ...",
  5508. text='Enter a Tool Diameter:',
  5509. min=0.0000, max=99.9999, decimals=4)
  5510. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5511. val, ok = tool_add_popup.get_value()
  5512. # and only if the tool is NCC Tool
  5513. if tool_widget == self.ncclear_tool.toolName:
  5514. if ok:
  5515. if float(val) == 0:
  5516. self.inform.emit('[WARNING_NOTCL] %s' %
  5517. _("Please enter a tool diameter with non-zero value, in Float format."))
  5518. return
  5519. self.ncclear_tool.on_tool_add(dia=float(val))
  5520. else:
  5521. self.inform.emit('[WARNING_NOTCL] %s...' %
  5522. _("Adding Tool cancelled"))
  5523. # and only if the tool is Paint Area Tool
  5524. elif tool_widget == self.paint_tool.toolName:
  5525. if ok:
  5526. if float(val) == 0:
  5527. self.inform.emit('[WARNING_NOTCL] %s' %
  5528. _("Please enter a tool diameter with non-zero value, in Float format."))
  5529. return
  5530. self.paint_tool.on_tool_add(dia=float(val))
  5531. else:
  5532. self.inform.emit('[WARNING_NOTCL] %s...' %
  5533. _("Adding Tool cancelled"))
  5534. # and only if the tool is Solder Paste Dispensing Tool
  5535. elif tool_widget == self.paste_tool.toolName:
  5536. if ok:
  5537. if float(val) == 0:
  5538. self.inform.emit('[WARNING_NOTCL] %s' %
  5539. _("Please enter a tool diameter with non-zero value, in Float format."))
  5540. return
  5541. self.paste_tool.on_tool_add(dia=float(val))
  5542. else:
  5543. self.inform.emit('[WARNING_NOTCL] %s...' %
  5544. _("Adding Tool cancelled"))
  5545. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5546. # See description bellow.
  5547. def on_delete_keypress(self):
  5548. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5549. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5550. if notebook_widget_name == 'selected_tab':
  5551. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5552. self.collection.get_active().on_tool_delete()
  5553. # work only if the notebook tab on focus is the Tools_Tab
  5554. elif notebook_widget_name == 'tool_tab':
  5555. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5556. # and only if the tool is NCC Tool
  5557. if tool_widget == self.ncclear_tool.toolName:
  5558. self.ncclear_tool.on_tool_delete()
  5559. # and only if the tool is Paint Tool
  5560. elif tool_widget == self.paint_tool.toolName:
  5561. self.paint_tool.on_tool_delete()
  5562. # and only if the tool is Solder Paste Dispensing Tool
  5563. elif tool_widget == self.paste_tool.toolName:
  5564. self.paste_tool.on_tool_delete()
  5565. else:
  5566. self.on_delete()
  5567. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5568. # some screens you have to be careful where you hover with your mouse.
  5569. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5570. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5571. # Complicated, I know :)
  5572. def on_delete(self):
  5573. """
  5574. Delete the currently selected FlatCAMObjs.
  5575. :return: None
  5576. """
  5577. self.report_usage("on_delete()")
  5578. response = None
  5579. bt_ok = None
  5580. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5581. # a geometry object before we update it.
  5582. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5583. and self.grb_editor.editor_active is False:
  5584. if self.defaults["global_delete_confirmation"] is True:
  5585. msgbox = QtWidgets.QMessageBox()
  5586. msgbox.setWindowTitle(_("Delete objects"))
  5587. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5588. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5589. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5590. "the selected objects?"))
  5591. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5592. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5593. msgbox.setDefaultButton(bt_ok)
  5594. msgbox.exec_()
  5595. response = msgbox.clickedButton()
  5596. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5597. if self.collection.get_active():
  5598. self.log.debug("App.on_delete()")
  5599. while self.collection.get_active():
  5600. obj_active = self.collection.get_active()
  5601. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5602. if isinstance(obj_active, FlatCAMGerber):
  5603. for el in obj_active.mark_shapes:
  5604. obj_active.mark_shapes[el].clear(update=True)
  5605. obj_active.mark_shapes[el].enabled = False
  5606. # obj_active.mark_shapes[el] = None
  5607. del el
  5608. elif isinstance(obj_active, FlatCAMCNCjob):
  5609. try:
  5610. obj_active.annotation.clear(update=True)
  5611. obj_active.annotation.enabled = False
  5612. except AttributeError:
  5613. pass
  5614. self.delete_first_selected()
  5615. self.inform.emit('%s...' %
  5616. _("Object(s) deleted"))
  5617. # make sure that the selection shape is deleted, too
  5618. self.delete_selection_shape()
  5619. else:
  5620. self.inform.emit(_("Failed. No object(s) selected..."))
  5621. else:
  5622. self.inform.emit(_("Save the work in Editor and try again ..."))
  5623. def delete_first_selected(self):
  5624. # Keep this for later
  5625. try:
  5626. sel_obj = self.collection.get_active()
  5627. name = sel_obj.options["name"]
  5628. isPlotted = sel_obj.options["plot"]
  5629. except AttributeError:
  5630. self.log.debug("Nothing selected for deletion")
  5631. return
  5632. if self.is_legacy is True:
  5633. # Remove plot only if the object was plotted otherwise delaxes will fail
  5634. if isPlotted:
  5635. try:
  5636. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5637. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5638. except Exception as e:
  5639. log.debug("App.delete_first_selected() --> %s" % str(e))
  5640. self.plotcanvas.auto_adjust_axes()
  5641. # Remove from dictionary
  5642. self.collection.delete_active()
  5643. # Clear form
  5644. self.setup_component_editor()
  5645. self.inform.emit('%s: %s' %
  5646. (_("Object deleted"), name))
  5647. def on_set_origin(self):
  5648. """
  5649. Set the origin to the left mouse click position
  5650. :return: None
  5651. """
  5652. # display the message for the user
  5653. # and ask him to click on the desired position
  5654. self.report_usage("on_set_origin()")
  5655. def origin_replot():
  5656. def worker_task():
  5657. with self.proc_container.new('%s...' % _("Plotting")):
  5658. for obj in self.collection.get_list():
  5659. obj.plot()
  5660. self.plotcanvas.fit_view()
  5661. if self.is_legacy:
  5662. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5663. else:
  5664. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5665. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5666. self.inform.emit(_('Click to set the origin ...'))
  5667. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5668. # first disconnect it as it may have been used by something else
  5669. try:
  5670. self.replot_signal.disconnect()
  5671. except TypeError:
  5672. pass
  5673. self.replot_signal[list].connect(origin_replot)
  5674. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5675. """
  5676. :param event:
  5677. :param location:
  5678. :param noplot:
  5679. :param use_thread:
  5680. :return:
  5681. """
  5682. noplot_sig = noplot
  5683. def worker_task():
  5684. with self.proc_container.new(_("Setting Origin...")):
  5685. for obj in self.collection.get_list():
  5686. obj.offset((x, y))
  5687. self.object_changed.emit(obj)
  5688. # Update the object bounding box options
  5689. a, b, c, d = obj.bounds()
  5690. obj.options['xmin'] = a
  5691. obj.options['ymin'] = b
  5692. obj.options['xmax'] = c
  5693. obj.options['ymax'] = d
  5694. self.inform.emit('[success] %s...' %
  5695. _('Origin set'))
  5696. if noplot_sig is False:
  5697. self.replot_signal.emit([])
  5698. if location is not None:
  5699. if len(location) != 2:
  5700. self.inform.emit('[ERROR_NOTCL] %s...' %
  5701. _("Origin coordinates specified but incomplete."))
  5702. return 'fail'
  5703. x, y = location
  5704. if use_thread is True:
  5705. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5706. else:
  5707. worker_task()
  5708. self.should_we_save = True
  5709. return
  5710. if event.button == 1:
  5711. if self.is_legacy is False:
  5712. event_pos = event.pos
  5713. else:
  5714. event_pos = (event.xdata, event.ydata)
  5715. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5716. if self.grid_status() == True:
  5717. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5718. else:
  5719. pos = pos_canvas
  5720. x = 0 - pos[0]
  5721. y = 0 - pos[1]
  5722. if use_thread is True:
  5723. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5724. else:
  5725. worker_task()
  5726. self.should_we_save = True
  5727. def on_jump_to(self, custom_location=None, fit_center=True):
  5728. """
  5729. Jump to a location by setting the mouse cursor location
  5730. :return:
  5731. """
  5732. self.report_usage("on_jump_to()")
  5733. if self.is_legacy is True:
  5734. self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5735. return
  5736. if not custom_location:
  5737. dia_box = Dialog_box(title=_("Jump to ..."),
  5738. label=_("Enter the coordinates in format X,Y:"),
  5739. icon=QtGui.QIcon('share/jump_to16.png'))
  5740. if dia_box.ok is True:
  5741. try:
  5742. location = eval(dia_box.location)
  5743. if not isinstance(location, tuple):
  5744. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5745. return
  5746. except:
  5747. return
  5748. else:
  5749. return
  5750. else:
  5751. location = custom_location
  5752. if fit_center:
  5753. if self.is_legacy is False:
  5754. self.plotcanvas.fit_center(loc=location)
  5755. else:
  5756. pass
  5757. # self.plotcanvas.fit_view()
  5758. cursor = QtGui.QCursor()
  5759. if self.is_legacy is False:
  5760. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5761. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5762. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5763. else:
  5764. # the origin finding works but not mapping the location to pixels
  5765. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5766. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5767. x0, y0 = x0 + self.plotcanvas.axes.transData.transform((0, 0))[0], y0 - \
  5768. self.plotcanvas.axes.transData.transform((0, 0))[1]
  5769. loc = self.plotcanvas.axes.transData.transform(location)
  5770. cursor.setPos(x0 + loc[0]/50, y0 - loc[1]/50)
  5771. self.inform.emit('[success] %s' %
  5772. _("Done."))
  5773. return location
  5774. def on_copy_object(self):
  5775. self.report_usage("on_copy_object()")
  5776. def initialize(obj_init, app):
  5777. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5778. try:
  5779. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5780. except AttributeError:
  5781. pass
  5782. try:
  5783. obj_init.apertures = deepcopy(obj.apertures)
  5784. except AttributeError:
  5785. pass
  5786. try:
  5787. if obj.tools:
  5788. obj_init.tools = deepcopy(obj.tools)
  5789. except Exception as e:
  5790. log.debug("App.on_copy_object() --> %s" % str(e))
  5791. def initialize_excellon(obj_init, app):
  5792. obj_init.tools = deepcopy(obj.tools)
  5793. # drills are offset, so they need to be deep copied
  5794. obj_init.drills = deepcopy(obj.drills)
  5795. # slots are offset, so they need to be deep copied
  5796. obj_init.slots = deepcopy(obj.slots)
  5797. obj_init.create_geometry()
  5798. for obj in self.collection.get_selected():
  5799. obj_name = obj.options["name"]
  5800. try:
  5801. if isinstance(obj, FlatCAMExcellon):
  5802. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5803. elif isinstance(obj, FlatCAMGerber):
  5804. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5805. elif isinstance(obj, FlatCAMGeometry):
  5806. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5807. except Exception as e:
  5808. return "Operation failed: %s" % str(e)
  5809. def on_copy_object2(self, custom_name):
  5810. def initialize_geometry(obj_init, app):
  5811. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5812. try:
  5813. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5814. except AttributeError:
  5815. pass
  5816. try:
  5817. obj_init.apertures = deepcopy(obj.apertures)
  5818. except AttributeError:
  5819. pass
  5820. try:
  5821. if obj.tools:
  5822. obj_init.tools = deepcopy(obj.tools)
  5823. except Exception as e:
  5824. log.debug("on_copy_object2() --> %s" % str(e))
  5825. def initialize_gerber(obj_init, app):
  5826. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5827. obj_init.apertures = deepcopy(obj.apertures)
  5828. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5829. def initialize_excellon(obj_init, app):
  5830. obj_init.tools = deepcopy(obj.tools)
  5831. # drills are offset, so they need to be deep copied
  5832. obj_init.drills = deepcopy(obj.drills)
  5833. # slots are offset, so they need to be deep copied
  5834. obj_init.slots = deepcopy(obj.slots)
  5835. obj_init.create_geometry()
  5836. for obj in self.collection.get_selected():
  5837. obj_name = obj.options["name"]
  5838. try:
  5839. if isinstance(obj, FlatCAMExcellon):
  5840. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5841. elif isinstance(obj, FlatCAMGerber):
  5842. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5843. elif isinstance(obj, FlatCAMGeometry):
  5844. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5845. except Exception as e:
  5846. return "Operation failed: %s" % str(e)
  5847. def on_rename_object(self, text):
  5848. self.report_usage("on_rename_object()")
  5849. named_obj = self.collection.get_active()
  5850. for obj in named_obj:
  5851. if obj is list:
  5852. self.on_rename_object(text)
  5853. else:
  5854. try:
  5855. obj.options['name'] = text
  5856. except Exception as e:
  5857. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5858. def convert_any2geo(self):
  5859. self.report_usage("convert_any2geo()")
  5860. def initialize(obj_init, app):
  5861. obj_init.solid_geometry = obj.solid_geometry
  5862. try:
  5863. obj_init.follow_geometry = obj.follow_geometry
  5864. except AttributeError:
  5865. pass
  5866. try:
  5867. obj_init.apertures = obj.apertures
  5868. except AttributeError:
  5869. pass
  5870. try:
  5871. if obj.tools:
  5872. obj_init.tools = obj.tools
  5873. except AttributeError:
  5874. pass
  5875. def initialize_excellon(obj_init, app):
  5876. # objs = self.collection.get_selected()
  5877. # FlatCAMGeometry.merge(objs, obj)
  5878. solid_geo = []
  5879. for tool in obj.tools:
  5880. for geo in obj.tools[tool]['solid_geometry']:
  5881. solid_geo.append(geo)
  5882. obj_init.solid_geometry = deepcopy(solid_geo)
  5883. if not self.collection.get_selected():
  5884. log.warning("App.convert_any2geo --> No object selected")
  5885. self.inform.emit('[WARNING_NOTCL] %s' %
  5886. _("No object is selected. Select an object and try again."))
  5887. return
  5888. for obj in self.collection.get_selected():
  5889. obj_name = obj.options["name"]
  5890. try:
  5891. if isinstance(obj, FlatCAMExcellon):
  5892. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5893. else:
  5894. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5895. except Exception as e:
  5896. return "Operation failed: %s" % str(e)
  5897. def convert_any2gerber(self):
  5898. self.report_usage("convert_any2gerber()")
  5899. def initialize_geometry(obj_init, app):
  5900. apertures = {}
  5901. apid = 0
  5902. apertures[str(apid)] = {}
  5903. apertures[str(apid)]['geometry'] = []
  5904. for obj_orig in obj.solid_geometry:
  5905. new_elem = dict()
  5906. new_elem['solid'] = obj_orig
  5907. new_elem['follow'] = obj_orig.exterior
  5908. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5909. apertures[str(apid)]['size'] = 0.0
  5910. apertures[str(apid)]['type'] = 'C'
  5911. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5912. obj_init.apertures = deepcopy(apertures)
  5913. def initialize_excellon(obj_init, app):
  5914. apertures = {}
  5915. apid = 10
  5916. for tool in obj.tools:
  5917. apertures[str(apid)] = {}
  5918. apertures[str(apid)]['geometry'] = []
  5919. for geo in obj.tools[tool]['solid_geometry']:
  5920. new_el = dict()
  5921. new_el['solid'] = geo
  5922. new_el['follow'] = geo.exterior
  5923. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5924. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5925. apertures[str(apid)]['type'] = 'C'
  5926. apid += 1
  5927. # create solid_geometry
  5928. solid_geometry = []
  5929. for apid in apertures:
  5930. for geo_el in apertures[apid]['geometry']:
  5931. solid_geometry.append(geo_el['solid'])
  5932. solid_geometry = MultiPolygon(solid_geometry)
  5933. solid_geometry = solid_geometry.buffer(0.0000001)
  5934. obj_init.solid_geometry = deepcopy(solid_geometry)
  5935. obj_init.apertures = deepcopy(apertures)
  5936. # clear the working objects (perhaps not necessary due of Python GC)
  5937. apertures.clear()
  5938. if not self.collection.get_selected():
  5939. log.warning("App.convert_any2gerber --> No object selected")
  5940. self.inform.emit('[WARNING_NOTCL] %s' %
  5941. _("No object is selected. Select an object and try again."))
  5942. return
  5943. for obj in self.collection.get_selected():
  5944. obj_name = obj.options["name"]
  5945. try:
  5946. if isinstance(obj, FlatCAMExcellon):
  5947. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5948. elif isinstance(obj, FlatCAMGeometry):
  5949. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5950. else:
  5951. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5952. except Exception as e:
  5953. return "Operation failed: %s" % str(e)
  5954. def abort_all_tasks(self):
  5955. if self.abort_flag is False:
  5956. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5957. self.abort_flag = True
  5958. def app_is_idle(self):
  5959. if self.abort_flag:
  5960. self.inform.emit('[WARNING_NOTCL] %s' %
  5961. _("The current task was gracefully closed on user request..."))
  5962. self.abort_flag = False
  5963. def on_selectall(self):
  5964. self.report_usage("on_selectall()")
  5965. # delete the possible selection box around a possible selected object
  5966. self.delete_selection_shape()
  5967. for name in self.collection.get_names():
  5968. self.collection.set_active(name)
  5969. curr_sel_obj = self.collection.get_by_name(name)
  5970. # create the selection box around the selected object
  5971. if self.defaults['global_selection_shape'] is True:
  5972. self.draw_selection_shape(curr_sel_obj)
  5973. def on_preferences(self):
  5974. # add the tab if it was closed
  5975. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5976. # delete the absolute and relative position and messages in the infobar
  5977. self.ui.position_label.setText("")
  5978. self.ui.rel_position_label.setText("")
  5979. # Switch plot_area to preferences page
  5980. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5981. # self.ui.show()
  5982. # this disconnect() is done so the slot will be connected only once
  5983. try:
  5984. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5985. except (TypeError, AttributeError):
  5986. pass
  5987. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5988. # detect changes in the preferences
  5989. for idx in range(self.ui.pref_tab_area.count()):
  5990. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5991. try:
  5992. try:
  5993. tb.textEdited.disconnect(self.on_preferences_edited)
  5994. except (TypeError, AttributeError):
  5995. pass
  5996. tb.textEdited.connect(self.on_preferences_edited)
  5997. except AttributeError:
  5998. pass
  5999. try:
  6000. try:
  6001. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6002. except (TypeError, AttributeError):
  6003. pass
  6004. tb.modificationChanged.connect(self.on_preferences_edited)
  6005. except AttributeError:
  6006. pass
  6007. try:
  6008. try:
  6009. tb.toggled.disconnect(self.on_preferences_edited)
  6010. except (TypeError, AttributeError):
  6011. pass
  6012. tb.toggled.connect(self.on_preferences_edited)
  6013. except AttributeError:
  6014. pass
  6015. try:
  6016. try:
  6017. tb.valueChanged.disconnect(self.on_preferences_edited)
  6018. except (TypeError, AttributeError):
  6019. pass
  6020. tb.valueChanged.connect(self.on_preferences_edited)
  6021. except AttributeError:
  6022. pass
  6023. try:
  6024. try:
  6025. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6026. except (TypeError, AttributeError):
  6027. pass
  6028. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6029. except AttributeError:
  6030. pass
  6031. def on_preferences_edited(self):
  6032. self.inform.emit('[WARNING_NOTCL] %s' %
  6033. _("Preferences edited but not saved."))
  6034. self.preferences_changed_flag = True
  6035. def on_preferences_closed(self):
  6036. # disconnect
  6037. for idx in range(self.ui.pref_tab_area.count()):
  6038. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6039. try:
  6040. tb.textEdited.disconnect(self.on_preferences_edited)
  6041. except (TypeError, AttributeError):
  6042. pass
  6043. try:
  6044. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6045. except (TypeError, AttributeError):
  6046. pass
  6047. try:
  6048. tb.toggled.disconnect(self.on_preferences_edited)
  6049. except (TypeError, AttributeError):
  6050. pass
  6051. try:
  6052. tb.valueChanged.disconnect(self.on_preferences_edited)
  6053. except (TypeError, AttributeError):
  6054. pass
  6055. try:
  6056. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6057. except (TypeError, AttributeError):
  6058. pass
  6059. if self.preferences_changed_flag is True:
  6060. msgbox = QtWidgets.QMessageBox()
  6061. msgbox.setText(_("One or more values are changed.\n"
  6062. "Do you want to save the Preferences?"))
  6063. msgbox.setWindowTitle(_("Save Preferences"))
  6064. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6065. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6066. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6067. msgbox.setDefaultButton(bt_yes)
  6068. msgbox.exec_()
  6069. response = msgbox.clickedButton()
  6070. if response == bt_yes:
  6071. self.on_save_button()
  6072. self.inform.emit('[success] %s' %
  6073. _("Preferences saved."))
  6074. else:
  6075. self.preferences_changed_flag = False
  6076. return
  6077. def on_flipy(self):
  6078. self.report_usage("on_flipy()")
  6079. obj_list = self.collection.get_selected()
  6080. xminlist = []
  6081. yminlist = []
  6082. xmaxlist = []
  6083. ymaxlist = []
  6084. if not obj_list:
  6085. self.inform.emit('[WARNING_NOTCL] %s' %
  6086. _("No object selected to Flip on Y axis."))
  6087. else:
  6088. try:
  6089. # first get a bounding box to fit all
  6090. for obj in obj_list:
  6091. xmin, ymin, xmax, ymax = obj.bounds()
  6092. xminlist.append(xmin)
  6093. yminlist.append(ymin)
  6094. xmaxlist.append(xmax)
  6095. ymaxlist.append(ymax)
  6096. # get the minimum x,y and maximum x,y for all objects selected
  6097. xminimal = min(xminlist)
  6098. yminimal = min(yminlist)
  6099. xmaximal = max(xmaxlist)
  6100. ymaximal = max(ymaxlist)
  6101. px = 0.5 * (xminimal + xmaximal)
  6102. py = 0.5 * (yminimal + ymaximal)
  6103. # execute mirroring
  6104. for obj in obj_list:
  6105. obj.mirror('X', [px, py])
  6106. obj.plot()
  6107. self.object_changed.emit(obj)
  6108. self.inform.emit('[success] %s' %
  6109. _("Flip on Y axis done."))
  6110. except Exception as e:
  6111. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6112. (_("Flip action was not executed."), str(e)))
  6113. return
  6114. def on_flipx(self):
  6115. self.report_usage("on_flipx()")
  6116. obj_list = self.collection.get_selected()
  6117. xminlist = []
  6118. yminlist = []
  6119. xmaxlist = []
  6120. ymaxlist = []
  6121. if not obj_list:
  6122. self.inform.emit('[WARNING_NOTCL] %s' %
  6123. _("No object selected to Flip on X axis."))
  6124. else:
  6125. try:
  6126. # first get a bounding box to fit all
  6127. for obj in obj_list:
  6128. xmin, ymin, xmax, ymax = obj.bounds()
  6129. xminlist.append(xmin)
  6130. yminlist.append(ymin)
  6131. xmaxlist.append(xmax)
  6132. ymaxlist.append(ymax)
  6133. # get the minimum x,y and maximum x,y for all objects selected
  6134. xminimal = min(xminlist)
  6135. yminimal = min(yminlist)
  6136. xmaximal = max(xmaxlist)
  6137. ymaximal = max(ymaxlist)
  6138. px = 0.5 * (xminimal + xmaximal)
  6139. py = 0.5 * (yminimal + ymaximal)
  6140. # execute mirroring
  6141. for obj in obj_list:
  6142. obj.mirror('Y', [px, py])
  6143. obj.plot()
  6144. self.object_changed.emit(obj)
  6145. self.inform.emit('[success] %s' %
  6146. _("Flip on X axis done."))
  6147. except Exception as e:
  6148. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6149. (_("Flip action was not executed."), str(e)))
  6150. return
  6151. def on_rotate(self, silent=False, preset=None):
  6152. self.report_usage("on_rotate()")
  6153. obj_list = self.collection.get_selected()
  6154. xminlist = []
  6155. yminlist = []
  6156. xmaxlist = []
  6157. ymaxlist = []
  6158. if not obj_list:
  6159. self.inform.emit('[WARNING_NOTCL] %s' %
  6160. _("No object selected to Rotate."))
  6161. else:
  6162. if silent is False:
  6163. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6164. min=-360, max=360, decimals=4,
  6165. init_val=float(self.defaults['tools_transform_rotate']))
  6166. num, ok = rotatebox.get_value()
  6167. else:
  6168. num = preset
  6169. ok = True
  6170. if ok:
  6171. try:
  6172. # first get a bounding box to fit all
  6173. for obj in obj_list:
  6174. xmin, ymin, xmax, ymax = obj.bounds()
  6175. xminlist.append(xmin)
  6176. yminlist.append(ymin)
  6177. xmaxlist.append(xmax)
  6178. ymaxlist.append(ymax)
  6179. # get the minimum x,y and maximum x,y for all objects selected
  6180. xminimal = min(xminlist)
  6181. yminimal = min(yminlist)
  6182. xmaximal = max(xmaxlist)
  6183. ymaximal = max(ymaxlist)
  6184. px = 0.5 * (xminimal + xmaximal)
  6185. py = 0.5 * (yminimal + ymaximal)
  6186. for sel_obj in obj_list:
  6187. sel_obj.rotate(-float(num), point=(px, py))
  6188. sel_obj.plot()
  6189. self.object_changed.emit(sel_obj)
  6190. self.inform.emit('[success] %s' %
  6191. _("Rotation done."))
  6192. except Exception as e:
  6193. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6194. (_("Rotation movement was not executed."), str(e)))
  6195. return
  6196. def on_skewx(self):
  6197. self.report_usage("on_skewx()")
  6198. obj_list = self.collection.get_selected()
  6199. xminlist = []
  6200. yminlist = []
  6201. if not obj_list:
  6202. self.inform.emit('[WARNING_NOTCL] %s' %
  6203. _("No object selected to Skew/Shear on X axis."))
  6204. else:
  6205. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6206. min=-360, max=360, decimals=4,
  6207. init_val=float(self.defaults['tools_transform_skew_x']))
  6208. num, ok = skewxbox.get_value()
  6209. if ok:
  6210. # first get a bounding box to fit all
  6211. for obj in obj_list:
  6212. xmin, ymin, xmax, ymax = obj.bounds()
  6213. xminlist.append(xmin)
  6214. yminlist.append(ymin)
  6215. # get the minimum x,y and maximum x,y for all objects selected
  6216. xminimal = min(xminlist)
  6217. yminimal = min(yminlist)
  6218. for obj in obj_list:
  6219. obj.skew(num, 0, point=(xminimal, yminimal))
  6220. obj.plot()
  6221. self.object_changed.emit(obj)
  6222. self.inform.emit('[success] %s' %
  6223. _("Skew on X axis done."))
  6224. def on_skewy(self):
  6225. self.report_usage("on_skewy()")
  6226. obj_list = self.collection.get_selected()
  6227. xminlist = []
  6228. yminlist = []
  6229. if not obj_list:
  6230. self.inform.emit('[WARNING_NOTCL] %s' %
  6231. _("No object selected to Skew/Shear on Y axis."))
  6232. else:
  6233. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6234. min=-360, max=360, decimals=4,
  6235. init_val=float(self.defaults['tools_transform_skew_y']))
  6236. num, ok = skewybox.get_value()
  6237. if ok:
  6238. # first get a bounding box to fit all
  6239. for obj in obj_list:
  6240. xmin, ymin, xmax, ymax = obj.bounds()
  6241. xminlist.append(xmin)
  6242. yminlist.append(ymin)
  6243. # get the minimum x,y and maximum x,y for all objects selected
  6244. xminimal = min(xminlist)
  6245. yminimal = min(yminlist)
  6246. for obj in obj_list:
  6247. obj.skew(0, num, point=(xminimal, yminimal))
  6248. obj.plot()
  6249. self.object_changed.emit(obj)
  6250. self.inform.emit('[success] %s' %
  6251. _("Skew on Y axis done."))
  6252. def on_plots_updated(self):
  6253. """
  6254. Callback used to report when the plots have changed.
  6255. Adjust axes and zooms to fit.
  6256. :return: None
  6257. """
  6258. if self.is_legacy is False:
  6259. self.plotcanvas.update() # TODO: Need update canvas?
  6260. else:
  6261. self.plotcanvas.auto_adjust_axes()
  6262. self.on_zoom_fit(None)
  6263. self.collection.update_view()
  6264. # self.inform.emit(_("Plots updated ..."))
  6265. # TODO: Rework toolbar 'clear', 'replot' functions
  6266. def on_toolbar_replot(self):
  6267. """
  6268. Callback for toolbar button. Re-plots all objects.
  6269. :return: None
  6270. """
  6271. self.report_usage("on_toolbar_replot")
  6272. self.log.debug("on_toolbar_replot()")
  6273. try:
  6274. self.collection.get_active().read_form()
  6275. except AttributeError:
  6276. self.log.debug("on_toolbar_replot(): AttributeError")
  6277. pass
  6278. self.plot_all()
  6279. def on_row_activated(self, index):
  6280. if index.isValid():
  6281. if index.internalPointer().parent_item != self.collection.root_item:
  6282. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6283. self.collection.on_item_activated(index)
  6284. def grid_status(self):
  6285. if self.ui.grid_snap_btn.isChecked():
  6286. return True
  6287. else:
  6288. return False
  6289. def populate_cmenu_grids(self):
  6290. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6291. self.ui.cmenu_gridmenu.clear()
  6292. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6293. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6294. grid_toggle.setCheckable(True)
  6295. if self.grid_status() == True:
  6296. grid_toggle.setChecked(True)
  6297. else:
  6298. grid_toggle.setChecked(False)
  6299. self.ui.cmenu_gridmenu.addSeparator()
  6300. for grid in sorted_list:
  6301. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6302. action.triggered.connect(self.set_grid)
  6303. self.ui.cmenu_gridmenu.addSeparator()
  6304. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6305. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6306. grid_add.triggered.connect(self.on_grid_add)
  6307. grid_delete.triggered.connect(self.on_grid_delete)
  6308. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6309. def set_grid(self):
  6310. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6311. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6312. def on_grid_add(self):
  6313. # ## Current application units in lower Case
  6314. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6315. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6316. text=_('Enter a Grid Value:'),
  6317. min=0.0000, max=99.9999, decimals=4)
  6318. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6319. val, ok = grid_add_popup.get_value()
  6320. if ok:
  6321. if float(val) == 0:
  6322. self.inform.emit('[WARNING_NOTCL] %s' %
  6323. _("Please enter a grid value with non-zero value, in Float format."))
  6324. return
  6325. else:
  6326. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6327. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6328. self.inform.emit('[success] %s...' %
  6329. _("New Grid added"))
  6330. else:
  6331. self.inform.emit('[WARNING_NOTCL] %s...' %
  6332. _("Grid already exists"))
  6333. else:
  6334. self.inform.emit('[WARNING_NOTCL] %s...' %
  6335. _("Adding New Grid cancelled"))
  6336. def on_grid_delete(self):
  6337. # ## Current application units in lower Case
  6338. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6339. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6340. text='Enter a Grid Value:',
  6341. min=0.0000, max=99.9999, decimals=4)
  6342. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6343. val, ok = grid_del_popup.get_value()
  6344. if ok:
  6345. if float(val) == 0:
  6346. self.inform.emit('[WARNING_NOTCL] %s' %
  6347. _("Please enter a grid value with non-zero value, in Float format."))
  6348. return
  6349. else:
  6350. try:
  6351. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6352. except ValueError:
  6353. self.inform.emit('[ERROR_NOTCL]%s...' %
  6354. _(" Grid Value does not exist"))
  6355. return
  6356. self.inform.emit('[success] %s...' %
  6357. _("Grid Value deleted"))
  6358. else:
  6359. self.inform.emit('[WARNING_NOTCL] %s...' %
  6360. _("Delete Grid value cancelled"))
  6361. def on_shortcut_list(self):
  6362. self.report_usage("on_shortcut_list()")
  6363. # add the tab if it was closed
  6364. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6365. # delete the absolute and relative position and messages in the infobar
  6366. self.ui.position_label.setText("")
  6367. self.ui.rel_position_label.setText("")
  6368. # Switch plot_area to preferences page
  6369. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6370. # self.ui.show()
  6371. def on_select_tab(self, name):
  6372. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6373. if self.ui.splitter.sizes()[0] == 0:
  6374. self.ui.splitter.setSizes([1, 1])
  6375. else:
  6376. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6377. self.ui.splitter.setSizes([0, 1])
  6378. if name == 'project':
  6379. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6380. elif name == 'selected':
  6381. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6382. elif name == 'tool':
  6383. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6384. def on_copy_name(self):
  6385. self.report_usage("on_copy_name()")
  6386. obj = self.collection.get_active()
  6387. try:
  6388. name = obj.options["name"]
  6389. except AttributeError:
  6390. log.debug("on_copy_name() --> No object selected to copy it's name")
  6391. self.inform.emit('[WARNING_NOTCL]%s' %
  6392. _(" No object selected to copy it's name"))
  6393. return
  6394. self.clipboard.setText(name)
  6395. self.inform.emit(_("Name copied on clipboard ..."))
  6396. def on_mouse_click_over_plot(self, event):
  6397. """
  6398. Default actions are:
  6399. :param event: Contains information about the event, like which button
  6400. was clicked, the pixel coordinates and the axes coordinates.
  6401. :return: None
  6402. """
  6403. self.pos = []
  6404. if self.is_legacy is False:
  6405. event_pos = event.pos
  6406. if self.defaults["global_pan_button"] == '2':
  6407. pan_button = 2
  6408. else:
  6409. pan_button = 3
  6410. # Set the mouse button for panning
  6411. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6412. else:
  6413. event_pos = (event.xdata, event.ydata)
  6414. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6415. if self.defaults["global_pan_button"] == '2':
  6416. pan_button = 3
  6417. else:
  6418. pan_button = 2
  6419. # So it can receive key presses
  6420. self.plotcanvas.native.setFocus()
  6421. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6422. if self.grid_status() == True:
  6423. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6424. else:
  6425. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6426. try:
  6427. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6428. if event.button == 1:
  6429. # Reset here the relative coordinates so there is a new reference on the click position
  6430. if self.rel_point1 is None:
  6431. self.rel_point1 = self.pos
  6432. else:
  6433. self.rel_point2 = copy(self.rel_point1)
  6434. self.rel_point1 = self.pos
  6435. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6436. if modifiers == QtCore.Qt.ShiftModifier:
  6437. # do not auto open the Project Tab
  6438. self.click_noproject = True
  6439. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6440. self.inform.emit('[success] %s' %
  6441. _("Coordinates copied to clipboard."))
  6442. return
  6443. self.on_mouse_move_over_plot(event, origin_click=True)
  6444. except Exception as e:
  6445. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6446. def on_double_click_over_plot(self, event):
  6447. if event.button == 1:
  6448. self.doubleclick = True
  6449. def on_mouse_move_over_plot(self, event, origin_click=None):
  6450. """
  6451. Callback for the mouse motion event over the plot.
  6452. :param event: Contains information about the event.
  6453. :param origin_click
  6454. :return: None
  6455. """
  6456. if self.is_legacy is False:
  6457. event_pos = event.pos
  6458. if self.defaults["global_pan_button"] == '2':
  6459. pan_button = 2
  6460. else:
  6461. pan_button = 3
  6462. event_is_dragging = event.is_dragging
  6463. else:
  6464. event_pos = (event.xdata, event.ydata)
  6465. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6466. if self.defaults["global_pan_button"] == '2':
  6467. pan_button = 3
  6468. else:
  6469. pan_button = 2
  6470. event_is_dragging = self.plotcanvas.is_dragging
  6471. # So it can receive key presses
  6472. self.plotcanvas.native.setFocus()
  6473. self.pos_jump = event_pos
  6474. self.ui.popMenu.mouse_is_panning = False
  6475. if not origin_click:
  6476. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6477. if event.button == pan_button and event_is_dragging == 1:
  6478. self.ui.popMenu.mouse_is_panning = True
  6479. return
  6480. if self.rel_point1 is not None:
  6481. try: # May fail in case mouse not within axes
  6482. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6483. if self.grid_status() == True:
  6484. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6485. # Update cursor
  6486. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6487. symbol='++', edge_color='black', size=20)
  6488. else:
  6489. pos = (pos_canvas[0], pos_canvas[1])
  6490. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6491. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6492. dx = pos[0] - float(self.rel_point1[0])
  6493. dy = pos[1] - float(self.rel_point1[1])
  6494. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6495. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6496. self.mouse = [pos[0], pos[1]]
  6497. # if the mouse is moved and the LMB is clicked then the action is a selection
  6498. if event_is_dragging == 1 and event.button == 1:
  6499. self.delete_selection_shape()
  6500. if dx < 0:
  6501. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6502. face_color=self.defaults['global_alt_sel_fill'])
  6503. self.selection_type = False
  6504. elif dx > 0:
  6505. self.draw_moving_selection_shape(self.pos, pos)
  6506. self.selection_type = True
  6507. else:
  6508. self.selection_type = None
  6509. # hover effect - enabled in Preferences -> General -> GUI Settings
  6510. if self.defaults['global_hover']:
  6511. for obj in self.collection.get_list():
  6512. try:
  6513. # select the object(s) only if it is enabled (plotted)
  6514. if obj.options['plot']:
  6515. if obj not in self.collection.get_selected():
  6516. poly_obj = Polygon(
  6517. [(obj.options['xmin'], obj.options['ymin']),
  6518. (obj.options['xmax'], obj.options['ymin']),
  6519. (obj.options['xmax'], obj.options['ymax']),
  6520. (obj.options['xmin'], obj.options['ymax'])]
  6521. )
  6522. if Point(pos).within(poly_obj):
  6523. if obj.isHovering is False:
  6524. obj.isHovering = True
  6525. obj.notHovering = True
  6526. # create the selection box around the selected object
  6527. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6528. else:
  6529. if obj.notHovering is True:
  6530. obj.notHovering = False
  6531. obj.isHovering = False
  6532. self.delete_hover_shape()
  6533. except:
  6534. # the Exception here will happen if we try to select on screen and we have an
  6535. # newly (and empty) just created Geometry or Excellon object that do not have the
  6536. # xmin, xmax, ymin, ymax options.
  6537. # In this case poly_obj creation (see above) will fail
  6538. pass
  6539. except:
  6540. self.ui.position_label.setText("")
  6541. self.ui.rel_position_label.setText("")
  6542. self.mouse = None
  6543. def on_mouse_click_release_over_plot(self, event):
  6544. """
  6545. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6546. and has been registered in ''self.__init__()''.
  6547. :param event: contains information about the event.
  6548. :return:
  6549. """
  6550. pos = 0, 0
  6551. if self.is_legacy is False:
  6552. event_pos = event.pos
  6553. right_button = 2
  6554. else:
  6555. event_pos = (event.xdata, event.ydata)
  6556. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6557. right_button = 3
  6558. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6559. if self.grid_status() == True:
  6560. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6561. else:
  6562. pos = (pos_canvas[0], pos_canvas[1])
  6563. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6564. # canvas menu
  6565. if event.button == right_button: # right click
  6566. if self.ui.popMenu.mouse_is_panning is False:
  6567. self.cursor = QtGui.QCursor()
  6568. self.populate_cmenu_grids()
  6569. self.ui.popMenu.popup(self.cursor.pos())
  6570. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6571. # selection and then select a type of selection ("enclosing" or "touching")
  6572. try:
  6573. if event.button == 1: # left click
  6574. if self.doubleclick is True:
  6575. self.doubleclick = False
  6576. if self.collection.get_selected():
  6577. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6578. if self.ui.splitter.sizes()[0] == 0:
  6579. self.ui.splitter.setSizes([1, 1])
  6580. # delete the selection shape(S) as it may be in the way
  6581. self.delete_selection_shape()
  6582. self.delete_hover_shape()
  6583. else:
  6584. if self.selection_type is not None:
  6585. self.selection_area_handler(self.pos, pos, self.selection_type)
  6586. self.selection_type = None
  6587. else:
  6588. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6589. if key_modifier == QtCore.Qt.ShiftModifier:
  6590. mod_key = 'Shift'
  6591. elif key_modifier == QtCore.Qt.ControlModifier:
  6592. mod_key = 'Control'
  6593. else:
  6594. mod_key = None
  6595. if mod_key == self.defaults["global_mselect_key"]:
  6596. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6597. # deselect, and if it's not selected then it will be selected
  6598. # If there is no active command (self.command_active is None) then we check if we clicked
  6599. # on a object by checking the bounding limits against mouse click position
  6600. if self.command_active is None:
  6601. self.select_objects(key='CTRL')
  6602. self.delete_hover_shape()
  6603. else:
  6604. # If there is no active command (self.command_active is None) then we check if we clicked
  6605. # on a object by checking the bounding limits against mouse click position
  6606. if self.command_active is None:
  6607. self.select_objects()
  6608. self.delete_hover_shape()
  6609. except Exception as e:
  6610. log.warning("Error: %s" % str(e))
  6611. return
  6612. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6613. """
  6614. :param start_pos: mouse position when the selection LMB click was done
  6615. :param end_pos: mouse position when the left mouse button is released
  6616. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6617. :return:
  6618. """
  6619. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6620. self.delete_selection_shape()
  6621. for obj in self.collection.get_list():
  6622. try:
  6623. # select the object(s) only if it is enabled (plotted)
  6624. if obj.options['plot']:
  6625. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6626. (obj.options['xmax'], obj.options['ymin']),
  6627. (obj.options['xmax'], obj.options['ymax']),
  6628. (obj.options['xmin'], obj.options['ymax'])])
  6629. if sel_type is True:
  6630. if poly_obj.within(poly_selection):
  6631. # create the selection box around the selected object
  6632. if self.defaults['global_selection_shape'] is True:
  6633. self.draw_selection_shape(obj)
  6634. self.collection.set_active(obj.options['name'])
  6635. else:
  6636. if poly_selection.intersects(poly_obj):
  6637. # create the selection box around the selected object
  6638. if self.defaults['global_selection_shape'] is True:
  6639. self.draw_selection_shape(obj)
  6640. self.collection.set_active(obj.options['name'])
  6641. except Exception as e:
  6642. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6643. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6644. # In this case poly_obj creation (see above) will fail
  6645. log.debug("App.selection_area_handler() --> %s" % str(e))
  6646. def select_objects(self, key=None):
  6647. # list where we store the overlapped objects under our mouse left click position
  6648. objects_under_the_click_list = []
  6649. # Populate the list with the overlapped objects on the click position
  6650. curr_x, curr_y = self.pos
  6651. for obj in self.all_objects_list:
  6652. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6653. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6654. if obj.options['name'] not in objects_under_the_click_list:
  6655. if obj.options['plot']:
  6656. # add objects to the objects_under_the_click list only if the object is plotted
  6657. # (active and not disabled)
  6658. objects_under_the_click_list.append(obj.options['name'])
  6659. try:
  6660. # If there is no element in the overlapped objects list then make everyone inactive
  6661. # because we selected "nothing"
  6662. if not objects_under_the_click_list:
  6663. self.collection.set_all_inactive()
  6664. # delete the possible selection box around a possible selected object
  6665. self.delete_selection_shape()
  6666. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6667. # only when working on App
  6668. if self.call_source == 'app':
  6669. if self.click_noproject is False:
  6670. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6671. else:
  6672. # restore auto open the Project Tab
  6673. self.click_noproject = False
  6674. # delete any text in the status bar, implicitly the last object name that was selected
  6675. self.inform.emit("")
  6676. else:
  6677. self.call_source = 'app'
  6678. else:
  6679. # case when there is only an object under the click and we toggle it
  6680. if len(objects_under_the_click_list) == 1:
  6681. if self.collection.get_active() is None:
  6682. self.collection.set_active(objects_under_the_click_list[0])
  6683. # create the selection box around the selected object
  6684. curr_sel_obj = self.collection.get_active()
  6685. if self.defaults['global_selection_shape'] is True:
  6686. self.draw_selection_shape(curr_sel_obj)
  6687. # self.inform.emit('[selected] %s: %s selected' %
  6688. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6689. if curr_sel_obj.kind == 'gerber':
  6690. self.inform.emit(
  6691. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6692. color='green', name=str(curr_sel_obj.options['name'])))
  6693. elif curr_sel_obj.kind == 'excellon':
  6694. self.inform.emit(
  6695. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6696. color='brown', name=str(curr_sel_obj.options['name'])))
  6697. elif curr_sel_obj.kind == 'cncjob':
  6698. self.inform.emit(
  6699. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6700. color='blue', name=str(curr_sel_obj.options['name'])))
  6701. elif curr_sel_obj.kind == 'geometry':
  6702. self.inform.emit(
  6703. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6704. color='red', name=str(curr_sel_obj.options['name'])))
  6705. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6706. self.collection.set_all_inactive()
  6707. self.delete_selection_shape()
  6708. self.collection.set_active(objects_under_the_click_list[0])
  6709. # create the selection box around the selected object
  6710. curr_sel_obj = self.collection.get_active()
  6711. if self.defaults['global_selection_shape'] is True:
  6712. self.draw_selection_shape(curr_sel_obj)
  6713. # self.inform.emit('[selected] %s: %s selected' %
  6714. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6715. if curr_sel_obj.kind == 'gerber':
  6716. self.inform.emit(
  6717. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6718. color='green', name=str(curr_sel_obj.options['name'])))
  6719. elif curr_sel_obj.kind == 'excellon':
  6720. self.inform.emit(
  6721. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6722. color='brown', name=str(curr_sel_obj.options['name'])))
  6723. elif curr_sel_obj.kind == 'cncjob':
  6724. self.inform.emit(
  6725. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6726. color='blue', name=str(curr_sel_obj.options['name'])))
  6727. elif curr_sel_obj.kind == 'geometry':
  6728. self.inform.emit(
  6729. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6730. color='red', name=str(curr_sel_obj.options['name'])))
  6731. else:
  6732. self.collection.set_all_inactive()
  6733. self.delete_selection_shape()
  6734. if self.call_source == 'app':
  6735. # delete any text in the status bar, implicitly the last object name that was selected
  6736. self.inform.emit("")
  6737. else:
  6738. self.call_source = 'app'
  6739. else:
  6740. # If there is no selected object
  6741. # make active the first element of the overlapped objects list
  6742. if self.collection.get_active() is None:
  6743. self.collection.set_active(objects_under_the_click_list[0])
  6744. name_sel_obj = self.collection.get_active().options['name']
  6745. # In case that there is a selected object but it is not in the overlapped object list
  6746. # make that object inactive and activate the first element in the overlapped object list
  6747. if name_sel_obj not in objects_under_the_click_list:
  6748. self.collection.set_inactive(name_sel_obj)
  6749. name_sel_obj = objects_under_the_click_list[0]
  6750. self.collection.set_active(name_sel_obj)
  6751. else:
  6752. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6753. self.collection.set_all_inactive()
  6754. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6755. len(objects_under_the_click_list)])
  6756. curr_sel_obj = self.collection.get_active()
  6757. # delete the possible selection box around a possible selected object
  6758. self.delete_selection_shape()
  6759. # create the selection box around the selected object
  6760. if self.defaults['global_selection_shape'] is True:
  6761. self.draw_selection_shape(curr_sel_obj)
  6762. # self.inform.emit('[selected] %s: %s selected' %
  6763. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6764. if curr_sel_obj.kind == 'gerber':
  6765. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6766. color='green', name=str(curr_sel_obj.options['name'])))
  6767. elif curr_sel_obj.kind == 'excellon':
  6768. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6769. color='brown', name=str(curr_sel_obj.options['name'])))
  6770. elif curr_sel_obj.kind == 'cncjob':
  6771. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6772. color='blue', name=str(curr_sel_obj.options['name'])))
  6773. elif curr_sel_obj.kind == 'geometry':
  6774. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6775. color='red', name=str(curr_sel_obj.options['name'])))
  6776. # for obj in self.collection.get_list():
  6777. # obj.plot()
  6778. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6779. # TODO: on selected objects change the object colors and do not draw the selection box
  6780. # self.plotcanvas.update() # this updates the canvas
  6781. except Exception as e:
  6782. log.error("[ERROR] Something went bad. %s" % str(e))
  6783. return
  6784. def delete_hover_shape(self):
  6785. self.hover_shapes.clear()
  6786. self.hover_shapes.redraw()
  6787. def draw_hover_shape(self, sel_obj, color=None):
  6788. """
  6789. :param sel_obj: the object for which the hover shape must be drawn
  6790. :return:
  6791. """
  6792. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6793. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6794. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6795. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6796. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6797. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6798. hover_rect = hover_rect.buffer(-0.1)
  6799. hover_rect = hover_rect.buffer(0.2)
  6800. else:
  6801. hover_rect = hover_rect.buffer(-0.00393)
  6802. hover_rect = hover_rect.buffer(0.00787)
  6803. # if color:
  6804. # face = Color(color)
  6805. # face.alpha = 0.2
  6806. # outline = Color(color, alpha=0.8)
  6807. # else:
  6808. # face = Color(self.defaults['global_sel_fill'])
  6809. # face.alpha = 0.2
  6810. # outline = self.defaults['global_sel_line']
  6811. if color:
  6812. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6813. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6814. else:
  6815. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6816. outline = self.defaults['global_sel_line']
  6817. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6818. if self.is_legacy is True:
  6819. self.hover_shapes.redraw()
  6820. def delete_selection_shape(self):
  6821. self.move_tool.sel_shapes.clear()
  6822. self.move_tool.sel_shapes.redraw()
  6823. def draw_selection_shape(self, sel_obj, color=None):
  6824. """
  6825. :param sel_obj: the object for which the selection shape must be drawn
  6826. :return:
  6827. """
  6828. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6829. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6830. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6831. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6832. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6833. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6834. sel_rect = sel_rect.buffer(-0.1)
  6835. sel_rect = sel_rect.buffer(0.2)
  6836. else:
  6837. sel_rect = sel_rect.buffer(-0.00393)
  6838. sel_rect = sel_rect.buffer(0.00787)
  6839. # if color:
  6840. # face = Color(color, alpha=0.2)
  6841. # outline = Color(color, alpha=0.8)
  6842. # else:
  6843. # face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6844. # outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6845. if color:
  6846. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6847. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6848. else:
  6849. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6850. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6851. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6852. color=outline,
  6853. face_color=face,
  6854. update=True,
  6855. layer=0,
  6856. tolerance=None))
  6857. if self.is_legacy is True:
  6858. self.move_tool.sel_shapes.redraw()
  6859. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6860. """
  6861. :param old_coords: old coordinates
  6862. :param coords: new coordinates
  6863. :return:
  6864. """
  6865. if 'color' in kwargs:
  6866. color = kwargs['color']
  6867. else:
  6868. color = self.defaults['global_sel_line']
  6869. if 'face_color' in kwargs:
  6870. face_color = kwargs['face_color']
  6871. else:
  6872. face_color = self.defaults['global_sel_fill']
  6873. if 'face_alpha' in kwargs:
  6874. face_alpha = kwargs['face_alpha']
  6875. else:
  6876. face_alpha = 0.3
  6877. x0, y0 = old_coords
  6878. x1, y1 = coords
  6879. pt1 = (x0, y0)
  6880. pt2 = (x1, y0)
  6881. pt3 = (x1, y1)
  6882. pt4 = (x0, y1)
  6883. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6884. # color_t = Color(face_color)
  6885. # color_t.alpha = face_alpha
  6886. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6887. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6888. layer=0, tolerance=None)
  6889. if self.is_legacy is True:
  6890. self.move_tool.sel_shapes.redraw()
  6891. def on_file_new_click(self):
  6892. if self.collection.get_list() and self.should_we_save:
  6893. msgbox = QtWidgets.QMessageBox()
  6894. # msgbox.setText("<B>Save changes ...</B>")
  6895. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6896. "Creating a New project will delete them.\n"
  6897. "Do you want to Save the project?"))
  6898. msgbox.setWindowTitle(_("Save changes"))
  6899. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6900. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6901. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6902. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6903. msgbox.setDefaultButton(bt_yes)
  6904. msgbox.exec_()
  6905. response = msgbox.clickedButton()
  6906. if response == bt_yes:
  6907. self.on_file_saveprojectas()
  6908. elif response == bt_cancel:
  6909. return
  6910. elif response == bt_no:
  6911. self.on_file_new()
  6912. else:
  6913. self.on_file_new()
  6914. self.inform.emit('[success] %s...' %
  6915. _("New Project created"))
  6916. def on_file_new(self, cli=None):
  6917. """
  6918. Callback for menu item File->New. Returns the application to its
  6919. startup state. This method is thread-safe.
  6920. :return: None
  6921. """
  6922. self.report_usage("on_file_new")
  6923. # Remove everything from memory
  6924. App.log.debug("on_file_new()")
  6925. if self.call_source != 'app':
  6926. self.editor2object(cleanup=True)
  6927. # ## EDITOR section
  6928. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6929. self.exc_editor = FlatCAMExcEditor(self)
  6930. self.grb_editor = FlatCAMGrbEditor(self)
  6931. # Clear pool
  6932. self.clear_pool()
  6933. for obj in self.collection.get_list():
  6934. # delete shapes left drawn from mark shape_collections, if any
  6935. if isinstance(obj, FlatCAMGerber):
  6936. try:
  6937. obj.mark_shapes.enabled = False
  6938. obj.mark_shapes.clear(update=True)
  6939. except AttributeError:
  6940. pass
  6941. # also delete annotation shapes, if any
  6942. elif isinstance(obj, FlatCAMCNCjob):
  6943. try:
  6944. obj.annotation.enabled = False
  6945. obj.annotation.clear(update=True)
  6946. except AttributeError:
  6947. pass
  6948. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6949. self.init_tcl()
  6950. self.delete_selection_shape()
  6951. self.collection.delete_all()
  6952. self.setup_component_editor()
  6953. # Clear project filename
  6954. self.project_filename = None
  6955. # Load the application defaults
  6956. self.load_defaults(filename='current_defaults')
  6957. # Re-fresh project options
  6958. self.on_options_app2project()
  6959. # Init Tools
  6960. self.init_tools()
  6961. if cli is None:
  6962. # Close any Tabs opened in the Plot Tab Area section
  6963. for index in range(self.ui.plot_tab_area.count()):
  6964. self.ui.plot_tab_area.closeTab(index)
  6965. # for whatever reason previous command does not close the last tab so I do it manually
  6966. self.ui.plot_tab_area.closeTab(0)
  6967. # # And then add again the Plot Area
  6968. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6969. self.ui.plot_tab_area.protectTab(0)
  6970. # take the focus of the Notebook on Project Tab.
  6971. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6972. self.set_ui_title(name=_("New Project - Not saved"))
  6973. def obj_properties(self):
  6974. self.report_usage("obj_properties()")
  6975. self.properties_tool.run(toggle=False)
  6976. def on_project_context_save(self):
  6977. obj = self.collection.get_active()
  6978. if type(obj) == FlatCAMGeometry:
  6979. self.on_file_exportdxf()
  6980. elif type(obj) == FlatCAMExcellon:
  6981. self.on_file_saveexcellon()
  6982. elif type(obj) == FlatCAMCNCjob:
  6983. obj.on_exportgcode_button_click()
  6984. elif type(obj) == FlatCAMGerber:
  6985. self.on_file_savegerber()
  6986. def obj_move(self):
  6987. self.report_usage("obj_move()")
  6988. self.move_tool.run(toggle=False)
  6989. def on_fileopengerber(self, checked=None, name=None):
  6990. """
  6991. File menu callback for opening a Gerber.
  6992. :return: None
  6993. """
  6994. self.report_usage("on_fileopengerber")
  6995. App.log.debug("on_fileopengerber()")
  6996. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6997. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6998. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6999. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7000. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7001. "*.mil);;" \
  7002. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7003. "Allegro Files (*.art);;" \
  7004. "Mentor Files (*.pho *.gdo);;" \
  7005. "All Files (*.*)"
  7006. if name is None:
  7007. try:
  7008. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7009. directory=self.get_last_folder(),
  7010. filter=_filter_)
  7011. except TypeError:
  7012. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7013. filenames = [str(filename) for filename in filenames]
  7014. else:
  7015. filenames = [name]
  7016. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7017. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7018. _("Opening Gerber file.")),
  7019. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7020. color=QtGui.QColor("gray"))
  7021. if len(filenames) == 0:
  7022. self.inform.emit('[WARNING_NOTCL] %s' %
  7023. _("Open Gerber cancelled."))
  7024. else:
  7025. for filename in filenames:
  7026. if filename != '':
  7027. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7028. def on_fileopenexcellon(self, checked=None, name=None):
  7029. """
  7030. File menu callback for opening an Excellon file.
  7031. :return: None
  7032. """
  7033. self.report_usage("on_fileopenexcellon")
  7034. App.log.debug("on_fileopenexcellon()")
  7035. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7036. "All Files (*.*)"
  7037. if name is None:
  7038. try:
  7039. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7040. directory=self.get_last_folder(),
  7041. filter=_filter_)
  7042. except TypeError:
  7043. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7044. filenames = [str(filename) for filename in filenames]
  7045. else:
  7046. filenames = [str(name)]
  7047. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7048. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7049. _("Opening Excellon file.")),
  7050. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7051. color=QtGui.QColor("gray"))
  7052. if len(filenames) == 0:
  7053. self.inform.emit('[WARNING_NOTCL]%s' %
  7054. _(" Open Excellon cancelled."))
  7055. else:
  7056. for filename in filenames:
  7057. if filename != '':
  7058. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7059. def on_fileopengcode(self, checked=None, name=None):
  7060. """
  7061. File menu call back for opening gcode.
  7062. :return: None
  7063. """
  7064. self.report_usage("on_fileopengcode")
  7065. App.log.debug("on_fileopengcode()")
  7066. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7067. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7068. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7069. "All Files (*.*)"
  7070. if name is None:
  7071. try:
  7072. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7073. directory=self.get_last_folder(),
  7074. filter=_filter_)
  7075. except TypeError:
  7076. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7077. filenames = [str(filename) for filename in filenames]
  7078. else:
  7079. filenames = [name]
  7080. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7081. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7082. _("Opening G-Code file.")),
  7083. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7084. color=QtGui.QColor("gray"))
  7085. if len(filenames) == 0:
  7086. self.inform.emit('[WARNING_NOTCL] %s' %
  7087. _("Open G-Code cancelled."))
  7088. else:
  7089. for filename in filenames:
  7090. if filename != '':
  7091. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7092. def on_file_openproject(self, checked=None):
  7093. """
  7094. File menu callback for opening a project.
  7095. :return: None
  7096. """
  7097. self.report_usage("on_file_openproject")
  7098. App.log.debug("on_file_openproject()")
  7099. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7100. try:
  7101. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7102. directory=self.get_last_folder(), filter=_filter_)
  7103. except TypeError:
  7104. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7105. # The Qt methods above will return a QString which can cause problems later.
  7106. # So far json.dump() will fail to serialize it.
  7107. # TODO: Improve the serialization methods and remove this fix.
  7108. filename = str(filename)
  7109. if filename == "":
  7110. self.inform.emit('[WARNING_NOTCL] %s' %
  7111. _("Open Project cancelled."))
  7112. else:
  7113. # self.worker_task.emit({'fcn': self.open_project,
  7114. # 'params': [filename]})
  7115. # The above was failing because open_project() is not
  7116. # thread safe. The new_project()
  7117. self.open_project(filename)
  7118. def on_file_openconfig(self, checked=None):
  7119. """
  7120. File menu callback for opening a config file.
  7121. :return: None
  7122. """
  7123. self.report_usage("on_file_openconfig")
  7124. App.log.debug("on_file_openconfig()")
  7125. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7126. try:
  7127. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7128. directory=self.data_path, filter=_filter_)
  7129. except TypeError:
  7130. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7131. filter=_filter_)
  7132. if filename == "":
  7133. self.inform.emit('[WARNING_NOTCL] %s' %
  7134. _("Open Config cancelled."))
  7135. else:
  7136. self.open_config_file(filename)
  7137. def on_file_exportsvg(self):
  7138. """
  7139. Callback for menu item File->Export SVG.
  7140. :return: None
  7141. """
  7142. self.report_usage("on_file_exportsvg")
  7143. App.log.debug("on_file_exportsvg()")
  7144. obj = self.collection.get_active()
  7145. if obj is None:
  7146. self.inform.emit('[WARNING_NOTCL] %s' %
  7147. _("No object selected."))
  7148. msg = _("Please Select a Geometry object to export")
  7149. msgbox = QtWidgets.QMessageBox()
  7150. msgbox.setInformativeText(msg)
  7151. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7152. msgbox.setDefaultButton(bt_ok)
  7153. msgbox.exec_()
  7154. return
  7155. # Check for more compatible types and add as required
  7156. if (not isinstance(obj, FlatCAMGeometry)
  7157. and not isinstance(obj, FlatCAMGerber)
  7158. and not isinstance(obj, FlatCAMCNCjob)
  7159. and not isinstance(obj, FlatCAMExcellon)):
  7160. msg = '[ERROR_NOTCL] %s' % \
  7161. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7162. msgbox = QtWidgets.QMessageBox()
  7163. msgbox.setInformativeText(msg)
  7164. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7165. msgbox.setDefaultButton(bt_ok)
  7166. msgbox.exec_()
  7167. return
  7168. name = obj.options["name"]
  7169. _filter = "SVG File (*.svg);;All Files (*.*)"
  7170. try:
  7171. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7172. caption=_("Export SVG"),
  7173. directory=self.get_last_save_folder() + '/' + str(name),
  7174. filter=_filter)
  7175. except TypeError:
  7176. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7177. filename = str(filename)
  7178. if filename == "":
  7179. self.inform.emit('[WARNING_NOTCL]%s' %
  7180. _(" Export SVG cancelled."))
  7181. return
  7182. else:
  7183. self.export_svg(name, filename)
  7184. if self.defaults["global_open_style"] is False:
  7185. self.file_opened.emit("SVG", filename)
  7186. self.file_saved.emit("SVG", filename)
  7187. def on_file_exportpng(self):
  7188. self.report_usage("on_file_exportpng")
  7189. App.log.debug("on_file_exportpng()")
  7190. self.date = str(datetime.today()).rpartition('.')[0]
  7191. self.date = ''.join(c for c in self.date if c not in ':-')
  7192. self.date = self.date.replace(' ', '_')
  7193. image = _screenshot()
  7194. data = np.asarray(image)
  7195. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7196. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7197. _('Data must be a 3D array with last dimension 3 or 4'))
  7198. return
  7199. filter_ = "PNG File (*.png);;All Files (*.*)"
  7200. try:
  7201. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7202. caption=_("Export PNG Image"),
  7203. directory=self.get_last_save_folder() + '/png_' + self.date,
  7204. filter=filter_)
  7205. except TypeError:
  7206. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7207. filename = str(filename)
  7208. if filename == "":
  7209. self.inform.emit(_("Export PNG cancelled."))
  7210. return
  7211. else:
  7212. write_png(filename, data)
  7213. if self.defaults["global_open_style"] is False:
  7214. self.file_opened.emit("png", filename)
  7215. self.file_saved.emit("png", filename)
  7216. def on_file_savegerber(self):
  7217. """
  7218. Callback for menu item in Project context menu.
  7219. :return: None
  7220. """
  7221. self.report_usage("on_file_savegerber")
  7222. App.log.debug("on_file_savegerber()")
  7223. obj = self.collection.get_active()
  7224. if obj is None:
  7225. self.inform.emit('[WARNING_NOTCL] %s' %
  7226. _("No object selected. Please select an Gerber object to export."))
  7227. return
  7228. # Check for more compatible types and add as required
  7229. if not isinstance(obj, FlatCAMGerber):
  7230. self.inform.emit('[ERROR_NOTCL] %s' %
  7231. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7232. return
  7233. name = self.collection.get_active().options["name"]
  7234. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7235. try:
  7236. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7237. caption="Save Gerber source file",
  7238. directory=self.get_last_save_folder() + '/' + name,
  7239. filter=_filter)
  7240. except TypeError:
  7241. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7242. filename = str(filename)
  7243. if filename == "":
  7244. self.inform.emit('[WARNING_NOTCL] %s' %
  7245. _("Save Gerber source file cancelled."))
  7246. return
  7247. else:
  7248. self.save_source_file(name, filename)
  7249. if self.defaults["global_open_style"] is False:
  7250. self.file_opened.emit("Gerber", filename)
  7251. self.file_saved.emit("Gerber", filename)
  7252. def on_file_saveexcellon(self):
  7253. """
  7254. Callback for menu item in project context menu.
  7255. :return: None
  7256. """
  7257. self.report_usage("on_file_saveexcellon")
  7258. App.log.debug("on_file_saveexcellon()")
  7259. obj = self.collection.get_active()
  7260. if obj is None:
  7261. self.inform.emit('[WARNING_NOTCL] %s' %
  7262. _("No object selected. Please select an Excellon object to export."))
  7263. return
  7264. # Check for more compatible types and add as required
  7265. if not isinstance(obj, FlatCAMExcellon):
  7266. self.inform.emit('[ERROR_NOTCL] %s' %
  7267. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7268. return
  7269. name = self.collection.get_active().options["name"]
  7270. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7271. try:
  7272. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7273. caption=_("Save Excellon source file"),
  7274. directory=self.get_last_save_folder() + '/' + name,
  7275. filter=_filter)
  7276. except TypeError:
  7277. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7278. filename = str(filename)
  7279. if filename == "":
  7280. self.inform.emit('[WARNING_NOTCL] %s' %
  7281. _("Saving Excellon source file cancelled."))
  7282. return
  7283. else:
  7284. self.save_source_file(name, filename)
  7285. if self.defaults["global_open_style"] is False:
  7286. self.file_opened.emit("Excellon", filename)
  7287. self.file_saved.emit("Excellon", filename)
  7288. def on_file_exportexcellon(self):
  7289. """
  7290. Callback for menu item File->Export->Excellon.
  7291. :return: None
  7292. """
  7293. self.report_usage("on_file_exportexcellon")
  7294. App.log.debug("on_file_exportexcellon()")
  7295. obj = self.collection.get_active()
  7296. if obj is None:
  7297. self.inform.emit('[WARNING_NOTCL] %s' %
  7298. _("No object selected. Please Select an Excellon object to export."))
  7299. return
  7300. # Check for more compatible types and add as required
  7301. if not isinstance(obj, FlatCAMExcellon):
  7302. self.inform.emit('[ERROR_NOTCL] %s' %
  7303. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7304. return
  7305. name = self.collection.get_active().options["name"]
  7306. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7307. try:
  7308. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7309. caption=_("Export Excellon"),
  7310. directory=self.get_last_save_folder() + '/' + name,
  7311. filter=_filter)
  7312. except TypeError:
  7313. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7314. filename = str(filename)
  7315. if filename == "":
  7316. self.inform.emit('[WARNING_NOTCL] %s' %
  7317. _("Export Excellon cancelled."))
  7318. return
  7319. else:
  7320. self.export_excellon(name, filename)
  7321. if self.defaults["global_open_style"] is False:
  7322. self.file_opened.emit("Excellon", filename)
  7323. self.file_saved.emit("Excellon", filename)
  7324. def on_file_exportgerber(self):
  7325. """
  7326. Callback for menu item File->Export->Gerber.
  7327. :return: None
  7328. """
  7329. self.report_usage("on_file_exportgerber")
  7330. App.log.debug("on_file_exportgerber()")
  7331. obj = self.collection.get_active()
  7332. if obj is None:
  7333. self.inform.emit('[WARNING_NOTCL] %s' %
  7334. _("No object selected. Please Select an Gerber object to export."))
  7335. return
  7336. # Check for more compatible types and add as required
  7337. if not isinstance(obj, FlatCAMGerber):
  7338. self.inform.emit('[ERROR_NOTCL] %s' %
  7339. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7340. return
  7341. name = self.collection.get_active().options["name"]
  7342. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7343. try:
  7344. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7345. caption=_("Export Gerber"),
  7346. directory=self.get_last_save_folder() + '/' + name,
  7347. filter=_filter_)
  7348. except TypeError:
  7349. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7350. filename = str(filename)
  7351. if filename == "":
  7352. self.inform.emit('[WARNING_NOTCL] %s' %
  7353. _("Export Gerber cancelled."))
  7354. return
  7355. else:
  7356. self.export_gerber(name, filename)
  7357. if self.defaults["global_open_style"] is False:
  7358. self.file_opened.emit("Gerber", filename)
  7359. self.file_saved.emit("Gerber", filename)
  7360. def on_file_exportdxf(self):
  7361. """
  7362. Callback for menu item File->Export DXF.
  7363. :return: None
  7364. """
  7365. self.report_usage("on_file_exportdxf")
  7366. App.log.debug("on_file_exportdxf()")
  7367. obj = self.collection.get_active()
  7368. if obj is None:
  7369. self.inform.emit('[WARNING_NOTCL] %s' %
  7370. _("No object selected."))
  7371. msg = _("Please Select a Geometry object to export")
  7372. msgbox = QtWidgets.QMessageBox()
  7373. msgbox.setInformativeText(msg)
  7374. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7375. msgbox.setDefaultButton(bt_ok)
  7376. msgbox.exec_()
  7377. return
  7378. # Check for more compatible types and add as required
  7379. if not isinstance(obj, FlatCAMGeometry):
  7380. msg = '[ERROR_NOTCL] %s' % \
  7381. _("Only Geometry objects can be used.")
  7382. msgbox = QtWidgets.QMessageBox()
  7383. msgbox.setInformativeText(msg)
  7384. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7385. msgbox.setDefaultButton(bt_ok)
  7386. msgbox.exec_()
  7387. return
  7388. name = self.collection.get_active().options["name"]
  7389. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7390. try:
  7391. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7392. caption=_("Export DXF"),
  7393. directory=self.get_last_save_folder() + '/' + name,
  7394. filter=_filter_)
  7395. except TypeError:
  7396. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7397. filter=_filter_)
  7398. filename = str(filename)
  7399. if filename == "":
  7400. self.inform.emit('[WARNING_NOTCL] %s' %
  7401. _("Export DXF cancelled."))
  7402. return
  7403. else:
  7404. self.export_dxf(name, filename)
  7405. if self.defaults["global_open_style"] is False:
  7406. self.file_opened.emit("DXF", filename)
  7407. self.file_saved.emit("DXF", filename)
  7408. def on_file_importsvg(self, type_of_obj):
  7409. """
  7410. Callback for menu item File->Import SVG.
  7411. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7412. :type type_of_obj: str
  7413. :return: None
  7414. """
  7415. self.report_usage("on_file_importsvg")
  7416. App.log.debug("on_file_importsvg()")
  7417. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7418. try:
  7419. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7420. directory=self.get_last_folder(), filter=_filter_)
  7421. except TypeError:
  7422. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7423. filter=_filter_)
  7424. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7425. type_of_obj = "geometry"
  7426. filenames = [str(filename) for filename in filenames]
  7427. if len(filenames) == 0:
  7428. self.inform.emit('[WARNING_NOTCL] %s' %
  7429. _("Open SVG cancelled."))
  7430. else:
  7431. for filename in filenames:
  7432. if filename != '':
  7433. self.worker_task.emit({'fcn': self.import_svg,
  7434. 'params': [filename, type_of_obj]})
  7435. def on_file_importdxf(self, type_of_obj):
  7436. """
  7437. Callback for menu item File->Import DXF.
  7438. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7439. :type type_of_obj: str
  7440. :return: None
  7441. """
  7442. self.report_usage("on_file_importdxf")
  7443. App.log.debug("on_file_importdxf()")
  7444. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7445. try:
  7446. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7447. directory=self.get_last_folder(),
  7448. filter=_filter_)
  7449. except TypeError:
  7450. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7451. filter=_filter_)
  7452. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7453. type_of_obj = "geometry"
  7454. filenames = [str(filename) for filename in filenames]
  7455. if len(filenames) == 0:
  7456. self.inform.emit('[WARNING_NOTCL] %s' %
  7457. _("Open DXF cancelled."))
  7458. else:
  7459. for filename in filenames:
  7460. if filename != '':
  7461. self.worker_task.emit({'fcn': self.import_dxf,
  7462. 'params': [filename, type_of_obj]})
  7463. # ###############################################################################################################
  7464. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7465. # ###############################################################################################################
  7466. def init_code_editor(self, name):
  7467. # Signals section
  7468. # Disconnect the old signals
  7469. try:
  7470. self.ui.buttonOpen.clicked.disconnect()
  7471. except TypeError:
  7472. pass
  7473. try:
  7474. self.ui.buttonSave.clicked.disconnect()
  7475. except TypeError:
  7476. pass
  7477. # add the tab if it was closed
  7478. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7479. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7480. # delete the absolute and relative position and messages in the infobar
  7481. self.ui.position_label.setText("")
  7482. self.ui.rel_position_label.setText("")
  7483. # first clear previous text in text editor (if any)
  7484. self.ui.code_editor.clear()
  7485. self.ui.code_editor.setReadOnly(False)
  7486. self.toggle_codeeditor = True
  7487. self.ui.code_editor.completer_enable = False
  7488. self.ui.buttonRun.hide()
  7489. # make sure to keep a reference to the code editor
  7490. self.reference_code_editor = self.ui.code_editor
  7491. # Switch plot_area to CNCJob tab
  7492. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7493. def on_view_source(self):
  7494. self.inform.emit('%s' %
  7495. _("Viewing the source code of the selected object."))
  7496. self.proc_container.view.set_busy(_("Loading..."))
  7497. try:
  7498. obj = self.collection.get_active()
  7499. except Exception as e:
  7500. log.debug("App.on_view_source() --> %s" % str(e))
  7501. self.inform.emit('[WARNING_NOTCL] %s' %
  7502. _("Select an Gerber or Excellon file to view it's source file."))
  7503. return 'fail'
  7504. if obj.kind == 'gerber':
  7505. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7506. elif obj.kind == 'excellon':
  7507. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7508. elif obj.kind == 'cncjob':
  7509. "GCode Files (*.NC);;All Files (*.*)"
  7510. else:
  7511. flt = "All Files (*.*)"
  7512. self.init_code_editor(name=_("Source Editor"))
  7513. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7514. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7515. # then append the text from GCode to the text editor
  7516. if obj.kind == 'cncjob':
  7517. try:
  7518. file = obj.export_gcode(
  7519. preamble=self.defaults["cncjob_prepend"],
  7520. postamble=self.defaults["cncjob_append"],
  7521. to_file=True)
  7522. if file == 'fail':
  7523. return 'fail'
  7524. except AttributeError:
  7525. self.inform.emit('[WARNING_NOTCL] %s' %
  7526. _("There is no selected object for which to see it's source file code."))
  7527. return 'fail'
  7528. else:
  7529. try:
  7530. file = StringIO(obj.source_file)
  7531. except AttributeError:
  7532. self.inform.emit('[WARNING_NOTCL] %s' %
  7533. _("There is no selected object for which to see it's source file code."))
  7534. return 'fail'
  7535. self.ui.cncjob_frame.hide()
  7536. try:
  7537. for line in file:
  7538. QtWidgets.QApplication.processEvents()
  7539. proc_line = str(line).strip('\n')
  7540. self.ui.code_editor.append(proc_line)
  7541. except Exception as e:
  7542. log.debug('App.on_view_source() -->%s' % str(e))
  7543. self.inform.emit('[ERROR] %s: %s' %
  7544. (_('Failed to load the source code for the selected object'), str(e)))
  7545. return
  7546. self.handleTextChanged()
  7547. self.ui.cncjob_frame.show()
  7548. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7549. self.proc_container.view.set_idle()
  7550. # self.ui.show()
  7551. def on_toggle_code_editor(self):
  7552. self.report_usage("on_toggle_code_editor()")
  7553. if self.toggle_codeeditor is False:
  7554. self.init_code_editor(name=_("Code Editor"))
  7555. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7556. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7557. else:
  7558. for idx in range(self.ui.plot_tab_area.count()):
  7559. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7560. self.ui.plot_tab_area.closeTab(idx)
  7561. break
  7562. self.toggle_codeeditor = False
  7563. def on_filenewscript(self, silent=False):
  7564. """
  7565. Will create a new script file and open it in the Code Editor
  7566. :param silent: if True will not display status messages
  7567. :return: None
  7568. """
  7569. if silent is False:
  7570. self.inform.emit('[success] %s' %
  7571. _("New TCL script file created in Code Editor."))
  7572. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7573. self.init_code_editor(name=_("Script Editor"))
  7574. self.ui.code_editor.completer_enable = True
  7575. self.ui.code_editor.append(_(
  7576. "#\n"
  7577. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7578. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7579. "#\n\n"
  7580. "# FlatCAM commands list:\n"
  7581. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7582. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7583. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7584. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7585. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7586. "# SubtractRectangle, Version, WriteGCode\n"
  7587. "#\n\n"
  7588. ))
  7589. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7590. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7591. self.ui.buttonRun.show()
  7592. try:
  7593. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7594. except TypeError:
  7595. pass
  7596. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7597. self.handleTextChanged()
  7598. self.ui.code_editor.show()
  7599. def on_fileopenscript(self, name=None, silent=False):
  7600. """
  7601. Will open a Tcl script file into the Code Editor
  7602. :param silent: if True will not display status messages
  7603. :param name: name of a Tcl script file to open
  7604. :return:
  7605. """
  7606. if name:
  7607. filename = name
  7608. else:
  7609. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7610. try:
  7611. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7612. directory=self.get_last_folder(), filter=_filter_)
  7613. except TypeError:
  7614. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7615. # The Qt methods above will return a QString which can cause problems later.
  7616. # So far json.dump() will fail to serialize it.
  7617. # TODO: Improve the serialization methods and remove this fix.
  7618. filename = str(filename)
  7619. if filename == "":
  7620. if silent is False:
  7621. self.inform.emit('[WARNING_NOTCL] %s' %
  7622. _("Open TCL script cancelled."))
  7623. else:
  7624. self.on_filenewscript()
  7625. try:
  7626. with open(filename, "r") as opened_script:
  7627. try:
  7628. for line in opened_script:
  7629. proc_line = str(line).strip('\n')
  7630. self.ui.code_editor.append(proc_line)
  7631. except Exception as e:
  7632. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7633. if silent is False:
  7634. self.inform.emit('[ERROR] %s %s' %
  7635. (_('App.on_fileopenscript() -->'), str(e)))
  7636. return
  7637. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7638. self.handleTextChanged()
  7639. if silent is False:
  7640. self.inform.emit('[success] %s' %
  7641. _("TCL script file opened in Code Editor."))
  7642. # self.ui.show()
  7643. except Exception as e:
  7644. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7645. def on_filerunscript(self, name=None, silent=False):
  7646. """
  7647. File menu callback for loading and running a TCL script.
  7648. :param silent: if True will not display status messages
  7649. :param name: name of a Tcl script file to be run by FlatCAM
  7650. :return: None
  7651. """
  7652. self.report_usage("on_filerunscript")
  7653. App.log.debug("on_file_runscript()")
  7654. if name:
  7655. filename = name
  7656. if self.cmd_line_headless != 1:
  7657. self.splash.showMessage('%s: %ssec\n%s' %
  7658. (_("Canvas initialization started.\n"
  7659. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7660. _("Executing FlatCAMScript file.")
  7661. ),
  7662. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7663. color=QtGui.QColor("gray"))
  7664. else:
  7665. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7666. try:
  7667. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7668. directory=self.get_last_folder(), filter=_filter_)
  7669. except TypeError:
  7670. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7671. # The Qt methods above will return a QString which can cause problems later.
  7672. # So far json.dump() will fail to serialize it.
  7673. # TODO: Improve the serialization methods and remove this fix.
  7674. filename = str(filename)
  7675. if filename == "":
  7676. if silent is False:
  7677. self.inform.emit('[WARNING_NOTCL] %s' %
  7678. _("Run TCL script cancelled."))
  7679. else:
  7680. if self.cmd_line_headless != 1:
  7681. if self.ui.shell_dock.isHidden():
  7682. self.ui.shell_dock.show()
  7683. try:
  7684. with open(filename, "r") as tcl_script:
  7685. cmd_line_shellfile_content = tcl_script.read()
  7686. if self.cmd_line_headless != 1:
  7687. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7688. else:
  7689. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7690. if silent is False:
  7691. self.inform.emit('[success] %s' %
  7692. _("TCL script file opened in Code Editor and executed."))
  7693. except Exception as e:
  7694. log.debug("App.on_filerunscript() -> %s" % str(e))
  7695. sys.exit(2)
  7696. def on_file_saveproject(self, silent=False):
  7697. """
  7698. Callback for menu item File->Save Project. Saves the project to
  7699. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7700. if set to None. The project is saved by calling ``self.save_project()``.
  7701. :param silent: if True will not display status messages
  7702. :return: None
  7703. """
  7704. self.report_usage("on_file_saveproject")
  7705. if self.project_filename is None:
  7706. self.on_file_saveprojectas()
  7707. else:
  7708. self.worker_task.emit({'fcn': self.save_project,
  7709. 'params': [self.project_filename, silent]})
  7710. if self.defaults["global_open_style"] is False:
  7711. self.file_opened.emit("project", self.project_filename)
  7712. self.file_saved.emit("project", self.project_filename)
  7713. self.set_ui_title(name=self.project_filename)
  7714. self.should_we_save = False
  7715. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7716. """
  7717. Callback for menu item File->Save Project As... Opens a file
  7718. chooser and saves the project to the given file via
  7719. ``self.save_project()``.
  7720. :param make_copy if to be create a copy of the project; boolean
  7721. :param use_thread: if to be run in a separate thread; boolean
  7722. :param quit_action: if to be followed by quiting the application; boolean
  7723. :return: None
  7724. """
  7725. self.report_usage("on_file_saveprojectas")
  7726. self.date = str(datetime.today()).rpartition('.')[0]
  7727. self.date = ''.join(c for c in self.date if c not in ':-')
  7728. self.date = self.date.replace(' ', '_')
  7729. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7730. try:
  7731. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7732. caption=_("Save Project As ..."),
  7733. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7734. filter=filter_)
  7735. except TypeError:
  7736. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7737. filename = str(filename)
  7738. if filename == '':
  7739. self.inform.emit('[WARNING_NOTCL] %s' %
  7740. _("Save Project cancelled."))
  7741. return
  7742. try:
  7743. f = open(filename, 'r')
  7744. f.close()
  7745. except IOError:
  7746. pass
  7747. if use_thread is True:
  7748. self.worker_task.emit({'fcn': self.save_project,
  7749. 'params': [filename, quit_action]})
  7750. else:
  7751. self.save_project(filename, quit_action)
  7752. # self.save_project(filename)
  7753. if self.defaults["global_open_style"] is False:
  7754. self.file_opened.emit("project", filename)
  7755. self.file_saved.emit("project", filename)
  7756. if not make_copy:
  7757. self.project_filename = filename
  7758. self.set_ui_title(name=self.project_filename)
  7759. self.should_we_save = False
  7760. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7761. """
  7762. Exports a Geometry Object to an SVG file.
  7763. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7764. :param filename: Path to the SVG file to save to.
  7765. :param scale_factor: factor by which to change/scale the thickness of the features
  7766. :return:
  7767. """
  7768. self.report_usage("export_svg()")
  7769. if filename is None:
  7770. filename = self.defaults["global_last_save_folder"]
  7771. self.log.debug("export_svg()")
  7772. try:
  7773. obj = self.collection.get_by_name(str(obj_name))
  7774. except:
  7775. # TODO: The return behavior has not been established... should raise exception?
  7776. return "Could not retrieve object: %s" % obj_name
  7777. with self.proc_container.new(_("Exporting SVG")) as proc:
  7778. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7779. # Determine bounding area for svg export
  7780. bounds = obj.bounds()
  7781. size = obj.size()
  7782. # Convert everything to strings for use in the xml doc
  7783. svgwidth = str(size[0])
  7784. svgheight = str(size[1])
  7785. minx = str(bounds[0])
  7786. miny = str(bounds[1] - size[1])
  7787. uom = obj.units.lower()
  7788. # Add a SVG Header and footer to the svg output from shapely
  7789. # The transform flips the Y Axis so that everything renders
  7790. # properly within svg apps such as inkscape
  7791. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7792. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7793. svg_header += 'width="' + svgwidth + uom + '" '
  7794. svg_header += 'height="' + svgheight + uom + '" '
  7795. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7796. svg_header += '<g transform="scale(1,-1)">'
  7797. svg_footer = '</g> </svg>'
  7798. svg_elem = svg_header + exported_svg + svg_footer
  7799. # Parse the xml through a xml parser just to add line feeds
  7800. # and to make it look more pretty for the output
  7801. svgcode = parse_xml_string(svg_elem)
  7802. try:
  7803. with open(filename, 'w') as fp:
  7804. fp.write(svgcode.toprettyxml())
  7805. except PermissionError:
  7806. self.inform.emit('[WARNING] %s' %
  7807. _("Permission denied, saving not possible.\n"
  7808. "Most likely another app is holding the file open and not accessible."))
  7809. return 'fail'
  7810. if self.defaults["global_open_style"] is False:
  7811. self.file_opened.emit("SVG", filename)
  7812. self.file_saved.emit("SVG", filename)
  7813. self.inform.emit('[success] %s: %s' %
  7814. (_("SVG file exported to"), filename))
  7815. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7816. """
  7817. Exports a Geometry Object to an SVG file in negative.
  7818. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7819. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7820. :param filename: Path to the SVG file to save to.
  7821. :param boundary: thickness of a black border to surround all the features
  7822. :param scale_factor: factor by which to change/scale the thickness of the features
  7823. :param use_thread: if to be run in a separate thread; boolean
  7824. :return:
  7825. """
  7826. self.report_usage("export_negative()")
  7827. if filename is None:
  7828. filename = self.defaults["global_last_save_folder"]
  7829. self.log.debug("export_svg() negative")
  7830. try:
  7831. obj = self.collection.get_by_name(str(obj_name))
  7832. except:
  7833. # TODO: The return behavior has not been established... should raise exception?
  7834. return "Could not retrieve object: %s" % obj_name
  7835. try:
  7836. box = self.collection.get_by_name(str(box_name))
  7837. except:
  7838. # TODO: The return behavior has not been established... should raise exception?
  7839. return "Could not retrieve object: %s" % box_name
  7840. if box is None:
  7841. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7842. (_("No object Box. Using instead"), obj))
  7843. box = obj
  7844. def make_negative_film():
  7845. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7846. # Determine bounding area for svg export
  7847. bounds = box.bounds()
  7848. size = box.size()
  7849. uom = obj.units.lower()
  7850. # Convert everything to strings for use in the xml doc
  7851. svgwidth = str(size[0] + (2 * boundary))
  7852. svgheight = str(size[1] + (2 * boundary))
  7853. minx = str(bounds[0] - boundary)
  7854. miny = str(bounds[1] + boundary + size[1])
  7855. miny_rect = str(bounds[1] - boundary)
  7856. # Add a SVG Header and footer to the svg output from shapely
  7857. # The transform flips the Y Axis so that everything renders
  7858. # properly within svg apps such as inkscape
  7859. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7860. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7861. svg_header += 'width="' + svgwidth + uom + '" '
  7862. svg_header += 'height="' + svgheight + uom + '" '
  7863. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7864. svg_header += '>'
  7865. svg_header += '<g transform="scale(1,-1)">'
  7866. svg_footer = '</g> </svg>'
  7867. # Change the attributes of the exported SVG
  7868. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7869. # We set opacity to maximum
  7870. # We set the color to WHITE
  7871. root = ET.fromstring(exported_svg)
  7872. for child in root:
  7873. child.set('fill', '#FFFFFF')
  7874. child.set('opacity', '1.0')
  7875. child.set('stroke', '#FFFFFF')
  7876. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7877. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7878. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7879. first_svg_elem_tag = 'rect'
  7880. first_svg_elem_attribs = {
  7881. 'x': minx,
  7882. 'y': miny_rect,
  7883. 'width': svgwidth,
  7884. 'height': svgheight,
  7885. 'id': 'neg_rect',
  7886. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7887. }
  7888. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7889. exported_svg = ET.tostring(root)
  7890. svg_elem = svg_header + str(exported_svg) + svg_footer
  7891. # Parse the xml through a xml parser just to add line feeds
  7892. # and to make it look more pretty for the output
  7893. doc = parse_xml_string(svg_elem)
  7894. try:
  7895. with open(filename, 'w') as fp:
  7896. fp.write(doc.toprettyxml())
  7897. except PermissionError:
  7898. self.inform.emit('[WARNING] %s' %
  7899. _("Permission denied, saving not possible.\n"
  7900. "Most likely another app is holding the file open and not accessible."))
  7901. return 'fail'
  7902. if self.defaults["global_open_style"] is False:
  7903. self.file_opened.emit("SVG", filename)
  7904. self.file_saved.emit("SVG", filename)
  7905. self.inform.emit('[success] %s: %s' %
  7906. (_("SVG file exported to"), filename))
  7907. if use_thread is True:
  7908. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7909. def job_thread_film(app_obj):
  7910. try:
  7911. make_negative_film()
  7912. except Exception as e:
  7913. proc.done()
  7914. return
  7915. proc.done()
  7916. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7917. else:
  7918. make_negative_film()
  7919. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7920. """
  7921. Exports a Geometry Object to an SVG file in positive black.
  7922. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7923. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7924. :param filename: Path to the SVG file to save to.
  7925. :param scale_factor: factor by which to change/scale the thickness of the features
  7926. :param use_thread: if to be run in a separate thread; boolean
  7927. :return:
  7928. """
  7929. self.report_usage("export_svg_positive()")
  7930. if filename is None:
  7931. filename = self.defaults["global_last_save_folder"]
  7932. self.log.debug("export_svg() black")
  7933. try:
  7934. obj = self.collection.get_by_name(str(obj_name))
  7935. except:
  7936. # TODO: The return behavior has not been established... should raise exception?
  7937. return "Could not retrieve object: %s" % obj_name
  7938. try:
  7939. box = self.collection.get_by_name(str(box_name))
  7940. except:
  7941. # TODO: The return behavior has not been established... should raise exception?
  7942. return "Could not retrieve object: %s" % box_name
  7943. if box is None:
  7944. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7945. (_("No object Box. Using instead"), obj))
  7946. box = obj
  7947. def make_positive_film():
  7948. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7949. self.progress.emit(40)
  7950. # Change the attributes of the exported SVG
  7951. # We don't need stroke-width
  7952. # We set opacity to maximum
  7953. # We set the colour to WHITE
  7954. root = ET.fromstring(exported_svg)
  7955. for child in root:
  7956. child.set('fill', str(self.defaults['tools_film_color']))
  7957. child.set('opacity', '1.0')
  7958. child.set('stroke', str(self.defaults['tools_film_color']))
  7959. exported_svg = ET.tostring(root)
  7960. # Determine bounding area for svg export
  7961. bounds = box.bounds()
  7962. size = box.size()
  7963. # This contain the measure units
  7964. uom = obj.units.lower()
  7965. # Define a boundary around SVG of about 1.0mm (~39mils)
  7966. if uom in "mm":
  7967. boundary = 1.0
  7968. else:
  7969. boundary = 0.0393701
  7970. self.progress.emit(80)
  7971. # Convert everything to strings for use in the xml doc
  7972. svgwidth = str(size[0] + (2 * boundary))
  7973. svgheight = str(size[1] + (2 * boundary))
  7974. minx = str(bounds[0] - boundary)
  7975. miny = str(bounds[1] + boundary + size[1])
  7976. self.log.debug(minx)
  7977. self.log.debug(miny)
  7978. # Add a SVG Header and footer to the svg output from shapely
  7979. # The transform flips the Y Axis so that everything renders
  7980. # properly within svg apps such as inkscape
  7981. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7982. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7983. svg_header += 'width="' + svgwidth + uom + '" '
  7984. svg_header += 'height="' + svgheight + uom + '" '
  7985. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7986. svg_header += '>'
  7987. svg_header += '<g transform="scale(1,-1)">'
  7988. svg_footer = '</g> </svg>'
  7989. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7990. self.progress.emit(90)
  7991. # Parse the xml through a xml parser just to add line feeds
  7992. # and to make it look more pretty for the output
  7993. doc = parse_xml_string(svg_elem)
  7994. try:
  7995. with open(filename, 'w') as fp:
  7996. fp.write(doc.toprettyxml())
  7997. except PermissionError:
  7998. self.inform.emit('[WARNING] %s' %
  7999. _("Permission denied, saving not possible.\n"
  8000. "Most likely another app is holding the file open and not accessible."))
  8001. return 'fail'
  8002. self.progress.emit(100)
  8003. if self.defaults["global_open_style"] is False:
  8004. self.file_opened.emit("SVG", filename)
  8005. self.file_saved.emit("SVG", filename)
  8006. self.inform.emit('[success] %s: %s' %
  8007. (_("SVG file exported to"), filename))
  8008. if use_thread is True:
  8009. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8010. def job_thread_film(app_obj):
  8011. try:
  8012. make_positive_film()
  8013. except Exception as e:
  8014. proc.done()
  8015. return
  8016. proc.done()
  8017. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8018. else:
  8019. make_positive_film()
  8020. def save_source_file(self, obj_name, filename, use_thread=True):
  8021. """
  8022. Exports a FlatCAM Object to an Gerber/Excellon file.
  8023. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8024. :param filename: Path to the Gerber file to save to.
  8025. :param use_thread: if to be run in a separate thread
  8026. :return:
  8027. """
  8028. self.report_usage("save source file()")
  8029. if filename is None:
  8030. filename = self.defaults["global_last_save_folder"]
  8031. self.log.debug("save source file()")
  8032. obj = self.collection.get_by_name(obj_name)
  8033. file_string = StringIO(obj.source_file)
  8034. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8035. try:
  8036. with open(filename, 'w') as file:
  8037. file.writelines('G04*\n')
  8038. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8039. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8040. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8041. file.writelines('G04 Created on : %s*\n' % time_string)
  8042. for line in file_string:
  8043. file.writelines(line)
  8044. except PermissionError:
  8045. self.inform.emit('[WARNING] %s' %
  8046. _("Permission denied, saving not possible.\n"
  8047. "Most likely another app is holding the file open and not accessible."))
  8048. return 'fail'
  8049. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8050. """
  8051. Exports a Excellon Object to an Excellon file.
  8052. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8053. :param filename: Path to the Excellon file to save to.
  8054. :param use_thread: if to be run in a separate thread
  8055. :return:
  8056. """
  8057. self.report_usage("export_excellon()")
  8058. if filename is None:
  8059. filename = self.defaults["global_last_save_folder"]
  8060. self.log.debug("export_excellon()")
  8061. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8062. self.defaults["excellon_exp_decimals"]
  8063. )
  8064. units = ''
  8065. if local_use is None:
  8066. try:
  8067. obj = self.collection.get_by_name(str(obj_name))
  8068. except:
  8069. # TODO: The return behavior has not been established... should raise exception?
  8070. return "Could not retrieve object: %s" % obj_name
  8071. else:
  8072. obj = local_use
  8073. # updated units
  8074. eunits = self.defaults["excellon_exp_units"]
  8075. ewhole = self.defaults["excellon_exp_integer"]
  8076. efract = self.defaults["excellon_exp_decimals"]
  8077. ezeros = self.defaults["excellon_exp_zeros"]
  8078. eformat = self.defaults["excellon_exp_format"]
  8079. slot_type = self.defaults["excellon_exp_slot_type"]
  8080. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8081. if fc_units == 'MM':
  8082. factor = 1 if eunits == 'METRIC' else 0.03937
  8083. else:
  8084. factor = 25.4 if eunits == 'METRIC' else 1
  8085. def make_excellon():
  8086. try:
  8087. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8088. header = 'M48\n'
  8089. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8090. (str(self.version), str(self.version_date))
  8091. header += ';Filename: %s' % str(obj_name) + '\n'
  8092. header += ';Created on : %s' % time_str + '\n'
  8093. if eformat == 'dec':
  8094. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8095. header += eunits + '\n'
  8096. for tool in obj.tools:
  8097. if eunits == 'METRIC':
  8098. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8099. tool=str(tool),
  8100. dec=2)
  8101. else:
  8102. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8103. tool=str(tool),
  8104. dec=4)
  8105. else:
  8106. if ezeros == 'LZ':
  8107. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8108. form='ndec', e_zeros='LZ', factor=factor,
  8109. slot_type=slot_type)
  8110. header += '%s,%s\n' % (eunits, 'LZ')
  8111. header += format_exc
  8112. for tool in obj.tools:
  8113. if eunits == 'METRIC':
  8114. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8115. tool=str(tool),
  8116. dec=2)
  8117. else:
  8118. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8119. tool=str(tool),
  8120. dec=4)
  8121. else:
  8122. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8123. form='ndec', e_zeros='TZ', factor=factor,
  8124. slot_type=slot_type)
  8125. header += '%s,%s\n' % (eunits, 'TZ')
  8126. header += format_exc
  8127. for tool in obj.tools:
  8128. if eunits == 'METRIC':
  8129. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8130. tool=str(tool),
  8131. dec=2)
  8132. else:
  8133. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8134. tool=str(tool),
  8135. dec=4)
  8136. header += '%\n'
  8137. footer = 'M30\n'
  8138. exported_excellon = header
  8139. exported_excellon += excellon_code
  8140. exported_excellon += footer
  8141. if local_use is None:
  8142. try:
  8143. with open(filename, 'w') as fp:
  8144. fp.write(exported_excellon)
  8145. except PermissionError:
  8146. self.inform.emit('[WARNING] %s' %
  8147. _("Permission denied, saving not possible.\n"
  8148. "Most likely another app is holding the file open and not accessible."))
  8149. return 'fail'
  8150. if self.defaults["global_open_style"] is False:
  8151. self.file_opened.emit("Excellon", filename)
  8152. self.file_saved.emit("Excellon", filename)
  8153. self.inform.emit('[success] %s: %s' %
  8154. (_("Excellon file exported to"), filename))
  8155. else:
  8156. return exported_excellon
  8157. except Exception as e:
  8158. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8159. return 'fail'
  8160. if use_thread is True:
  8161. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8162. def job_thread_exc(app_obj):
  8163. ret = make_excellon()
  8164. if ret == 'fail':
  8165. self.inform.emit('[ERROR_NOTCL] %s' %
  8166. _('Could not export Excellon file.'))
  8167. return
  8168. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8169. else:
  8170. ret = make_excellon()
  8171. if ret == 'fail':
  8172. self.inform.emit('[ERROR_NOTCL] %s' %
  8173. _('Could not export Excellon file.'))
  8174. return 'fail'
  8175. if local_use is not None:
  8176. return ret
  8177. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8178. """
  8179. Exports a Gerber Object to an Gerber file.
  8180. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8181. :param filename: Path to the Gerber file to save to.
  8182. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8183. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8184. :param use_thread: if to be run in a separate thread
  8185. :return:
  8186. """
  8187. self.report_usage("export_gerber()")
  8188. if filename is None:
  8189. filename = self.defaults["global_last_save_folder"]
  8190. self.log.debug("export_gerber()")
  8191. if local_use is None:
  8192. try:
  8193. obj = self.collection.get_by_name(str(obj_name))
  8194. except:
  8195. # TODO: The return behavior has not been established... should raise exception?
  8196. return "Could not retrieve object: %s" % obj_name
  8197. else:
  8198. obj = local_use
  8199. # updated units
  8200. gunits = self.defaults["gerber_exp_units"]
  8201. gwhole = self.defaults["gerber_exp_integer"]
  8202. gfract = self.defaults["gerber_exp_decimals"]
  8203. gzeros = self.defaults["gerber_exp_zeros"]
  8204. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8205. if fc_units == 'MM':
  8206. factor = 1 if gunits == 'MM' else 0.03937
  8207. else:
  8208. factor = 25.4 if gunits == 'MM' else 1
  8209. def make_gerber():
  8210. try:
  8211. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8212. header = 'G04*\n'
  8213. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8214. (str(self.version), str(self.version_date))
  8215. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8216. header += 'G04 Created on : %s*' % time_str + '\n'
  8217. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8218. header += "%MO{units}*%\n".format(units=gunits)
  8219. for apid in obj.apertures:
  8220. if obj.apertures[apid]['type'] == 'C':
  8221. header += "%ADD{apid}{type},{size}*%\n".format(
  8222. apid=str(apid),
  8223. type='C',
  8224. size=(factor * obj.apertures[apid]['size'])
  8225. )
  8226. elif obj.apertures[apid]['type'] == 'R':
  8227. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8228. apid=str(apid),
  8229. type='R',
  8230. width=(factor * obj.apertures[apid]['width']),
  8231. height=(factor * obj.apertures[apid]['height'])
  8232. )
  8233. elif obj.apertures[apid]['type'] == 'O':
  8234. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8235. apid=str(apid),
  8236. type='O',
  8237. width=(factor * obj.apertures[apid]['width']),
  8238. height=(factor * obj.apertures[apid]['height'])
  8239. )
  8240. header += '\n'
  8241. # obsolete units but some software may need it
  8242. if gunits == 'IN':
  8243. header += 'G70*\n'
  8244. else:
  8245. header += 'G71*\n'
  8246. # Absolute Mode
  8247. header += 'G90*\n'
  8248. header += 'G01*\n'
  8249. # positive polarity
  8250. header += '%LPD*%\n'
  8251. footer = 'M02*\n'
  8252. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8253. exported_gerber = header
  8254. exported_gerber += gerber_code
  8255. exported_gerber += footer
  8256. if local_use is None:
  8257. try:
  8258. with open(filename, 'w') as fp:
  8259. fp.write(exported_gerber)
  8260. except PermissionError:
  8261. self.inform.emit('[WARNING] %s' %
  8262. _("Permission denied, saving not possible.\n"
  8263. "Most likely another app is holding the file open and not accessible."))
  8264. return 'fail'
  8265. if self.defaults["global_open_style"] is False:
  8266. self.file_opened.emit("Gerber", filename)
  8267. self.file_saved.emit("Gerber", filename)
  8268. self.inform.emit('[success] %s: %s' %
  8269. (_("Gerber file exported to"), filename))
  8270. else:
  8271. return exported_gerber
  8272. except Exception as e:
  8273. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8274. return 'fail'
  8275. if use_thread is True:
  8276. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8277. def job_thread_grb(app_obj):
  8278. ret = make_gerber()
  8279. if ret == 'fail':
  8280. self.inform.emit('[ERROR_NOTCL] %s' %
  8281. _('Could not export Gerber file.'))
  8282. return
  8283. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8284. else:
  8285. ret = make_gerber()
  8286. if ret == 'fail':
  8287. self.inform.emit('[ERROR_NOTCL] %s' %
  8288. _('Could not export Gerber file.'))
  8289. return 'fail'
  8290. if local_use is not None:
  8291. return ret
  8292. def export_dxf(self, obj_name, filename, use_thread=True):
  8293. """
  8294. Exports a Geometry Object to an DXF file.
  8295. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8296. :param filename: Path to the DXF file to save to.
  8297. :param use_thread: if to be run in a separate thread
  8298. :return:
  8299. """
  8300. self.report_usage("export_dxf()")
  8301. if filename is None:
  8302. filename = self.defaults["global_last_save_folder"]
  8303. self.log.debug("export_dxf()")
  8304. format_exc = ''
  8305. units = ''
  8306. try:
  8307. obj = self.collection.get_by_name(str(obj_name))
  8308. except:
  8309. # TODO: The return behavior has not been established... should raise exception?
  8310. return "Could not retrieve object: %s" % obj_name
  8311. # updated units
  8312. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8313. if units == 'IN' or units == 'INCH':
  8314. units = 'INCH'
  8315. elif units == 'MM' or units == 'METIRC':
  8316. units ='METRIC'
  8317. def make_dxf():
  8318. try:
  8319. dxf_code = obj.export_dxf()
  8320. dxf_code.saveas(filename)
  8321. if self.defaults["global_open_style"] is False:
  8322. self.file_opened.emit("DXF", filename)
  8323. self.file_saved.emit("DXF", filename)
  8324. self.inform.emit('[success] %s: %s' %
  8325. (_("DXF file exported to"), filename))
  8326. except:
  8327. return 'fail'
  8328. if use_thread is True:
  8329. with self.proc_container.new(_("Exporting DXF")) as proc:
  8330. def job_thread_exc(app_obj):
  8331. ret = make_dxf()
  8332. if ret == 'fail':
  8333. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8334. _('Could not export DXF file.'))
  8335. return
  8336. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8337. else:
  8338. ret = make_dxf()
  8339. if ret == 'fail':
  8340. self.inform.emit('[WARNING_NOTCL] %s' %
  8341. _('Could not export DXF file.'))
  8342. return
  8343. def import_svg(self, filename, geo_type='geometry', outname=None):
  8344. """
  8345. Adds a new Geometry Object to the projects and populates
  8346. it with shapes extracted from the SVG file.
  8347. :param filename: Path to the SVG file.
  8348. :param outname:
  8349. :return:
  8350. """
  8351. self.report_usage("import_svg()")
  8352. obj_type = ""
  8353. if geo_type is None or geo_type == "geometry":
  8354. obj_type = "geometry"
  8355. elif geo_type == "gerber":
  8356. obj_type = geo_type
  8357. else:
  8358. self.inform.emit('[ERROR_NOTCL] %s' %
  8359. _("Not supported type is picked as parameter. "
  8360. "Only Geometry and Gerber are supported"))
  8361. return
  8362. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8363. def obj_init(geo_obj, app_obj):
  8364. geo_obj.import_svg(filename, obj_type, units=units)
  8365. geo_obj.multigeo = False
  8366. with self.proc_container.new(_("Importing SVG")) as proc:
  8367. # Object name
  8368. name = outname or filename.split('/')[-1].split('\\')[-1]
  8369. self.new_object(obj_type, name, obj_init, autoselected=False)
  8370. self.progress.emit(20)
  8371. # Register recent file
  8372. self.file_opened.emit("svg", filename)
  8373. # GUI feedback
  8374. self.inform.emit('[success] %s: %s' %
  8375. (_("Opened"), filename))
  8376. self.progress.emit(100)
  8377. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8378. """
  8379. Adds a new Geometry Object to the projects and populates
  8380. it with shapes extracted from the DXF file.
  8381. :param filename: Path to the DXF file.
  8382. :param outname:
  8383. :type putname: str
  8384. :return:
  8385. """
  8386. self.report_usage("import_dxf()")
  8387. obj_type = ""
  8388. if geo_type is None or geo_type == "geometry":
  8389. obj_type = "geometry"
  8390. elif geo_type == "gerber":
  8391. obj_type = geo_type
  8392. else:
  8393. self.inform.emit('[ERROR_NOTCL] %s' %
  8394. _("Not supported type is picked as parameter. "
  8395. "Only Geometry and Gerber are supported"))
  8396. return
  8397. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8398. def obj_init(geo_obj, app_obj):
  8399. geo_obj.import_dxf(filename, obj_type, units=units)
  8400. geo_obj.multigeo = False
  8401. with self.proc_container.new(_("Importing DXF")) as proc:
  8402. # Object name
  8403. name = outname or filename.split('/')[-1].split('\\')[-1]
  8404. self.new_object(obj_type, name, obj_init, autoselected=False)
  8405. self.progress.emit(20)
  8406. # Register recent file
  8407. self.file_opened.emit("dxf", filename)
  8408. # GUI feedback
  8409. self.inform.emit('[success] %s: %s' %
  8410. (_("Opened"), filename))
  8411. self.progress.emit(100)
  8412. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8413. """
  8414. Adds a new Geometry Object to the projects and populates
  8415. it with shapes extracted from the SVG file.
  8416. :param filename: Path to the SVG file.
  8417. :param o_type: type of FlatCAM objeect
  8418. :param dpi: dot per inch
  8419. :param mode: black or color
  8420. :param mask: dictate the level of detail
  8421. :param outname: name for the resulting file
  8422. :return:
  8423. """
  8424. self.report_usage("import_image()")
  8425. if o_type is None or o_type == "geometry":
  8426. obj_type = "geometry"
  8427. elif o_type == "gerber":
  8428. obj_type = o_type
  8429. else:
  8430. self.inform.emit('[ERROR_NOTCL] %s' %
  8431. _("Not supported type is picked as parameter. "
  8432. "Only Geometry and Gerber are supported"))
  8433. return
  8434. def obj_init(geo_obj, app_obj):
  8435. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8436. geo_obj.multigeo = False
  8437. with self.proc_container.new(_("Importing Image")) as proc:
  8438. # Object name
  8439. name = outname or filename.split('/')[-1].split('\\')[-1]
  8440. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8441. self.new_object(obj_type, name, obj_init)
  8442. self.progress.emit(20)
  8443. # Register recent file
  8444. self.file_opened.emit("image", filename)
  8445. # GUI feedback
  8446. self.inform.emit('[success] %s: %s' %
  8447. (_("Opened"), filename))
  8448. self.progress.emit(100)
  8449. def open_gerber(self, filename, outname=None):
  8450. """
  8451. Opens a Gerber file, parses it and creates a new object for
  8452. it in the program. Thread-safe.
  8453. :param outname: Name of the resulting object. None causes the
  8454. name to be that of the file.
  8455. :param filename: Gerber file filename
  8456. :type filename: str
  8457. :param follow: If true, the parser will not create polygons, just lines
  8458. following the gerber path.
  8459. :type follow: bool
  8460. :return: None
  8461. """
  8462. # How the object should be initialized
  8463. def obj_init(gerber_obj, app_obj):
  8464. assert isinstance(gerber_obj, FlatCAMGerber), \
  8465. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8466. # Opening the file happens here
  8467. self.progress.emit(30)
  8468. try:
  8469. gerber_obj.parse_file(filename)
  8470. except IOError:
  8471. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8472. (_("Failed to open file"), filename))
  8473. app_obj.progress.emit(0)
  8474. return "fail"
  8475. except ParseError as err:
  8476. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8477. (_("Failed to parse file"), filename, str(err)))
  8478. app_obj.progress.emit(0)
  8479. self.log.error(str(err))
  8480. return "fail"
  8481. except Exception as e:
  8482. log.debug("App.open_gerber() --> %s" % str(e))
  8483. msg = '[ERROR] %s' % \
  8484. _("An internal error has occurred. See shell.\n")
  8485. msg += traceback.format_exc()
  8486. app_obj.inform.emit(msg)
  8487. return "fail"
  8488. if gerber_obj.is_empty():
  8489. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8490. # self.collection.set_active(gerber_obj.options["name"])
  8491. # self.collection.delete_active()
  8492. self.inform.emit('[ERROR_NOTCL] %s' %
  8493. _("Object is not Gerber file or empty. Aborting object creation."))
  8494. return "fail"
  8495. # Further parsing
  8496. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8497. App.log.debug("open_gerber()")
  8498. with self.proc_container.new(_("Opening Gerber")) as proc:
  8499. self.progress.emit(10)
  8500. # Object name
  8501. name = outname or filename.split('/')[-1].split('\\')[-1]
  8502. # # ## Object creation # ##
  8503. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8504. if ret == 'fail':
  8505. self.inform.emit('[ERROR_NOTCL]%s' %
  8506. _(' Open Gerber failed. Probable not a Gerber file.'))
  8507. return
  8508. # Register recent file
  8509. self.file_opened.emit("gerber", filename)
  8510. self.progress.emit(100)
  8511. # GUI feedback
  8512. self.inform.emit('[success] %s: %s' %
  8513. (_("Opened"), filename))
  8514. def open_excellon(self, filename, outname=None, plot=True):
  8515. """
  8516. Opens an Excellon file, parses it and creates a new object for
  8517. it in the program. Thread-safe.
  8518. :param outname: Name of the resulting object. None causes the
  8519. name to be that of the file.
  8520. :param filename: Excellon file filename
  8521. :type filename: str
  8522. :return: None
  8523. """
  8524. App.log.debug("open_excellon()")
  8525. # How the object should be initialized
  8526. def obj_init(excellon_obj, app_obj):
  8527. # self.progress.emit(20)
  8528. try:
  8529. ret = excellon_obj.parse_file(filename=filename)
  8530. if ret == "fail":
  8531. log.debug("Excellon parsing failed.")
  8532. self.inform.emit('[ERROR_NOTCL] %s' %
  8533. _("This is not Excellon file."))
  8534. return "fail"
  8535. except IOError:
  8536. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8537. (_("Cannot open file"), filename))
  8538. log.debug("Could not open Excellon object.")
  8539. self.progress.emit(0) # TODO: self and app_bjj mixed
  8540. return "fail"
  8541. except:
  8542. msg = '[ERROR_NOTCL] %s' % \
  8543. _("An internal error has occurred. See shell.\n")
  8544. msg += traceback.format_exc()
  8545. app_obj.inform.emit(msg)
  8546. return "fail"
  8547. ret = excellon_obj.create_geometry()
  8548. if ret == 'fail':
  8549. log.debug("Could not create geometry for Excellon object.")
  8550. return "fail"
  8551. for tool in excellon_obj.tools:
  8552. if excellon_obj.tools[tool]['solid_geometry']:
  8553. return
  8554. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8555. (_("No geometry found in file"), filename))
  8556. return "fail"
  8557. with self.proc_container.new(_("Opening Excellon.")):
  8558. # Object name
  8559. name = outname or filename.split('/')[-1].split('\\')[-1]
  8560. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8561. if ret_val == 'fail':
  8562. self.inform.emit('[ERROR_NOTCL] %s' %
  8563. _('Open Excellon file failed. Probable not an Excellon file.'))
  8564. return
  8565. # Register recent file
  8566. self.file_opened.emit("excellon", filename)
  8567. # GUI feedback
  8568. self.inform.emit('[success] %s: %s' %
  8569. (_("Opened"), filename))
  8570. def open_gcode(self, filename, outname=None, plot=True):
  8571. """
  8572. Opens a G-gcode file, parses it and creates a new object for
  8573. it in the program. Thread-safe.
  8574. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8575. :param filename: G-code file filename
  8576. :type filename: str
  8577. :return: None
  8578. """
  8579. App.log.debug("open_gcode()")
  8580. # How the object should be initialized
  8581. def obj_init(job_obj, app_obj_):
  8582. """
  8583. :param job_obj: the resulting object
  8584. :type app_obj_: App
  8585. """
  8586. assert isinstance(app_obj_, App), \
  8587. "Initializer expected App, got %s" % type(app_obj_)
  8588. self.progress.emit(10)
  8589. try:
  8590. f = open(filename)
  8591. gcode = f.read()
  8592. f.close()
  8593. except IOError:
  8594. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8595. (_("Failed to open"), filename))
  8596. self.progress.emit(0)
  8597. return "fail"
  8598. job_obj.gcode = gcode
  8599. self.progress.emit(20)
  8600. ret = job_obj.gcode_parse()
  8601. if ret == "fail":
  8602. self.inform.emit('[ERROR_NOTCL] %s' %
  8603. _("This is not GCODE"))
  8604. return "fail"
  8605. self.progress.emit(60)
  8606. job_obj.create_geometry()
  8607. with self.proc_container.new(_("Opening G-Code.")):
  8608. # Object name
  8609. name = outname or filename.split('/')[-1].split('\\')[-1]
  8610. # New object creation and file processing
  8611. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8612. if ret == 'fail':
  8613. self.inform.emit('[ERROR_NOTCL] %s' %
  8614. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8615. "Attempting to create a FlatCAM CNCJob Object from "
  8616. "G-Code file failed during processing"))
  8617. return "fail"
  8618. # Register recent file
  8619. self.file_opened.emit("cncjob", filename)
  8620. # GUI feedback
  8621. self.inform.emit('[success] %s: %s' %
  8622. (_("Opened"), filename))
  8623. self.progress.emit(100)
  8624. def open_config_file(self, filename, run_from_arg=None):
  8625. """
  8626. Loads a config file from the specified file.
  8627. :param filename: Name of the file from which to load.
  8628. :type filename: str
  8629. :return: None
  8630. """
  8631. App.log.debug("Opening config file: " + filename)
  8632. if run_from_arg:
  8633. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8634. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8635. _("Opening FlatCAM Config file.")),
  8636. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8637. color=QtGui.QColor("gray"))
  8638. # add the tab if it was closed
  8639. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8640. # first clear previous text in text editor (if any)
  8641. self.ui.code_editor.clear()
  8642. # Switch plot_area to CNCJob tab
  8643. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8644. try:
  8645. if filename:
  8646. f = QtCore.QFile(filename)
  8647. if f.open(QtCore.QIODevice.ReadOnly):
  8648. stream = QtCore.QTextStream(f)
  8649. gcode_edited = stream.readAll()
  8650. self.ui.code_editor.setPlainText(gcode_edited)
  8651. f.close()
  8652. except IOError:
  8653. App.log.error("Failed to open config file: %s" % filename)
  8654. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8655. (_("Failed to open config file"), filename))
  8656. return
  8657. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8658. """
  8659. Loads a project from the specified file.
  8660. 1) Loads and parses file
  8661. 2) Registers the file as recently opened.
  8662. 3) Calls on_file_new()
  8663. 4) Updates options
  8664. 5) Calls new_object() with the object's from_dict() as init method.
  8665. 6) Calls plot_all() if plot=True
  8666. :param filename: Name of the file from which to load.
  8667. :type filename: str
  8668. :param run_from_arg: True if run for arguments
  8669. :param plot: If True plot all objects in the project
  8670. :param cli: run from command line
  8671. :return: None
  8672. """
  8673. App.log.debug("Opening project: " + filename)
  8674. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8675. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8676. if cli is None:
  8677. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8678. if run_from_arg:
  8679. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8680. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8681. _("Opening FlatCAM Project file.")),
  8682. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8683. color=QtGui.QColor("gray"))
  8684. # Open and parse an uncompressed Project file
  8685. try:
  8686. f = open(filename, 'r')
  8687. except IOError:
  8688. App.log.error("Failed to open project file: %s" % filename)
  8689. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8690. (_("Failed to open project file"), filename))
  8691. return
  8692. try:
  8693. d = json.load(f, object_hook=dict2obj)
  8694. except Exception as e:
  8695. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8696. (filename, str(e)))
  8697. f.close()
  8698. # Open and parse a compressed Project file
  8699. try:
  8700. with lzma.open(filename) as f:
  8701. file_content = f.read().decode('utf-8')
  8702. d = json.loads(file_content, object_hook=dict2obj)
  8703. except Exception as e:
  8704. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8705. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8706. (_("Failed to open project file"), filename))
  8707. return
  8708. # Clear the current project
  8709. # # NOT THREAD SAFE # ##
  8710. if run_from_arg is True:
  8711. pass
  8712. elif cli is True:
  8713. self.delete_selection_shape()
  8714. else:
  8715. self.on_file_new()
  8716. # Project options
  8717. self.options.update(d['options'])
  8718. self.project_filename = filename
  8719. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8720. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8721. if cli is None:
  8722. self.set_screen_units(self.options["units"])
  8723. # Re create objects
  8724. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8725. for obj in d['objs']:
  8726. def obj_init(obj_inst, app_inst):
  8727. obj_inst.from_dict(obj)
  8728. App.log.debug("Recreating from opened project an %s object: %s" %
  8729. (obj['kind'].capitalize(), obj['options']['name']))
  8730. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8731. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8732. if cli is None:
  8733. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8734. obj['kind'].upper(),
  8735. obj['options']['name']
  8736. )
  8737. )
  8738. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8739. self.inform.emit('[success] %s: %s' %
  8740. (_("Project loaded from"), filename))
  8741. self.should_we_save = False
  8742. self.file_opened.emit("project", filename)
  8743. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8744. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8745. if cli is None:
  8746. self.set_ui_title(name=self.project_filename)
  8747. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8748. def propagate_defaults(self, silent=False):
  8749. """
  8750. This method is used to set default values in classes. It's
  8751. an alternative to project options but allows the use
  8752. of values invisible to the user.
  8753. :return: None
  8754. """
  8755. if silent is False:
  8756. self.log.debug("propagate_defaults()")
  8757. # Which objects to update the given parameters.
  8758. routes = {
  8759. "global_zdownrate": CNCjob,
  8760. "excellon_zeros": Excellon,
  8761. "excellon_format_upper_in": Excellon,
  8762. "excellon_format_lower_in": Excellon,
  8763. "excellon_format_upper_mm": Excellon,
  8764. "excellon_format_lower_mm": Excellon,
  8765. "excellon_units": Excellon,
  8766. "gerber_use_buffer_for_union": Gerber,
  8767. "geometry_multidepth": Geometry
  8768. }
  8769. for param in routes:
  8770. if param in routes[param].defaults:
  8771. try:
  8772. routes[param].defaults[param] = self.defaults[param]
  8773. if silent is False:
  8774. self.log.debug(" " + param + " OK")
  8775. except KeyError:
  8776. if silent is False:
  8777. self.log.debug(" ERROR: " + param + " not in defaults.")
  8778. else:
  8779. # Try extracting the name:
  8780. # classname_param here is param in the object
  8781. if param.find(routes[param].__name__.lower() + "_") == 0:
  8782. p = param[len(routes[param].__name__) + 1:]
  8783. if p in routes[param].defaults:
  8784. routes[param].defaults[p] = self.defaults[param]
  8785. if silent is False:
  8786. self.log.debug(" " + param + " OK!")
  8787. def restore_main_win_geom(self):
  8788. try:
  8789. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8790. self.defaults["global_def_win_y"],
  8791. self.defaults["global_def_win_w"],
  8792. self.defaults["global_def_win_h"])
  8793. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8794. except KeyError as e:
  8795. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8796. def plot_all(self, zoom=True):
  8797. """
  8798. Re-generates all plots from all objects.
  8799. :return: None
  8800. """
  8801. self.log.debug("Plot_all()")
  8802. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8803. for obj in self.collection.get_list():
  8804. def worker_task(obj):
  8805. with self.proc_container.new("Plotting"):
  8806. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8807. if zoom:
  8808. self.object_plotted.emit(obj)
  8809. # Send to worker
  8810. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8811. def register_folder(self, filename):
  8812. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8813. def register_save_folder(self, filename):
  8814. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8815. def set_progress_bar(self, percentage, text=""):
  8816. self.ui.progress_bar.setValue(int(percentage))
  8817. def setup_shell(self):
  8818. """
  8819. Creates shell functions. Runs once at startup.
  8820. :return: None
  8821. """
  8822. self.log.debug("setup_shell()")
  8823. def shelp(p=None):
  8824. if not p:
  8825. return _("Available commands:\n") + \
  8826. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8827. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8828. if p not in commands:
  8829. return "Unknown command: %s" % p
  8830. return commands[p]["help"]
  8831. # --- Migrated to new architecture ---
  8832. # def options(name):
  8833. # ops = self.collection.get_by_name(str(name)).options
  8834. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8835. def h(*args):
  8836. """
  8837. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8838. and standalone parameters into list.
  8839. """
  8840. kwa = {}
  8841. a = []
  8842. n = len(args)
  8843. name = None
  8844. for i in range(n):
  8845. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8846. if match:
  8847. assert name is None
  8848. name = match.group(1)
  8849. continue
  8850. if name is None:
  8851. a.append(args[i])
  8852. else:
  8853. kwa[name] = args[i]
  8854. name = None
  8855. return a, kwa
  8856. @contextmanager
  8857. def wait_signal(signal, timeout=10000):
  8858. """
  8859. Block loop until signal emitted, timeout (ms) elapses
  8860. or unhandled exception happens in a thread.
  8861. :param timeout: time after which the loop is exited
  8862. :param signal: Signal to wait for.
  8863. """
  8864. loop = QtCore.QEventLoop()
  8865. # Normal termination
  8866. signal.connect(loop.quit)
  8867. # Termination by exception in thread
  8868. self.thread_exception.connect(loop.quit)
  8869. status = {'timed_out': False}
  8870. def report_quit():
  8871. status['timed_out'] = True
  8872. loop.quit()
  8873. yield
  8874. # Temporarily change how exceptions are managed.
  8875. oeh = sys.excepthook
  8876. ex = []
  8877. def except_hook(type_, value, traceback_):
  8878. ex.append(value)
  8879. oeh(type_, value, traceback_)
  8880. sys.excepthook = except_hook
  8881. # Terminate on timeout
  8882. if timeout is not None:
  8883. QtCore.QTimer.singleShot(timeout, report_quit)
  8884. # # ## Block ## ##
  8885. loop.exec_()
  8886. # Restore exception management
  8887. sys.excepthook = oeh
  8888. if ex:
  8889. self.raiseTclError(str(ex[0]))
  8890. if status['timed_out']:
  8891. raise Exception('Timed out!')
  8892. def make_docs():
  8893. output = ''
  8894. import collections
  8895. od = collections.OrderedDict(sorted(commands.items()))
  8896. for cmd_, val in od.items():
  8897. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8898. t = val['help']
  8899. usage_i = t.find('>')
  8900. if usage_i < 0:
  8901. expl = t
  8902. output += expl + '\n\n'
  8903. continue
  8904. expl = t[:usage_i - 1]
  8905. output += expl + '\n\n'
  8906. end_usage_i = t[usage_i:].find('\n')
  8907. if end_usage_i < 0:
  8908. end_usage_i = len(t[usage_i:])
  8909. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8910. else:
  8911. extras = t[usage_i+end_usage_i+1:]
  8912. parts = [s.strip() for s in extras.split('\n')]
  8913. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8914. for p in parts:
  8915. output += ' ' + p + '\n\n'
  8916. return output
  8917. '''
  8918. Howto implement TCL shell commands:
  8919. All parameters passed to command should be possible to set as None and test it afterwards.
  8920. This is because we need to see error caused in tcl,
  8921. if None value as default parameter is not allowed TCL will return empty error.
  8922. Use:
  8923. def mycommand(name=None,...):
  8924. Test it like this:
  8925. if name is None:
  8926. self.raise_tcl_error('Argument name is missing.')
  8927. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8928. otherwise we will miss it and processing will silently continue.
  8929. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8930. which is catched in exec_command and displayed in TCL shell console with red background.
  8931. Error in console is displayed with TCL trace.
  8932. This behavior works only within main thread,
  8933. errors with promissed tasks can be catched and detected only with log.
  8934. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8935. TCL shell.
  8936. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8937. '''
  8938. commands = {
  8939. 'help': {
  8940. 'fcn': shelp,
  8941. 'help': _("Shows list of commands.")
  8942. },
  8943. }
  8944. # Import/overwrite tcl commands as objects of TclCommand descendants
  8945. # This modifies the variable 'commands'.
  8946. tclCommands.register_all_commands(self, commands)
  8947. # Add commands to the tcl interpreter
  8948. for cmd in commands:
  8949. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8950. # Make the tcl puts function return instead of print to stdout
  8951. self.tcl.eval('''
  8952. rename puts original_puts
  8953. proc puts {args} {
  8954. if {[llength $args] == 1} {
  8955. return "[lindex $args 0]"
  8956. } else {
  8957. eval original_puts $args
  8958. }
  8959. }
  8960. ''')
  8961. def setup_recent_items(self):
  8962. # TODO: Move this to constructor
  8963. icons = {
  8964. "gerber": "share/flatcam_icon16.png",
  8965. "excellon": "share/drill16.png",
  8966. 'geometry': "share/geometry16.png",
  8967. "cncjob": "share/cnc16.png",
  8968. "project": "share/project16.png",
  8969. "svg": "share/geometry16.png",
  8970. "dxf": "share/dxf16.png",
  8971. "pdf": "share/pdf32.png",
  8972. "image": "share/image16.png"
  8973. }
  8974. openers = {
  8975. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8976. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8977. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8978. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8979. 'project': self.open_project,
  8980. 'svg': self.import_svg,
  8981. 'dxf': self.import_dxf,
  8982. 'image': self.import_image,
  8983. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8984. }
  8985. # Open recent file for files
  8986. try:
  8987. f = open(self.data_path + '/recent.json')
  8988. except IOError:
  8989. App.log.error("Failed to load recent item list.")
  8990. self.inform.emit('[ERROR_NOTCL] %s' %
  8991. _("Failed to load recent item list."))
  8992. return
  8993. try:
  8994. self.recent = json.load(f)
  8995. except json.scanner.JSONDecodeError:
  8996. App.log.error("Failed to parse recent item list.")
  8997. self.inform.emit('[ERROR_NOTCL] %s' %
  8998. _("Failed to parse recent item list."))
  8999. f.close()
  9000. return
  9001. f.close()
  9002. # Open recent file for projects
  9003. try:
  9004. fp = open(self.data_path + '/recent_projects.json')
  9005. except IOError:
  9006. App.log.error("Failed to load recent project item list.")
  9007. self.inform.emit('[ERROR_NOTCL] %s' %
  9008. _("Failed to load recent projects item list."))
  9009. return
  9010. try:
  9011. self.recent_projects = json.load(fp)
  9012. except json.scanner.JSONDecodeError:
  9013. App.log.error("Failed to parse recent project item list.")
  9014. self.inform.emit('[ERROR_NOTCL] %s' %
  9015. _("Failed to parse recent project item list."))
  9016. fp.close()
  9017. return
  9018. fp.close()
  9019. # Closure needed to create callbacks in a loop.
  9020. # Otherwise late binding occurs.
  9021. def make_callback(func, fname):
  9022. def opener():
  9023. func(fname)
  9024. return opener
  9025. def reset_recent_files():
  9026. # Reset menu
  9027. self.ui.recent.clear()
  9028. self.recent = []
  9029. try:
  9030. f = open(self.data_path + '/recent.json', 'w')
  9031. except IOError:
  9032. App.log.error("Failed to open recent items file for writing.")
  9033. return
  9034. json.dump(self.recent, f)
  9035. def reset_recent_projects():
  9036. # Reset menu
  9037. self.ui.recent_projects.clear()
  9038. self.recent_projects = []
  9039. try:
  9040. fp = open(self.data_path + '/recent_projects.json', 'w')
  9041. except IOError:
  9042. App.log.error("Failed to open recent projects items file for writing.")
  9043. return
  9044. json.dump(self.recent, fp)
  9045. # Reset menu
  9046. self.ui.recent.clear()
  9047. self.ui.recent_projects.clear()
  9048. # Create menu items for projects
  9049. for recent in self.recent_projects:
  9050. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9051. if recent['kind'] == 'project':
  9052. try:
  9053. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9054. # Attach callback
  9055. o = make_callback(openers[recent["kind"]], recent['filename'])
  9056. action.triggered.connect(o)
  9057. self.ui.recent_projects.addAction(action)
  9058. except KeyError:
  9059. App.log.error("Unsupported file type: %s" % recent["kind"])
  9060. # Last action in Recent Files menu is one that Clear the content
  9061. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9062. clear_action_proj.triggered.connect(reset_recent_projects)
  9063. self.ui.recent_projects.addSeparator()
  9064. self.ui.recent_projects.addAction(clear_action_proj)
  9065. # Create menu items for files
  9066. for recent in self.recent:
  9067. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9068. if recent['kind'] != 'project':
  9069. try:
  9070. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9071. # Attach callback
  9072. o = make_callback(openers[recent["kind"]], recent['filename'])
  9073. action.triggered.connect(o)
  9074. self.ui.recent.addAction(action)
  9075. except KeyError:
  9076. App.log.error("Unsupported file type: %s" % recent["kind"])
  9077. # Last action in Recent Files menu is one that Clear the content
  9078. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9079. clear_action.triggered.connect(reset_recent_files)
  9080. self.ui.recent.addSeparator()
  9081. self.ui.recent.addAction(clear_action)
  9082. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9083. # self.ui.menufilerecent.set_submenu(recent_menu)
  9084. # recent_menu.show_all()
  9085. # self.ui.recent.show()
  9086. self.log.debug("Recent items list has been populated.")
  9087. def setup_component_editor(self):
  9088. # label = QtWidgets.QLabel("Choose an item from Project")
  9089. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9090. sel_title = QtWidgets.QTextEdit(
  9091. _('<b>Shortcut Key List</b>'))
  9092. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9093. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9094. settings = QSettings("Open Source", "FlatCAM")
  9095. if settings.contains("notebook_font_size"):
  9096. fsize = settings.value('notebook_font_size', type=int)
  9097. else:
  9098. fsize = 12
  9099. tsize = fsize + int(fsize / 2)
  9100. # selected_text = (_('''
  9101. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9102. #
  9103. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9104. # The normal flow when working in FlatCAM is the following:</span></p>
  9105. #
  9106. # <ol>
  9107. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9108. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9109. # even dragging and dropping the files on the GUI.<br />
  9110. # <br />
  9111. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9112. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9113. # &nbsp;</li>
  9114. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9115. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9116. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9117. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9118. # <br />
  9119. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9120. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9121. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9122. # it even if it was out of focus.<br />
  9123. # <br />
  9124. # You can change the parameters in this screen and the flow direction is like this:<br />
  9125. # <br />
  9126. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9127. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9128. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9129. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9130. # </ol>
  9131. #
  9132. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9133. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9134. # <strong>F3</strong>.</span></p>
  9135. #
  9136. # ''').format(fsize=fsize, tsize=tsize))
  9137. selected_text = '''
  9138. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9139. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9140. {s1}</span></p>
  9141. <ol>
  9142. <li><span style="font-size:{fsize}px">{s2}<br />
  9143. <br />
  9144. {s3}</span><br />
  9145. &nbsp;</li>
  9146. <li><span style="font-size:{fsize}px">{s4}<br />
  9147. &nbsp;</li>
  9148. <br />
  9149. <li><span style="font-size:{fsize}px">{s5}<br />
  9150. &nbsp;</li>
  9151. <br />
  9152. <li><span style="font-size:{fsize}px">{s6}<br />
  9153. <br />
  9154. {s7}</span></li>
  9155. </ol>
  9156. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9157. '''.format(
  9158. title=_("Selected Tab - Choose an Item from Project Tab"),
  9159. subtitle=_("Details"),
  9160. s1=_("The normal flow when working in FlatCAM is the following:"),
  9161. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9162. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9163. "files on the GUI."),
  9164. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9165. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9166. "actions offered within the app."),
  9167. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9168. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9169. "SELECTED TAB will be updated with the object properties according to its kind: "
  9170. "Gerber, Excellon, Geometry or CNCJob object."),
  9171. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9172. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9173. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9174. "the SELECTED TAB and populate it even if it was out of focus."),
  9175. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9176. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9177. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9178. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9179. "(again, done in SELECTED TAB) --> Save GCode."),
  9180. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9181. "or through its own key shortcut: <b>F3</b>."),
  9182. tsize=tsize,
  9183. fsize=fsize
  9184. )
  9185. sel_title.setText(selected_text)
  9186. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9187. self.ui.selected_scroll_area.setWidget(sel_title)
  9188. def setup_obj_classes(self):
  9189. """
  9190. Sets up application specifics on the FlatCAMObj class.
  9191. :return: None
  9192. """
  9193. FlatCAMObj.app = self
  9194. ObjectCollection.app = self
  9195. Gerber.app = self
  9196. Excellon.app = self
  9197. Geometry.app = self
  9198. CNCjob.app = self
  9199. FCProcess.app = self
  9200. FCProcessContainer.app = self
  9201. def version_check(self):
  9202. """
  9203. Checks for the latest version of the program. Alerts the
  9204. user if theirs is outdated. This method is meant to be run
  9205. in a separate thread.
  9206. :return: None
  9207. """
  9208. self.log.debug("version_check()")
  9209. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9210. full_url = App.version_url + \
  9211. "?s=" + str(self.defaults['global_serial']) + \
  9212. "&v=" + str(self.version) + \
  9213. "&os=" + str(self.os) + \
  9214. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9215. else:
  9216. # no_stats dict; just so it won't break things on website
  9217. no_ststs_dict = {}
  9218. no_ststs_dict["global_ststs"] = {}
  9219. full_url = App.version_url + \
  9220. "?s=" + str(self.defaults['global_serial']) + \
  9221. "&v=" + str(self.version) + \
  9222. "&os=" + str(self.os) + \
  9223. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9224. App.log.debug("Checking for updates @ %s" % full_url)
  9225. # ## Get the data
  9226. try:
  9227. f = urllib.request.urlopen(full_url)
  9228. except:
  9229. # App.log.warning("Failed checking for latest version. Could not connect.")
  9230. self.log.warning("Failed checking for latest version. Could not connect.")
  9231. self.inform.emit('[WARNING_NOTCL] %s' %
  9232. _("Failed checking for latest version. Could not connect."))
  9233. return
  9234. try:
  9235. data = json.load(f)
  9236. except Exception as e:
  9237. App.log.error("Could not parse information about latest version.")
  9238. self.inform.emit('[ERROR_NOTCL] %s' %
  9239. _("Could not parse information about latest version."))
  9240. App.log.debug("json.load(): %s" % str(e))
  9241. f.close()
  9242. return
  9243. f.close()
  9244. # ## Latest version?
  9245. if self.version >= data["version"]:
  9246. App.log.debug("FlatCAM is up to date!")
  9247. self.inform.emit('[success] %s' %
  9248. _("FlatCAM is up to date!"))
  9249. return
  9250. App.log.debug("Newer version available.")
  9251. self.message.emit(
  9252. _("Newer Version Available"),
  9253. _("There is a newer version of FlatCAM available for download:\n\n") +
  9254. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9255. _("info")
  9256. )
  9257. def on_plotcanvas_setup(self, container=None):
  9258. """
  9259. This is doing the setup for the plot area (VisPy canvas)
  9260. :param container: widget where to install the canvas
  9261. :return: None
  9262. """
  9263. if container:
  9264. plot_container = container
  9265. else:
  9266. plot_container = self.ui.right_layout
  9267. if self.is_legacy is False:
  9268. self.plotcanvas = PlotCanvas(plot_container, self)
  9269. else:
  9270. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9271. # So it can receive key presses
  9272. self.plotcanvas.native.setFocus()
  9273. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9274. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9275. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9276. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9277. # Keys over plot enabled
  9278. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9279. self.app_cursor = self.plotcanvas.new_cursor()
  9280. if self.ui.grid_snap_btn.isChecked():
  9281. self.app_cursor.enabled = True
  9282. else:
  9283. self.app_cursor.enabled = False
  9284. if self.is_legacy is False:
  9285. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9286. else:
  9287. # will use the default Matplotlib axes
  9288. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9289. def on_zoom_fit(self, event):
  9290. """
  9291. Callback for zoom-out request. This can be either from the corresponding
  9292. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9293. with axes limits from the geometry bounds of all objects.
  9294. :param event: Ignored.
  9295. :return: None
  9296. """
  9297. if self.is_legacy is False:
  9298. self.plotcanvas.fit_view()
  9299. else:
  9300. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9301. width = xmax - xmin
  9302. height = ymax - ymin
  9303. xmin -= 0.05 * width
  9304. xmax += 0.05 * width
  9305. ymin -= 0.05 * height
  9306. ymax += 0.05 * height
  9307. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9308. def on_zoom_in(self):
  9309. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9310. def on_zoom_out(self):
  9311. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9312. def disable_all_plots(self):
  9313. self.report_usage("disable_all_plots()")
  9314. self.disable_plots(self.collection.get_list())
  9315. self.inform.emit('[success] %s' %
  9316. _("All plots disabled."))
  9317. def disable_other_plots(self):
  9318. self.report_usage("disable_other_plots()")
  9319. self.disable_plots(self.collection.get_non_selected())
  9320. self.inform.emit('[success] %s' %
  9321. _("All non selected plots disabled."))
  9322. def enable_all_plots(self):
  9323. self.report_usage("enable_all_plots()")
  9324. self.enable_plots(self.collection.get_list())
  9325. self.inform.emit('[success] %s' %
  9326. _("All plots enabled."))
  9327. def on_enable_sel_plots(self):
  9328. log.debug("App.on_enable_sel_plot()")
  9329. object_list = self.collection.get_selected()
  9330. self.enable_plots(objects=object_list)
  9331. self.inform.emit('[success] %s' %
  9332. _("Selected plots enabled..."))
  9333. def on_disable_sel_plots(self):
  9334. log.debug("App.on_disable_sel_plot()")
  9335. # self.inform.emit(_("Disabling plots ..."))
  9336. object_list = self.collection.get_selected()
  9337. self.disable_plots(objects=object_list)
  9338. self.inform.emit('[success] %s' %
  9339. _("Selected plots disabled..."))
  9340. def enable_plots(self, objects):
  9341. """
  9342. Disables plots
  9343. :param objects: list of Objects to be enabled
  9344. :return:
  9345. """
  9346. log.debug("Enabling plots ...")
  9347. # self.inform.emit(_("Working ..."))
  9348. for obj in objects:
  9349. if obj.options['plot'] is False:
  9350. obj.options.set_change_callback(lambda x: None)
  9351. obj.options['plot'] = True
  9352. obj.options.set_change_callback(obj.on_options_change)
  9353. def worker_task(objects):
  9354. with self.proc_container.new(_("Enabling plots ...")):
  9355. for obj in objects:
  9356. # obj.options['plot'] = True
  9357. if isinstance(obj, FlatCAMCNCjob):
  9358. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9359. else:
  9360. obj.plot(visible=True)
  9361. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9362. # self.plots_updated.emit()
  9363. def disable_plots(self, objects):
  9364. """
  9365. Disables plots
  9366. :param objects: list of Objects to be disabled
  9367. :return:
  9368. """
  9369. # if no objects selected then do nothing
  9370. if not self.collection.get_selected():
  9371. return
  9372. log.debug("Disabling plots ...")
  9373. # self.inform.emit(_("Working ..."))
  9374. for obj in objects:
  9375. if obj.options['plot'] is True:
  9376. obj.options.set_change_callback(lambda x: None)
  9377. obj.options['plot'] = False
  9378. obj.options.set_change_callback(obj.on_options_change)
  9379. try:
  9380. self.delete_selection_shape()
  9381. except Exception as e:
  9382. log.debug("App.disable_plots() --> %s" % str(e))
  9383. # self.plots_updated.emit()
  9384. def worker_task(objects):
  9385. with self.proc_container.new(_("Disabling plots ...")):
  9386. for obj in objects:
  9387. # obj.options['plot'] = True
  9388. if isinstance(obj, FlatCAMCNCjob):
  9389. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9390. else:
  9391. obj.plot(visible=False)
  9392. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9393. def toggle_plots(self, objects):
  9394. """
  9395. Toggle plots visibility
  9396. :param objects: list of Objects for which to be toggled the visibility
  9397. :return:
  9398. """
  9399. # if no objects selected then do nothing
  9400. if not self.collection.get_selected():
  9401. return
  9402. log.debug("Toggling plots ...")
  9403. self.inform.emit(_("Working ..."))
  9404. for obj in objects:
  9405. if obj.options['plot'] is False:
  9406. obj.options['plot'] = True
  9407. else:
  9408. obj.options['plot'] = False
  9409. self.plots_updated.emit()
  9410. def clear_plots(self):
  9411. objects = self.collection.get_list()
  9412. for obj in objects:
  9413. obj.clear(obj == objects[-1])
  9414. # Clear pool to free memory
  9415. self.clear_pool()
  9416. def generate_cnc_job(self, objects):
  9417. self.report_usage("generate_cnc_job()")
  9418. # for obj in objects:
  9419. # obj.generatecncjob()
  9420. for obj in objects:
  9421. obj.on_generatecnc_button_click()
  9422. def save_project(self, filename, quit_action=False, silent=False):
  9423. """
  9424. Saves the current project to the specified file.
  9425. :param filename: Name of the file in which to save.
  9426. :type filename: str
  9427. :param quit_action: if the project saving will be followed by an app quit; boolean
  9428. :param silent: if True will not display status messages
  9429. :return: None
  9430. """
  9431. self.log.debug("save_project()")
  9432. self.save_in_progress = True
  9433. with self.proc_container.new(_("Saving FlatCAM Project")):
  9434. # Capture the latest changes
  9435. # Current object
  9436. try:
  9437. self.collection.get_active().read_form()
  9438. except:
  9439. self.log.debug("There was no active object")
  9440. pass
  9441. # Project options
  9442. self.options_read_form()
  9443. # Serialize the whole project
  9444. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9445. "options": self.options,
  9446. "version": self.version}
  9447. if self.defaults["global_save_compressed"] is True:
  9448. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9449. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9450. # # Write
  9451. f.write(g)
  9452. self.inform.emit('[success] %s: %s' %
  9453. (_("Project saved to"), filename))
  9454. else:
  9455. # Open file
  9456. try:
  9457. f = open(filename, 'w')
  9458. except IOError:
  9459. App.log.error("Failed to open file for saving: %s", filename)
  9460. return
  9461. # Write
  9462. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9463. f.close()
  9464. # verification of the saved project
  9465. # Open and parse
  9466. try:
  9467. saved_f = open(filename, 'r')
  9468. except IOError:
  9469. if silent is False:
  9470. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9471. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9472. )
  9473. return
  9474. try:
  9475. saved_d = json.load(saved_f, object_hook=dict2obj)
  9476. except:
  9477. if silent is False:
  9478. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9479. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9480. )
  9481. f.close()
  9482. return
  9483. saved_f.close()
  9484. if silent is False:
  9485. if 'version' in saved_d:
  9486. self.inform.emit('[success] %s: %s' %
  9487. (_("Project saved to"), filename))
  9488. else:
  9489. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9490. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9491. )
  9492. settings = QSettings("Open Source", "FlatCAM")
  9493. lock_state = self.ui.lock_action.isChecked()
  9494. settings.setValue('toolbar_lock', lock_state)
  9495. # This will write the setting to the platform specific storage.
  9496. del settings
  9497. # if quit:
  9498. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9499. # t.start()
  9500. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9501. def start_delayed_quit(self, delay, filename, should_quit=None):
  9502. """
  9503. :param delay: period of checking if project file size is more than zero; in seconds
  9504. :param filename: the name of the project file to be checked periodically for size more than zero
  9505. :param should_quit: if the task finished will be followed by an app quit; boolean
  9506. :return:
  9507. """
  9508. to_quit = should_quit
  9509. self.save_timer = QtCore.QTimer()
  9510. self.save_timer.setInterval(delay)
  9511. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9512. self.save_timer.start()
  9513. def check_project_file_size(self, filename, should_quit=None):
  9514. """
  9515. :param filename: the name of the project file to be checked periodically for size more than zero
  9516. :param should_quit: will quit the app if True; boolean
  9517. :return:
  9518. """
  9519. try:
  9520. if os.stat(filename).st_size > 0:
  9521. self.save_in_progress = False
  9522. self.save_timer.stop()
  9523. if should_quit:
  9524. self.app_quit.emit()
  9525. except Exception as e:
  9526. traceback.print_exc()
  9527. def on_options_app2project(self):
  9528. """
  9529. Callback for Options->Transfer Options->App=>Project. Copies options
  9530. from application defaults to project defaults.
  9531. :return: None
  9532. """
  9533. self.report_usage("on_options_app2project")
  9534. self.defaults_read_form()
  9535. self.options.update(self.defaults)
  9536. self.options_write_form()
  9537. def on_options_project2app(self):
  9538. """
  9539. Callback for Options->Transfer Options->Project=>App. Copies options
  9540. from project defaults to application defaults.
  9541. :return: None
  9542. """
  9543. self.report_usage("on_options_project2app")
  9544. self.options_read_form()
  9545. self.defaults.update(self.options)
  9546. self.defaults_write_form()
  9547. def on_options_project2object(self):
  9548. """
  9549. Callback for Options->Transfer Options->Project=>Object. Copies options
  9550. from project defaults to the currently selected object.
  9551. :return: None
  9552. """
  9553. self.report_usage("on_options_project2object")
  9554. self.options_read_form()
  9555. obj = self.collection.get_active()
  9556. if obj is None:
  9557. self.inform.emit('[WARNING_NOTCL] %s' %
  9558. _("No object selected."))
  9559. return
  9560. for option in self.options:
  9561. if option.find(obj.kind + "_") == 0:
  9562. oname = option[len(obj.kind) + 1:]
  9563. obj.options[oname] = self.options[option]
  9564. obj.to_form() # Update UI
  9565. def on_options_object2project(self):
  9566. """
  9567. Callback for Options->Transfer Options->Object=>Project. Copies options
  9568. from the currently selected object to project defaults.
  9569. :return: None
  9570. """
  9571. self.report_usage("on_options_object2project")
  9572. obj = self.collection.get_active()
  9573. if obj is None:
  9574. self.inform.emit('[WARNING_NOTCL] %s' %
  9575. _("No object selected."))
  9576. return
  9577. obj.read_form()
  9578. for option in obj.options:
  9579. if option in ['name']: # TODO: Handle this better...
  9580. continue
  9581. self.options[obj.kind + "_" + option] = obj.options[option]
  9582. self.options_write_form()
  9583. def on_options_object2app(self):
  9584. """
  9585. Callback for Options->Transfer Options->Object=>App. Copies options
  9586. from the currently selected object to application defaults.
  9587. :return: None
  9588. """
  9589. self.report_usage("on_options_object2app")
  9590. obj = self.collection.get_active()
  9591. if obj is None:
  9592. self.inform.emit('[WARNING_NOTCL] %s' %
  9593. _("No object selected."))
  9594. return
  9595. obj.read_form()
  9596. for option in obj.options:
  9597. if option in ['name']: # TODO: Handle this better...
  9598. continue
  9599. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9600. self.defaults_write_form()
  9601. def on_options_app2object(self):
  9602. """
  9603. Callback for Options->Transfer Options->App=>Object. Copies options
  9604. from application defaults to the currently selected object.
  9605. :return: None
  9606. """
  9607. self.report_usage("on_options_app2object")
  9608. self.defaults_read_form()
  9609. obj = self.collection.get_active()
  9610. if obj is None:
  9611. self.inform.emit('[WARNING_NOTCL] %s' %
  9612. _("No object selected."))
  9613. return
  9614. for option in self.defaults:
  9615. if option.find(obj.kind + "_") == 0:
  9616. oname = option[len(obj.kind) + 1:]
  9617. obj.options[oname] = self.defaults[option]
  9618. obj.to_form() # Update UI
  9619. class ArgsThread(QtCore.QObject):
  9620. open_signal = pyqtSignal(list)
  9621. start = pyqtSignal()
  9622. if sys.platform == 'win32':
  9623. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9624. else:
  9625. address = ('/tmp/testipc', 'AF_UNIX')
  9626. def __init__(self):
  9627. super(ArgsThread, self).__init__()
  9628. self.start.connect(self.run)
  9629. def my_loop(self, address):
  9630. try:
  9631. listener = Listener(*address)
  9632. while True:
  9633. conn = listener.accept()
  9634. self.serve(conn)
  9635. except socket.error as e:
  9636. conn = Client(*address)
  9637. conn.send(sys.argv)
  9638. conn.send('close')
  9639. # close the current instance only if there are args
  9640. if len(sys.argv) > 1:
  9641. sys.exit()
  9642. def serve(self, conn):
  9643. while True:
  9644. msg = conn.recv()
  9645. if msg == 'close':
  9646. break
  9647. self.open_signal.emit(msg)
  9648. conn.close()
  9649. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9650. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9651. @pyqtSlot()
  9652. def run(self):
  9653. self.my_loop(self.address)
  9654. class GracefulException(Exception):
  9655. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9656. def __init__(self):
  9657. super().__init__()
  9658. def __str__(self):
  9659. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9660. # end of file