FlatCAMApp.py 516 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472
  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/20"
  106. beta = True
  107. # current date now
  108. date = str(datetime.today()).rpartition('.')[0]
  109. date = ''.join(c for c in date if c not in ':-')
  110. date = date.replace(' ', '_')
  111. # URL for update checks and statistics
  112. version_url = "http://flatcam.org/version"
  113. # App URL
  114. app_url = "http://flatcam.org"
  115. # Manual URL
  116. manual_url = "http://flatcam.org/manual/index.html"
  117. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  118. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  119. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  120. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  121. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  122. # this variable will hold the project status
  123. # if True it will mean that the project was modified and not saved
  124. should_we_save = False
  125. # flag is True if saving action has been triggered
  126. save_in_progress = False
  127. # ###########################################################################
  128. # ############################# Signals ################################
  129. # ###########################################################################
  130. # Inform the user
  131. # Handled by:
  132. # * App.info() --> Print on the status bar
  133. inform = QtCore.pyqtSignal(str)
  134. app_quit = QtCore.pyqtSignal()
  135. # General purpose background task
  136. worker_task = QtCore.pyqtSignal(dict)
  137. # File opened
  138. # Handled by:
  139. # * register_folder()
  140. # * register_recent()
  141. # Note: Setting the parameters to unicode does not seem
  142. # to have an effect. Then are received as Qstring
  143. # anyway.
  144. # File type and filename
  145. file_opened = QtCore.pyqtSignal(str, str)
  146. # File type and filename
  147. file_saved = QtCore.pyqtSignal(str, str)
  148. # Percentage of progress
  149. progress = QtCore.pyqtSignal(int)
  150. plots_updated = QtCore.pyqtSignal()
  151. # Emitted by new_object() and passes the new object as argument, plot flag.
  152. # on_object_created() adds the object to the collection, plots on appropriate flag
  153. # and emits new_object_available.
  154. object_created = QtCore.pyqtSignal(object, bool, bool)
  155. # Emitted when a object has been changed (like scaled, mirrored)
  156. object_changed = QtCore.pyqtSignal(object)
  157. # Emitted after object has been plotted.
  158. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  159. object_plotted = QtCore.pyqtSignal(object)
  160. # Emitted when a new object has been added or deleted from/to the collection
  161. object_status_changed = QtCore.pyqtSignal(object, str)
  162. message = QtCore.pyqtSignal(str, str, str)
  163. # Emmited when shell command is finished(one command only)
  164. shell_command_finished = QtCore.pyqtSignal(object)
  165. # Emitted when multiprocess pool has been recreated
  166. pool_recreated = QtCore.pyqtSignal(object)
  167. # Emitted when an unhandled exception happens
  168. # in the worker task.
  169. thread_exception = QtCore.pyqtSignal(object)
  170. # used to signal that there are arguments for the app
  171. args_at_startup = QtCore.pyqtSignal(list)
  172. # a reusable signal to replot a list of objects
  173. # should be disconnected after use so it can be reused
  174. replot_signal = pyqtSignal(list)
  175. def __init__(self, user_defaults=True, post_gui=None):
  176. """
  177. Starts the application.
  178. :return: app
  179. :rtype: App
  180. """
  181. App.log.info("FlatCAM Starting...")
  182. self.main_thread = QtWidgets.QApplication.instance().thread()
  183. # ############################################################################
  184. # # ################# OS-specific ############################################
  185. # ############################################################################
  186. portable = False
  187. # Folder for user settings.
  188. if sys.platform == 'win32':
  189. # #########################################################################
  190. # Setup the listening thread for another instance launching with args #####
  191. # #########################################################################
  192. # make sure the thread is stored by using a self. otherwise it's garbage collected
  193. self.th = QtCore.QThread()
  194. self.th.start(priority=QtCore.QThread.LowestPriority)
  195. self.new_launch = ArgsThread()
  196. self.new_launch.open_signal[list].connect(self.on_startup_args)
  197. self.new_launch.moveToThread(self.th)
  198. self.new_launch.start.emit()
  199. from win32com.shell import shell, shellcon
  200. if platform.architecture()[0] == '32bit':
  201. App.log.debug("Win32!")
  202. else:
  203. App.log.debug("Win64!")
  204. # #########################################################################
  205. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  206. # #########################################################################
  207. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  208. try:
  209. with open(config_file, 'r'):
  210. pass
  211. except FileNotFoundError:
  212. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  213. try:
  214. with open(config_file, 'r') as f:
  215. try:
  216. for line in f:
  217. param = str(line).replace('\n', '').rpartition('=')
  218. if param[0] == 'portable':
  219. try:
  220. portable = eval(param[2])
  221. except NameError:
  222. portable = False
  223. if param[0] == 'headless':
  224. if param[2].lower() == 'true':
  225. self.cmd_line_headless = 1
  226. else:
  227. self.cmd_line_headless = None
  228. except Exception as e:
  229. log.debug('App.__init__() -->%s' % str(e))
  230. return
  231. except FileNotFoundError as e:
  232. log.debug(str(e))
  233. pass
  234. if portable is False:
  235. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  236. else:
  237. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  238. self.os = 'windows'
  239. else: # Linux/Unix/MacOS
  240. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  241. self.os = 'unix'
  242. # ##########################################################################
  243. # ################## Setup folders and files ###############################
  244. # ##########################################################################
  245. if not os.path.exists(self.data_path):
  246. os.makedirs(self.data_path)
  247. App.log.debug('Created data folder: ' + self.data_path)
  248. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  249. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  250. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  251. if not os.path.exists(self.postprocessorpaths):
  252. os.makedirs(self.postprocessorpaths)
  253. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  254. # create current_defaults.FlatConfig file if there is none
  255. try:
  256. f = open(self.data_path + '/current_defaults.FlatConfig')
  257. f.close()
  258. except IOError:
  259. App.log.debug('Creating empty current_defaults.FlatConfig')
  260. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  261. json.dump({}, f)
  262. f.close()
  263. # create factory_defaults.FlatConfig file if there is none
  264. try:
  265. f = open(self.data_path + '/factory_defaults.FlatConfig')
  266. f.close()
  267. except IOError:
  268. App.log.debug('Creating empty factory_defaults.FlatConfig')
  269. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  270. json.dump({}, f)
  271. f.close()
  272. # create a recent files json file if there is none
  273. try:
  274. f = open(self.data_path + '/recent.json')
  275. f.close()
  276. except IOError:
  277. App.log.debug('Creating empty recent.json')
  278. f = open(self.data_path + '/recent.json', 'w')
  279. json.dump([], f)
  280. f.close()
  281. # create a recent projects json file if there is none
  282. try:
  283. fp = open(self.data_path + '/recent_projects.json')
  284. fp.close()
  285. except IOError:
  286. App.log.debug('Creating empty recent_projects.json')
  287. fp = open(self.data_path + '/recent_projects.json', 'w')
  288. json.dump([], fp)
  289. fp.close()
  290. # Application directory. CHDIR to it. Otherwise, trying to load
  291. # GUI icons will fail as their path is relative.
  292. # This will fail under cx_freeze ...
  293. self.app_home = os.path.dirname(os.path.realpath(__file__))
  294. App.log.debug("Application path is " + self.app_home)
  295. App.log.debug("Started in " + os.getcwd())
  296. # cx_freeze workaround
  297. if os.path.isfile(self.app_home):
  298. self.app_home = os.path.dirname(self.app_home)
  299. os.chdir(self.app_home)
  300. # #############################################################################
  301. # ##################### CREATE MULTIPROCESSING POOL ###########################
  302. # #############################################################################
  303. self.pool = Pool()
  304. # ##########################################################################
  305. # ################## Setting the Splash Screen #############################
  306. # ##########################################################################
  307. settings = QSettings("Open Source", "FlatCAM")
  308. if settings.contains("splash_screen"):
  309. show_splash = settings.value("splash_screen")
  310. else:
  311. settings.setValue('splash_screen', 1)
  312. # This will write the setting to the platform specific storage.
  313. del settings
  314. show_splash = 1
  315. if show_splash and self.cmd_line_headless != 1:
  316. splash_pix = QtGui.QPixmap('share/splash.png')
  317. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  318. # self.splash.setMask(splash_pix.mask())
  319. # move splashscreen to the current monitor
  320. desktop = QtWidgets.QApplication.desktop()
  321. screen = desktop.screenNumber(QtGui.QCursor.pos())
  322. current_screen_center = desktop.availableGeometry(screen).center()
  323. self.splash.move(current_screen_center - self.splash.rect().center())
  324. self.splash.show()
  325. self.splash.showMessage(_("FlatCAM is initializing ..."),
  326. alignment=Qt.AlignBottom | Qt.AlignLeft,
  327. color=QtGui.QColor("gray"))
  328. else:
  329. show_splash = 0
  330. # #############################################################################
  331. # ##################### Initialize GUI ########################################
  332. # #############################################################################
  333. # FlatCAM colors used in plotting
  334. self.FC_light_green = '#BBF268BF'
  335. self.FC_dark_green = '#006E20BF'
  336. self.FC_light_blue = '#a5a5ffbf'
  337. self.FC_dark_blue = '#0000ffbf'
  338. QtCore.QObject.__init__(self)
  339. self.ui = FlatCAMGUI(self.version, self.beta, self)
  340. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  341. self.ui.final_save.connect(self.final_save)
  342. # #############################################################################
  343. # ############################## Data #########################################
  344. # #############################################################################
  345. self.recent = []
  346. self.recent_projects = []
  347. self.clipboard = QtWidgets.QApplication.clipboard()
  348. self.project_filename = None
  349. self.toggle_units_ignore = False
  350. # self.defaults_form = PreferencesUI()
  351. # when adding entries here read the comments in the method found bellow named:
  352. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  353. self.defaults_form_fields = {
  354. # General App
  355. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  356. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  357. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  358. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  359. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  360. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  361. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  362. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  363. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  364. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  365. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  366. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  367. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  368. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  369. # General GUI Preferences
  370. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  371. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  372. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  373. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  374. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  375. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  376. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  377. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  378. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  379. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  380. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  381. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  382. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  383. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  384. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  385. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  386. # General GUI Settings
  387. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  388. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  389. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  390. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  391. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  392. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  393. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  394. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  395. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  396. # Gerber General
  397. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  398. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  399. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  400. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  401. # Gerber Options
  402. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  403. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  404. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  405. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  406. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  407. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  408. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  409. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  410. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  411. # Gerber Advanced Options
  412. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  413. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  414. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  415. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  416. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  417. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  418. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  419. # Gerber Export
  420. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  421. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  422. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  423. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  424. # Gerber Editor
  425. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  426. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  427. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  428. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  429. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  430. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  431. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  432. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  433. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  434. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  435. "gerber_editor_circ_angle":
  436. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  437. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  438. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  439. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  440. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  441. # Excellon General
  442. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  443. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  444. "excellon_format_upper_in":
  445. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  446. "excellon_format_lower_in":
  447. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  448. "excellon_format_upper_mm":
  449. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  450. "excellon_format_lower_mm":
  451. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  452. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  453. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  454. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  455. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  456. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  457. # Excellon Options
  458. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  459. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  460. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  461. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  462. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  463. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  464. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  465. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  466. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  467. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  468. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  469. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  470. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  471. # Excellon Advanced Options
  472. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  473. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  474. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  475. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  476. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  477. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  478. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  479. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  480. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  481. # Excellon Export
  482. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  483. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  484. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  485. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  486. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  487. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  488. # Excellon Editor
  489. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  490. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  491. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  492. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  493. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  494. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  495. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  496. "excellon_editor_circ_angle":
  497. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  498. # Excellon Slots
  499. "excellon_editor_slot_direction":
  500. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  501. "excellon_editor_slot_angle":
  502. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  503. "excellon_editor_slot_length":
  504. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  505. # Excellon Slots
  506. "excellon_editor_slot_array_size":
  507. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  508. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  509. "excellon_editor_slot_lin_pitch":
  510. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  511. "excellon_editor_slot_lin_angle":
  512. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  513. "excellon_editor_slot_circ_dir":
  514. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  515. "excellon_editor_slot_circ_angle":
  516. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  517. # Geometry General
  518. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  519. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  520. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  521. # Geometry Options
  522. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  523. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  524. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  525. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  526. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  527. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  528. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  529. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  530. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  531. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  532. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  533. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  534. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  535. # Geometry Advanced Options
  536. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  537. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  538. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  539. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  540. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  541. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  542. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  543. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  544. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  545. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  546. # Geometry Editor
  547. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  548. # CNCJob General
  549. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  550. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  551. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  552. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  553. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  554. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  555. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  556. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  557. # CNC Job Options
  558. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  559. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  560. # CNC Job Advanced Options
  561. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  562. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  563. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  564. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  565. # NCC Tool
  566. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  567. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  568. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  569. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  570. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  571. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  572. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  573. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  574. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  575. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  576. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  577. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  578. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  579. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  580. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  581. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  582. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  583. # CutOut Tool
  584. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  585. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  586. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  587. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  588. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  589. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  590. # Paint Area Tool
  591. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  592. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  593. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  594. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  595. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  596. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  597. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  598. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  599. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  600. # 2-sided Tool
  601. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  602. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  603. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  604. # Film Tool
  605. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  606. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  607. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  608. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  609. # Panelize Tool
  610. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  611. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  612. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  613. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  614. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  615. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  616. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  617. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  618. # Calculators Tool
  619. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  620. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  621. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  622. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  623. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  624. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  625. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  626. # Transformations Tool
  627. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  628. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  629. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  630. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  631. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  632. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  633. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  634. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  635. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  636. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  637. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  638. # SolderPaste Dispensing Tool
  639. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  640. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  641. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  642. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  643. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  644. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  645. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  646. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  647. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  648. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  649. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  650. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  651. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  652. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  653. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  654. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  655. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  656. # Utilities
  657. # File associations
  658. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  659. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  660. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  661. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  662. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  663. }
  664. # ############################
  665. # ### LOAD POSTPROCESSORS ####
  666. # ############################
  667. self.postprocessors = load_postprocessors(self)
  668. for name in list(self.postprocessors.keys()):
  669. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  670. if name.partition('_')[0] == 'Paste':
  671. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  672. continue
  673. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  674. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  675. if name == 'hpgl':
  676. continue
  677. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  678. # ############################
  679. # ### LOAD LANGUAGES ####
  680. # ############################
  681. self.languages = fcTranslate.load_languages()
  682. for name in sorted(self.languages.values()):
  683. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  684. # #################################################################################
  685. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  686. # #################################################################################
  687. self.defaults = LoudDict()
  688. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  689. self.defaults.update({
  690. # Global APP Preferences
  691. "first_run": True,
  692. "units": "IN",
  693. "global_serial": 0,
  694. "global_stats": {},
  695. "global_tabs_detachable": True,
  696. "global_graphic_engine": '3D',
  697. "global_app_level": 'b',
  698. "global_portable": False,
  699. "global_language": 'English',
  700. "global_version_check": True,
  701. "global_send_stats": True,
  702. "global_pan_button": '2',
  703. "global_mselect_key": 'Control',
  704. "global_project_at_startup": False,
  705. "global_systray_icon": True,
  706. "global_project_autohide": True,
  707. "global_toggle_tooltips": True,
  708. "global_worker_number": 2,
  709. "global_tolerance": 0.005,
  710. "global_open_style": True,
  711. "global_delete_confirmation": True,
  712. "global_compression_level": 3,
  713. "global_save_compressed": True,
  714. # Global GUI Preferences
  715. "global_gridx": 0.0393701,
  716. "global_gridy": 0.0393701,
  717. "global_snap_max": 0.001968504,
  718. "global_workspace": False,
  719. "global_workspaceT": "A4P",
  720. "global_grid_context_menu": {
  721. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  722. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  723. },
  724. "global_plot_fill": '#BBF268BF',
  725. "global_plot_line": '#006E20BF',
  726. "global_sel_fill": '#a5a5ffbf',
  727. "global_sel_line": '#0000ffbf',
  728. "global_alt_sel_fill": '#BBF268BF',
  729. "global_alt_sel_line": '#006E20BF',
  730. "global_draw_color": '#FF0000',
  731. "global_sel_draw_color": '#0000FF',
  732. "global_proj_item_color": '#000000',
  733. "global_proj_item_dis_color": '#b7b7cb',
  734. "global_activity_icon": 'Ball green',
  735. "global_toolbar_view": 511,
  736. "global_background_timeout": 300000, # Default value is 5 minutes
  737. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  738. # (python trace only for unknown errors),
  739. # 1 = show trace(show trace always),
  740. # 2 = (For the future).
  741. # Persistence
  742. "global_last_folder": None,
  743. "global_last_save_folder": None,
  744. # Default window geometry
  745. "global_def_win_x": 100,
  746. "global_def_win_y": 100,
  747. "global_def_win_w": 1024,
  748. "global_def_win_h": 650,
  749. "global_def_notebook_width": 1,
  750. # Constants...
  751. "global_defaults_save_period_ms": 20000, # Time between default saves.
  752. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  753. "global_shell_at_startup": False, # Show the shell at startup.
  754. "global_recent_limit": 10, # Max. items in recent list.
  755. "fit_key": 'V',
  756. "zoom_out_key": '-',
  757. "zoom_in_key": '=',
  758. "grid_toggle_key": 'G',
  759. "global_zoom_ratio": 1.5,
  760. "global_point_clipboard_format": "(%.4f, %.4f)",
  761. "global_zdownrate": None,
  762. # General GUI Settings
  763. "global_hover": False,
  764. "global_selection_shape": True,
  765. "global_layout": "compact",
  766. # Gerber General
  767. "gerber_plot": True,
  768. "gerber_solid": True,
  769. "gerber_multicolored": False,
  770. "gerber_circle_steps": 128,
  771. "gerber_use_buffer_for_union": True,
  772. # Gerber Options
  773. "gerber_isotooldia": 0.00787402,
  774. "gerber_isopasses": 1,
  775. "gerber_isooverlap": 0.00393701,
  776. "gerber_milling_type": "cl",
  777. "gerber_combine_passes": False,
  778. "gerber_noncoppermargin": 0.00393701,
  779. "gerber_noncopperrounded": False,
  780. "gerber_bboxmargin": 0.00393701,
  781. "gerber_bboxrounded": False,
  782. # Gerber Advanced Options
  783. "gerber_aperture_display": False,
  784. "gerber_aperture_scale_factor": 1.0,
  785. "gerber_aperture_buffer_factor": 0.0,
  786. "gerber_follow": False,
  787. "gerber_buffering": "full",
  788. "gerber_simplification": False,
  789. "gerber_simp_tolerance": 0.0005,
  790. # Gerber Export
  791. "gerber_exp_units": 'IN',
  792. "gerber_exp_integer": 2,
  793. "gerber_exp_decimals": 4,
  794. "gerber_exp_zeros": 'L',
  795. # Gerber Editor
  796. "gerber_editor_sel_limit": 30,
  797. "gerber_editor_newcode": 10,
  798. "gerber_editor_newsize": 0.8,
  799. "gerber_editor_newtype": 'C',
  800. "gerber_editor_newdim": "0.5, 0.5",
  801. "gerber_editor_array_size": 5,
  802. "gerber_editor_lin_axis": 'X',
  803. "gerber_editor_lin_pitch": 1,
  804. "gerber_editor_lin_angle": 0.0,
  805. "gerber_editor_circ_dir": 'CW',
  806. "gerber_editor_circ_angle": 0.0,
  807. "gerber_editor_scale_f": 1.0,
  808. "gerber_editor_buff_f": 0.1,
  809. "gerber_editor_ma_low": 0.0,
  810. "gerber_editor_ma_high": 1.0,
  811. # Excellon General
  812. "excellon_plot": True,
  813. "excellon_solid": True,
  814. "excellon_format_upper_in": 2,
  815. "excellon_format_lower_in": 4,
  816. "excellon_format_upper_mm": 3,
  817. "excellon_format_lower_mm": 3,
  818. "excellon_zeros": "L",
  819. "excellon_units": "INCH",
  820. "excellon_update": True,
  821. "excellon_optimization_type": 'B',
  822. "excellon_search_time": 3,
  823. # Excellon Options
  824. "excellon_drillz": -0.0590551,
  825. "excellon_travelz": 0.0787402,
  826. "excellon_endz": 0.5,
  827. "excellon_feedrate": 3.14961,
  828. "excellon_spindlespeed": None,
  829. "excellon_dwell": False,
  830. "excellon_dwelltime": 1,
  831. "excellon_toolchange": False,
  832. "excellon_toolchangez": 0.5,
  833. "excellon_ppname_e": 'default',
  834. "excellon_tooldia": 0.0314961,
  835. "excellon_slot_tooldia": 0.0708661,
  836. "excellon_gcode_type": "drills",
  837. # Excellon Advanced Options
  838. "excellon_offset": 0.0,
  839. "excellon_toolchangexy": "0.0, 0.0",
  840. "excellon_startz": None,
  841. "excellon_feedrate_rapid": 31.4961,
  842. "excellon_z_pdepth": -0.02,
  843. "excellon_feedrate_probe": 3.14961,
  844. "excellon_spindledir": 'CW',
  845. "excellon_f_plunge": False,
  846. "excellon_f_retract": False,
  847. # Excellon Export
  848. "excellon_exp_units": 'INCH',
  849. "excellon_exp_format": 'ndec',
  850. "excellon_exp_integer": 2,
  851. "excellon_exp_decimals": 4,
  852. "excellon_exp_zeros": 'LZ',
  853. "excellon_exp_slot_type": 'routing',
  854. # Excellon Editor
  855. "excellon_editor_sel_limit": 30,
  856. "excellon_editor_newdia": 0.039,
  857. "excellon_editor_array_size": 5,
  858. "excellon_editor_lin_dir": 'X',
  859. "excellon_editor_lin_pitch": 0.1,
  860. "excellon_editor_lin_angle": 0.0,
  861. "excellon_editor_circ_dir": 'CW',
  862. "excellon_editor_circ_angle": 12,
  863. # Excellon Slots
  864. "excellon_editor_slot_direction": 'X',
  865. "excellon_editor_slot_angle": 0.0,
  866. "excellon_editor_slot_length": 5.0,
  867. # Excellon Slot Array
  868. "excellon_editor_slot_array_size": 5,
  869. "excellon_editor_slot_lin_dir": 'X',
  870. "excellon_editor_slot_lin_pitch": 0.1,
  871. "excellon_editor_slot_lin_angle": 0.0,
  872. "excellon_editor_slot_circ_dir": 'CW',
  873. "excellon_editor_slot_circ_angle": 0.0,
  874. # Geometry General
  875. "geometry_plot": True,
  876. "geometry_circle_steps": 128,
  877. "geometry_cnctooldia": "0.0944882",
  878. # Geometry Options
  879. "geometry_cutz": -0.0944882,
  880. "geometry_vtipdia": 0.1,
  881. "geometry_vtipangle": 30,
  882. "geometry_multidepth": False,
  883. "geometry_depthperpass": 0.0314961,
  884. "geometry_travelz": 0.0787402,
  885. "geometry_toolchange": False,
  886. "geometry_toolchangez": 0.5,
  887. "geometry_endz": 0.5,
  888. "geometry_feedrate": 3.14961,
  889. "geometry_feedrate_z": 3.14961,
  890. "geometry_spindlespeed": None,
  891. "geometry_dwell": False,
  892. "geometry_dwelltime": 1,
  893. "geometry_ppname_g": 'default',
  894. # Geometry Advanced Options
  895. "geometry_toolchangexy": "0.0, 0.0",
  896. "geometry_startz": None,
  897. "geometry_feedrate_rapid": 3.14961,
  898. "geometry_extracut": False,
  899. "geometry_z_pdepth": -0.02,
  900. "geometry_f_plunge": False,
  901. "geometry_spindledir": 'CW',
  902. "geometry_feedrate_probe": 3.14961,
  903. "geometry_segx": 0.0,
  904. "geometry_segy": 0.0,
  905. # Geometry Editor
  906. "geometry_editor_sel_limit": 30,
  907. # CNC Job General
  908. "cncjob_plot": True,
  909. "cncjob_plot_kind": 'all',
  910. "cncjob_annotation": True,
  911. "cncjob_tooldia": 0.0393701,
  912. "cncjob_coords_type": "G90",
  913. "cncjob_coords_decimals": 4,
  914. "cncjob_fr_decimals": 2,
  915. "cncjob_steps_per_circle": 128,
  916. # CNC Job Options
  917. "cncjob_prepend": "",
  918. "cncjob_append": "",
  919. # CNC Job Advanced Options
  920. "cncjob_toolchange_macro": "",
  921. "cncjob_toolchange_macro_enable": False,
  922. "cncjob_annotation_fontsize": 9,
  923. "cncjob_annotation_fontcolor": '#990000',
  924. # NCC Tool
  925. "tools_ncctools": "0.0393701, 0.019685",
  926. "tools_nccorder": 'rev',
  927. "tools_nccoverlap": 0.015748,
  928. "tools_nccmargin": 0.0393701,
  929. "tools_nccmethod": "seed",
  930. "tools_nccconnect": True,
  931. "tools_ncccontour": True,
  932. "tools_nccrest": False,
  933. "tools_ncc_offset_choice": False,
  934. "tools_ncc_offset_value": 0.0000,
  935. "tools_nccref": 'itself',
  936. "tools_ncc_plotting": 'normal',
  937. "tools_nccmilling_type": 'cl',
  938. "tools_ncctool_type": 'V',
  939. "tools_ncccutz": -0.001968504,
  940. "tools_ncctipdia": 0.00393701,
  941. "tools_ncctipangle": 30,
  942. # Cutout Tool
  943. "tools_cutouttooldia": 0.0944882,
  944. "tools_cutoutkind": "single",
  945. "tools_cutoutmargin": 0.00393701,
  946. "tools_cutoutgapsize": 0.15748,
  947. "tools_gaps_ff": "4",
  948. "tools_cutout_convexshape": False,
  949. # Paint Tool
  950. "tools_painttooldia": 0.023622,
  951. "tools_paintorder": 'rev',
  952. "tools_paintoverlap": 0.015748,
  953. "tools_paintmargin": 0.0,
  954. "tools_paintmethod": "seed",
  955. "tools_selectmethod": "all",
  956. "tools_pathconnect": True,
  957. "tools_paintcontour": True,
  958. "tools_paint_plotting": 'normal',
  959. # 2-Sided Tool
  960. "tools_2sided_mirror_axis": "X",
  961. "tools_2sided_axis_loc": "point",
  962. "tools_2sided_drilldia": 0.11811,
  963. # Film Tool
  964. "tools_film_type": 'neg',
  965. "tools_film_boundary": 0.0393701,
  966. "tools_film_scale": 0,
  967. "tools_film_color": '#000000',
  968. # Panel Tool
  969. "tools_panelize_spacing_columns": 0,
  970. "tools_panelize_spacing_rows": 0,
  971. "tools_panelize_columns": 1,
  972. "tools_panelize_rows": 1,
  973. "tools_panelize_constrain": False,
  974. "tools_panelize_constrainx": 0.0,
  975. "tools_panelize_constrainy": 0.0,
  976. "tools_panelize_panel_type": 'gerber',
  977. # Calculators Tool
  978. "tools_calc_vshape_tip_dia": 0.007874,
  979. "tools_calc_vshape_tip_angle": 30,
  980. "tools_calc_vshape_cut_z": 0.000787,
  981. "tools_calc_electro_length": 10.0,
  982. "tools_calc_electro_width": 10.0,
  983. "tools_calc_electro_cdensity": 13.0,
  984. "tools_calc_electro_growth": 10.0,
  985. # Transform Tool
  986. "tools_transform_rotate": 90,
  987. "tools_transform_skew_x": 0.0,
  988. "tools_transform_skew_y": 0.0,
  989. "tools_transform_scale_x": 1.0,
  990. "tools_transform_scale_y": 1.0,
  991. "tools_transform_scale_link": True,
  992. "tools_transform_scale_reference": True,
  993. "tools_transform_offset_x": 0.0,
  994. "tools_transform_offset_y": 0.0,
  995. "tools_transform_mirror_reference": False,
  996. "tools_transform_mirror_point": (0, 0),
  997. # SolderPaste Tool
  998. "tools_solderpaste_tools": "0.0393701, 0.011811",
  999. "tools_solderpaste_new": 0.011811,
  1000. "tools_solderpaste_z_start": 0.00019685039,
  1001. "tools_solderpaste_z_dispense": 0.00393701,
  1002. "tools_solderpaste_z_stop": 0.00019685039,
  1003. "tools_solderpaste_z_travel": 0.00393701,
  1004. "tools_solderpaste_z_toolchange": 0.0393701,
  1005. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1006. "tools_solderpaste_frxy": 3.0,
  1007. "tools_solderpaste_frz": 3.0,
  1008. "tools_solderpaste_frz_dispense": 0.0393701,
  1009. "tools_solderpaste_speedfwd": 20,
  1010. "tools_solderpaste_dwellfwd": 1,
  1011. "tools_solderpaste_speedrev": 10,
  1012. "tools_solderpaste_dwellrev": 1,
  1013. "tools_solderpaste_pp": 'Paste_1',
  1014. # Subtract Tool
  1015. "tools_sub_close_paths": True,
  1016. # Utilities
  1017. # file associations
  1018. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1019. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1020. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1021. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1022. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1023. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1024. # Keyword list
  1025. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1026. 'Repetier, Roland_MDX_20, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1027. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, axisoffset, box, '
  1028. 'center_x, center_y, columns, combine, connect, contour, default, '
  1029. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1030. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1031. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1032. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1033. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1034. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1035. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1036. ,
  1037. })
  1038. # ############################################################
  1039. # ############### Load defaults from file ####################
  1040. # ############################################################
  1041. if user_defaults:
  1042. self.load_defaults(filename='current_defaults')
  1043. # #############################################################
  1044. # ############## APPLY APP LANGUAGE ###########################
  1045. # #############################################################
  1046. ret_val = fcTranslate.apply_language('strings')
  1047. if ret_val == "no language":
  1048. self.inform.emit('[ERROR] %s' %
  1049. _("Could not find the Language files. The App strings are missing."))
  1050. log.debug("Could not find the Language files. The App strings are missing.")
  1051. else:
  1052. # make the current language the current selection on the language combobox
  1053. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1054. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1055. # ##############################################################
  1056. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1057. # ##############################################################
  1058. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1059. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1060. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1061. self.save_defaults(silent=True, first_time=True)
  1062. self.propagate_defaults(silent=True)
  1063. self.restore_main_win_geom()
  1064. # def auto_save_defaults():
  1065. # try:
  1066. # self.save_defaults(silent=True)
  1067. # self.propagate_defaults(silent=True)
  1068. # finally:
  1069. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1070. # the following lines activates automatic defaults save
  1071. # if user_defaults:
  1072. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1073. # self.options_form = PreferencesUI()
  1074. self.options_form_fields = {
  1075. "units": self.ui.general_options_form.general_app_group.units_radio,
  1076. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1077. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1078. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1079. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1080. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1081. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1082. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1083. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1084. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1085. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1086. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1087. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1088. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1089. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1090. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1091. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1092. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1093. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1094. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1095. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1096. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1097. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1098. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1099. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1100. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1101. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1102. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1103. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1104. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1105. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1106. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1107. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1108. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1109. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1110. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1111. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1112. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1113. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1114. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1115. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1116. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1117. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1118. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1119. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1120. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1121. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1122. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1123. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1124. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1125. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1126. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1127. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1128. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1129. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1130. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1131. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1132. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1133. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1134. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1135. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1136. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1137. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1138. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1139. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1140. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1141. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1142. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1143. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1144. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1145. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1146. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1147. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1148. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1149. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1150. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1151. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1152. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1153. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1154. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1155. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1156. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1157. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1158. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1159. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1160. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1161. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1162. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1163. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1164. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1165. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1166. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1167. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1168. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1169. }
  1170. for name in list(self.postprocessors.keys()):
  1171. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1172. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1173. self.options = LoudDict()
  1174. self.options.set_change_callback(self.on_options_dict_change)
  1175. self.options.update({
  1176. "units": "IN",
  1177. "global_gridx": 1.0,
  1178. "global_gridy": 1.0,
  1179. "global_snap_max": 0.05,
  1180. "global_background_timeout": 300000, # Default value is 5 minutes
  1181. "global_verbose_error_level": 0, # Shell verbosity:
  1182. # 0 = default(python trace only for unknown errors),
  1183. # 1 = show trace(show trace allways), 2 = (For the future).
  1184. "gerber_plot": True,
  1185. "gerber_solid": True,
  1186. "gerber_multicolored": False,
  1187. "gerber_isotooldia": 0.016,
  1188. "gerber_isopasses": 1,
  1189. "gerber_isooverlap": 0.15,
  1190. "gerber_combine_passes": True,
  1191. "gerber_noncoppermargin": 0.0,
  1192. "gerber_noncopperrounded": False,
  1193. "gerber_bboxmargin": 0.0,
  1194. "gerber_bboxrounded": False,
  1195. "excellon_plot": True,
  1196. "excellon_solid": False,
  1197. "excellon_format_upper_in": 2,
  1198. "excellon_format_lower_in": 4,
  1199. "excellon_format_upper_mm": 3,
  1200. "excellon_format_lower_mm": 3,
  1201. "excellon_units": 'INCH',
  1202. "excellon_optimization_type": 'B',
  1203. "excellon_search_time": 3,
  1204. "excellon_zeros": "L",
  1205. "excellon_drillz": -0.1,
  1206. "excellon_travelz": 0.1,
  1207. "excellon_feedrate": 3.0,
  1208. "excellon_feedrate_rapid": 3.0,
  1209. "excellon_spindlespeed": None,
  1210. "excellon_spindledir": 'CW',
  1211. "excellon_dwell": True,
  1212. "excellon_dwelltime": 1000,
  1213. "excellon_toolchange": False,
  1214. "excellon_toolchangez": 1.0,
  1215. "excellon_toolchangexy": "0.0, 0.0",
  1216. "excellon_tooldia": 0.016,
  1217. "excellon_ppname_e": 'default',
  1218. "excellon_f_plunge": False,
  1219. "excellon_startz": None,
  1220. "excellon_endz": 2.0,
  1221. "geometry_plot": True,
  1222. "geometry_segx": 0.0,
  1223. "geometry_segy": 0.0,
  1224. "geometry_cutz": -0.002,
  1225. "geometry_vtipdia": 0.1,
  1226. "geometry_vtipangle": 30,
  1227. "geometry_travelz": 0.1,
  1228. "geometry_feedrate": 3.0,
  1229. "geometry_feedrate_z": 3.0,
  1230. "geometry_feedrate_rapid": 3.0,
  1231. "geometry_spindlespeed": None,
  1232. "geometry_spindledir": 'CW',
  1233. "geometry_dwell": True,
  1234. "geometry_dwelltime": 1000,
  1235. "geometry_cnctooldia": 0.016,
  1236. "geometry_toolchange": False,
  1237. "geometry_toolchangez": 2.0,
  1238. "geometry_toolchangexy": "0.0, 0.0",
  1239. "geometry_startz": None,
  1240. "geometry_endz": 2.0,
  1241. "geometry_ppname_g": "default",
  1242. "geometry_f_plunge": False,
  1243. "geometry_depthperpass": 0.002,
  1244. "geometry_multidepth": False,
  1245. "geometry_extracut": False,
  1246. "cncjob_plot": True,
  1247. "cncjob_tooldia": 0.016,
  1248. "cncjob_prepend": "",
  1249. "cncjob_append": "",
  1250. "tools_ncctools": "1.0, 0.5",
  1251. "tools_nccoverlap": 0.4,
  1252. "tools_nccmargin": 1,
  1253. "tools_cutouttooldia": 0.07,
  1254. "tools_cutoutmargin": 0.1,
  1255. "tools_cutoutgapsize": 0.15,
  1256. "tools_gaps_ff": "8",
  1257. "tools_painttooldia": 0.07,
  1258. "tools_paintoverlap": 0.15,
  1259. "tools_paintmargin": 0.0,
  1260. "tools_paintmethod": "seed",
  1261. "tools_selectmethod": "single",
  1262. "tools_pathconnect": True,
  1263. "tools_paintcontour": True,
  1264. "tools_2sided_mirror_axis": "X",
  1265. "tools_2sided_axis_loc": 'point',
  1266. "tools_2sided_drilldia": 1,
  1267. "tools_film_type": 'neg',
  1268. "tools_film_boundary": 1,
  1269. "tools_film_scale": 0,
  1270. "tools_panelize_spacing_columns": 0,
  1271. "tools_panelize_spacing_rows": 0,
  1272. "tools_panelize_columns": 1,
  1273. "tools_panelize_rows": 1,
  1274. "tools_panelize_constrain": False,
  1275. "tools_panelize_constrainx": 0.0,
  1276. "tools_panelize_constrainy": 0.0
  1277. })
  1278. self.options.update(self.defaults) # Copy app defaults to project options
  1279. self.gen_form = None
  1280. self.ger_form = None
  1281. self.exc_form = None
  1282. self.geo_form = None
  1283. self.cnc_form = None
  1284. self.tools_form = None
  1285. self.fa_form = None
  1286. self.on_options_combo_change(0) # Will show the initial form
  1287. # ################################
  1288. # ### Initialize the color box's color in Preferences -> Global -> Color
  1289. # Init Plot Colors
  1290. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1291. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1292. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1293. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1294. int(self.defaults['global_plot_fill'][7:9], 16))
  1295. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1296. int(self.defaults['global_plot_fill'][7:9], 16))
  1297. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1298. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1299. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1300. # Init Left-Right Selection colors
  1301. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1302. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1303. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1304. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1305. int(self.defaults['global_sel_fill'][7:9], 16))
  1306. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1307. int(self.defaults['global_sel_fill'][7:9], 16))
  1308. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1309. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1310. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1311. # Init Right-Left Selection colors
  1312. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1313. self.defaults['global_alt_sel_fill'])
  1314. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1315. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1316. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1317. int(self.defaults['global_sel_fill'][7:9], 16))
  1318. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1319. int(self.defaults['global_sel_fill'][7:9], 16))
  1320. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1321. self.defaults['global_alt_sel_line'])
  1322. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1323. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1324. # Init Draw color and Selection Draw Color
  1325. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1326. self.defaults['global_draw_color'])
  1327. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1328. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1329. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1330. self.defaults['global_sel_draw_color'])
  1331. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1332. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1333. # Init Project Items color
  1334. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1335. self.defaults['global_proj_item_color'])
  1336. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1337. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1338. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1339. self.defaults['global_proj_item_dis_color'])
  1340. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1341. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1342. # Init the Annotation CNC Job color
  1343. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1344. self.defaults['cncjob_annotation_fontcolor'])
  1345. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1346. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1347. # Init the Tool Film color
  1348. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1349. self.defaults['tools_film_color'])
  1350. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1351. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1352. # ### End of Data ####
  1353. # ###############################################
  1354. # ############# SETUP Plot Area #################
  1355. # ###############################################
  1356. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1357. if self.defaults["global_graphic_engine"] == '3D':
  1358. self.is_legacy = False
  1359. else:
  1360. self.is_legacy = True
  1361. # Matplotlib axis
  1362. self.axes = None
  1363. if show_splash:
  1364. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1365. "Canvas initialization started."),
  1366. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1367. color=QtGui.QColor("gray"))
  1368. start_plot_time = time.time() # debug
  1369. self.plotcanvas = None
  1370. # this is a list just because when in legacy it is needed to add multiple cursors
  1371. # each gets deleted when the axes are deleted therefore there is a need of one for each
  1372. self.app_cursor = []
  1373. self.hover_shapes = None
  1374. self.on_plotcanvas_setup()
  1375. end_plot_time = time.time()
  1376. self.used_time = end_plot_time - start_plot_time
  1377. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1378. if show_splash:
  1379. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1380. "Canvas initialization started.\n"
  1381. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1382. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1383. color=QtGui.QColor("gray"))
  1384. self.ui.splitter.setStretchFactor(1, 2)
  1385. # #################################################################
  1386. # ####################### SYS TRAY ################################
  1387. # #################################################################
  1388. if self.defaults["global_systray_icon"]:
  1389. self.parent_w = QtWidgets.QWidget()
  1390. if self.cmd_line_headless == 1:
  1391. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1392. headless=True,
  1393. parent=self.parent_w)
  1394. else:
  1395. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1396. parent=self.parent_w)
  1397. # ##############################################
  1398. # ######### SETUP OBJECT COLLECTION ############
  1399. # ##############################################
  1400. self.collection = ObjectCollection(self)
  1401. self.ui.project_tab_layout.addWidget(self.collection.view)
  1402. # ### Adjust tabs width ## ##
  1403. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1404. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1405. self.collection.view.setMinimumWidth(290)
  1406. self.log.debug("Finished creating Object Collection.")
  1407. # ###############################################
  1408. # ############# Worker SETUP ####################
  1409. # ###############################################
  1410. if self.defaults["global_worker_number"]:
  1411. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1412. else:
  1413. self.workers = WorkerStack(workers_number=2)
  1414. self.worker_task.connect(self.workers.add_task)
  1415. self.log.debug("Finished creating Workers crew.")
  1416. # ################################################
  1417. # ############### Activity Monitor ###############
  1418. # ################################################
  1419. if self.defaults["global_activity_icon"] == "Ball green":
  1420. icon = 'share/active_2_static.png'
  1421. movie = "share/active_2.gif"
  1422. elif self.defaults["global_activity_icon"] == "Ball black":
  1423. icon = 'share/active_static.png'
  1424. movie = "share/active.gif"
  1425. elif self.defaults["global_activity_icon"] == "Arrow green":
  1426. icon = 'share/active_3_static.png'
  1427. movie = "share/active_3.gif"
  1428. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1429. icon = 'share/active_4_static.png'
  1430. movie = "share/active_4.gif"
  1431. else:
  1432. icon = 'share/active_static.png'
  1433. movie = "share/active.gif"
  1434. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1435. self.ui.infobar.addWidget(self.activity_view)
  1436. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1437. # ################################################
  1438. # ############### Signal handling ################
  1439. # ################################################
  1440. # ############# Custom signals ##################
  1441. # signal for displaying messages in status bar
  1442. self.inform.connect(self.info)
  1443. # signal to be called when the app is quiting
  1444. self.app_quit.connect(self.quit_application)
  1445. self.message.connect(self.message_dialog)
  1446. self.progress.connect(self.set_progress_bar)
  1447. # signals that are emitted when object state changes
  1448. self.object_created.connect(self.on_object_created)
  1449. self.object_changed.connect(self.on_object_changed)
  1450. self.object_plotted.connect(self.on_object_plotted)
  1451. self.plots_updated.connect(self.on_plots_updated)
  1452. # signals emitted when file state change
  1453. self.file_opened.connect(self.register_recent)
  1454. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1455. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1456. # ############# Standard signals ###################
  1457. # ### Menu
  1458. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1459. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1460. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1461. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1462. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1463. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1464. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1465. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1466. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1467. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1468. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1469. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1470. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1471. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1472. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1473. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1474. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1475. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1476. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1477. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1478. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1479. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1480. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1481. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1482. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1483. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1484. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1485. self.ui.menufile_exit.triggered.connect(self.final_save)
  1486. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1487. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1488. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1489. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1490. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1491. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1492. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1493. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1494. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1495. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1496. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1497. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1498. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1499. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1500. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1501. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1502. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1503. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1504. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1505. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1506. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1507. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1508. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1509. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1510. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1511. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1512. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1513. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1514. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1515. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1516. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1517. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1518. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1519. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1520. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1521. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1522. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1523. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1524. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1525. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1526. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1527. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1528. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1529. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1530. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1531. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1532. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1533. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1534. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1535. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1536. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1537. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1538. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1539. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1540. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1541. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1542. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1543. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1544. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1545. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1546. # ToolBar signals
  1547. self.connect_toolbar_signals()
  1548. # Notebook signals
  1549. # make the right click on the notebook tab connect to a function
  1550. self.ui.notebook.setupContextMenu()
  1551. self.ui.notebook.addContextMenu(
  1552. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1553. initial_checked=self.defaults["global_tabs_detachable"])
  1554. # activate initial state
  1555. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1556. # Context Menu
  1557. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1558. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1559. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1560. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1561. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1562. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1563. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1564. self.ui.clearplot.triggered.connect(self.clear_plots)
  1565. self.ui.replot.triggered.connect(self.plot_all)
  1566. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1567. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1568. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1569. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1570. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1571. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1572. # Preferences Plot Area TAB
  1573. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1574. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1575. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1576. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1577. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1578. # ##############################
  1579. # ### GUI PREFERENCES SIGNALS ##
  1580. # ##############################
  1581. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1582. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1583. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1584. )
  1585. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1586. lambda: self.on_toggle_units(no_pref=False))
  1587. # ###############################################################
  1588. # ################### GUI COLORS SIGNALS ########################
  1589. # ###############################################################
  1590. # Setting plot colors signals
  1591. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1592. self.on_pf_color_entry)
  1593. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1594. self.on_pf_color_button)
  1595. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1596. self.on_pf_color_spinner)
  1597. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1598. self.on_pf_color_slider)
  1599. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1600. self.on_pl_color_entry)
  1601. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1602. self.on_pl_color_button)
  1603. # Setting selection (left - right) colors signals
  1604. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1605. self.on_sf_color_entry)
  1606. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1607. self.on_sf_color_button)
  1608. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1609. self.on_sf_color_spinner)
  1610. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1611. self.on_sf_color_slider)
  1612. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1613. self.on_sl_color_entry)
  1614. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1615. self.on_sl_color_button)
  1616. # Setting selection (right - left) colors signals
  1617. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1618. self.on_alt_sf_color_entry)
  1619. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1620. self.on_alt_sf_color_button)
  1621. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1622. self.on_alt_sf_color_spinner)
  1623. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1624. self.on_alt_sf_color_slider)
  1625. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1626. self.on_alt_sl_color_entry)
  1627. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1628. self.on_alt_sl_color_button)
  1629. # Setting Editor Draw colors signals
  1630. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1631. self.on_draw_color_entry)
  1632. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1633. self.on_draw_color_button)
  1634. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1635. self.on_sel_draw_color_entry)
  1636. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1637. self.on_sel_draw_color_button)
  1638. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1639. self.on_proj_color_entry)
  1640. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1641. self.on_proj_color_button)
  1642. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1643. self.on_proj_color_dis_entry)
  1644. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1645. self.on_proj_color_dis_button)
  1646. # ########## workspace setting signals ###########
  1647. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1648. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1649. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1650. # ########## CNC Job related signals #############
  1651. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1652. self.on_cnc_custom_parameters)
  1653. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1654. self.on_annotation_fontcolor_entry)
  1655. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1656. self.on_annotation_fontcolor_button)
  1657. # ########## Tools related signals #############
  1658. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1659. self.on_film_color_entry)
  1660. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1661. self.on_film_color_button)
  1662. # ########## Modify G-CODE Plot Area TAB ###########
  1663. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1664. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1665. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1666. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1667. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1668. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1669. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1670. # portability changed signal
  1671. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1672. # Object list
  1673. self.collection.view.activated.connect(self.on_row_activated)
  1674. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1675. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1676. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1677. # Export Excellon parameters.
  1678. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1679. self.on_update_exc_export
  1680. )
  1681. # call it once to make sure it is updated at startup
  1682. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1683. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1684. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1685. self.on_excellon_defaults_button)
  1686. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1687. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1688. self.on_excellon_options_button)
  1689. # when there are arguments at application startup this get launched
  1690. self.args_at_startup[list].connect(self.on_startup_args)
  1691. # ##############################################################
  1692. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1693. # ##############################################################
  1694. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1695. lambda: self.restore_extensions(ext_type='excellon'))
  1696. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1697. lambda: self.restore_extensions(ext_type='gcode'))
  1698. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1699. lambda: self.restore_extensions(ext_type='gerber'))
  1700. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1701. lambda: self.delete_all_extensions(ext_type='excellon'))
  1702. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1703. lambda: self.delete_all_extensions(ext_type='gcode'))
  1704. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1705. lambda: self.delete_all_extensions(ext_type='gerber'))
  1706. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1707. lambda: self.add_extension(ext_type='excellon'))
  1708. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1709. lambda: self.add_extension(ext_type='gcode'))
  1710. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1711. lambda: self.add_extension(ext_type='gerber'))
  1712. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1713. lambda: self.del_extension(ext_type='excellon'))
  1714. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1715. lambda: self.del_extension(ext_type='gcode'))
  1716. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1717. lambda: self.del_extension(ext_type='gerber'))
  1718. # connect the 'Apply' buttons from the Preferences/File Associations
  1719. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1720. lambda: self.on_register_files(obj_type='excellon'))
  1721. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1722. lambda: self.on_register_files(obj_type='gcode'))
  1723. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1724. lambda: self.on_register_files(obj_type='gerber'))
  1725. # ##############################################################
  1726. # ###################### KEYWORDS SIGNALS ######################
  1727. # ##############################################################
  1728. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1729. lambda: self.restore_extensions(ext_type='keyword'))
  1730. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1731. lambda: self.delete_all_extensions(ext_type='keyword'))
  1732. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1733. lambda: self.add_extension(ext_type='keyword'))
  1734. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1735. lambda: self.del_extension(ext_type='keyword'))
  1736. # splash screen button signal
  1737. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1738. # connect the abort_all_tasks related slots to the related signals
  1739. self.proc_container.idle_flag.connect(self.app_is_idle)
  1740. # #####################################################################################
  1741. # ########### FINISHED CONNECTING SIGNALS #############################################
  1742. # #####################################################################################
  1743. self.log.debug("Finished connecting Signals.")
  1744. # #####################################################################################
  1745. # ########################## Other setups #############################################
  1746. # #####################################################################################
  1747. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1748. # depending on from where those tools are called different actions can be done
  1749. self.call_source = 'app'
  1750. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1751. self.tool_tab_locked = False
  1752. # decide if to show or hide the Notebook side of the screen at startup
  1753. if self.defaults["global_project_at_startup"] is True:
  1754. self.ui.splitter.setSizes([1, 1])
  1755. else:
  1756. self.ui.splitter.setSizes([0, 1])
  1757. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1758. self.setup_obj_classes()
  1759. self.setup_recent_items()
  1760. self.setup_component_editor()
  1761. # #####################################################################################
  1762. # ######################### Auto-complete KEYWORDS ####################################
  1763. # #####################################################################################
  1764. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1765. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1766. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1767. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1768. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1769. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1770. 'mirror', 'ncc',
  1771. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1772. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1773. 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1774. 'save', 'save_project',
  1775. 'save_sys', 'scale',
  1776. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1777. 'version', 'write_gcode'
  1778. ]
  1779. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1780. 'Repetier', 'Roland_MDX_20', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1781. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset',
  1782. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1783. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1784. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1785. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1786. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1787. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1788. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1789. 'spacing_columns',
  1790. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1791. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1792. ]
  1793. self.tcl_keywords = [
  1794. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1795. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1796. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1797. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1798. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1799. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1800. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1801. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1802. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1803. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1804. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1805. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1806. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1807. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1808. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1809. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1810. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1811. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1812. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1813. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1814. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1815. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1816. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1817. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1818. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1819. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1820. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1821. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1822. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1823. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1824. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1825. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1826. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1827. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1828. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1829. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1830. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1831. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1832. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1833. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1834. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1835. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1836. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1837. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1838. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1839. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1840. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1841. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1842. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1843. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1844. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1845. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1846. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1847. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1848. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1849. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1850. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1851. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1852. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1853. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1854. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1855. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1856. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1857. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1858. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1859. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1860. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1861. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1862. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1863. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1864. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1865. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1866. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1867. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1868. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1869. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1870. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1871. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1872. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1873. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1874. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1875. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1876. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1877. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1878. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1879. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1880. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1881. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1882. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1883. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1884. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1885. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1886. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1887. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1888. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1889. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1890. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1891. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1892. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1893. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1894. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1895. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1896. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1897. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1898. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1899. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1900. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1901. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1902. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1903. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1904. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1905. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1906. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1907. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1908. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1909. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1910. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1911. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1912. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1913. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1914. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1915. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1916. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1917. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1918. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1919. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1920. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1921. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1922. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1923. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1924. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1925. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1926. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1927. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1928. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1929. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1930. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1931. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1932. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1933. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1934. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1935. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1936. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1937. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1938. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1939. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1940. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1941. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1942. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1943. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1944. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1945. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1946. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1947. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1948. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1949. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1950. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1951. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1952. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1953. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1954. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1955. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1956. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1957. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1958. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1959. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1960. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1961. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1962. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1963. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1964. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1965. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1966. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1967. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1968. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1969. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1970. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1971. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1972. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1973. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1974. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1975. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1976. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1977. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1978. ]
  1979. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1980. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1981. # ####################################################################################
  1982. # ####################### Shell SETUP ################################################
  1983. # ####################################################################################
  1984. self.shell = FCShell(self, version=self.version)
  1985. self.shell._edit.set_model_data(self.myKeywords)
  1986. self.ui.code_editor.set_model_data(self.myKeywords)
  1987. self.shell.setWindowIcon(self.ui.app_icon)
  1988. self.shell.setWindowTitle("FlatCAM Shell")
  1989. self.shell.resize(*self.defaults["global_shell_shape"])
  1990. self.shell.append_output("FlatCAM %s - " % self.version)
  1991. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1992. self.init_tcl()
  1993. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1994. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1995. self.ui.shell_dock.setWidget(self.shell)
  1996. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1997. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1998. QtWidgets.QDockWidget.DockWidgetFloatable |
  1999. QtWidgets.QDockWidget.DockWidgetClosable)
  2000. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2001. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2002. if self.defaults["global_shell_at_startup"]:
  2003. self.ui.shell_dock.show()
  2004. else:
  2005. self.ui.shell_dock.hide()
  2006. # ##################################################################################
  2007. # ###################### Tools and Plugins #########################################
  2008. # ##################################################################################
  2009. self.dblsidedtool = None
  2010. self.measurement_tool = None
  2011. self.panelize_tool = None
  2012. self.film_tool = None
  2013. self.paste_tool = None
  2014. self.calculator_tool = None
  2015. self.sub_tool = None
  2016. self.move_tool = None
  2017. self.cutout_tool = None
  2018. self.ncclear_tool = None
  2019. self.paint_tool = None
  2020. self.transform_tool = None
  2021. self.properties_tool = None
  2022. self.pdf_tool = None
  2023. self.image_tool = None
  2024. self.pcb_wizard_tool = None
  2025. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2026. self.install_tools()
  2027. # ### System Font Parsing ###
  2028. # self.f_parse = ParseFont(self)
  2029. # self.parse_system_fonts()
  2030. # #####################################################################################
  2031. # ######################## Check for updates ##########################################
  2032. # #####################################################################################
  2033. # Separate thread (Not worker)
  2034. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2035. if (self.beta is False or self.beta is None) and \
  2036. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2037. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2038. self.thr2 = QtCore.QThread()
  2039. self.worker_task.emit({'fcn': self.version_check,
  2040. 'params': []})
  2041. self.thr2.start(QtCore.QThread.LowPriority)
  2042. # #####################################################################################
  2043. # ######################### Register files with FlatCAM; #############################
  2044. # ######################### It works only for Windows for now ########################
  2045. # #####################################################################################
  2046. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2047. self.on_register_files()
  2048. # #####################################################################################
  2049. # ###################### Variables for global usage ###################################
  2050. # #####################################################################################
  2051. # coordinates for relative position display
  2052. self.rel_point1 = (0, 0)
  2053. self.rel_point2 = (0, 0)
  2054. # variable to store coordinates
  2055. self.pos = (0, 0)
  2056. self.pos_jump = (0, 0)
  2057. # variable to store mouse coordinates
  2058. self.mouse = [0, 0]
  2059. # decide if we have a double click or single click
  2060. self.doubleclick = False
  2061. # variable to store if a command is active (then the var is not None) and which one it is
  2062. self.command_active = None
  2063. # variable to store the status of moving selection action
  2064. # None value means that it's not an selection action
  2065. # True value = a selection from left to right
  2066. # False value = a selection from right to left
  2067. self.selection_type = None
  2068. # List to store the objects that are currently loaded in FlatCAM
  2069. # This list is updated on each object creation or object delete
  2070. self.all_objects_list = list()
  2071. # List to store the objects that are selected
  2072. self.sel_objects_list = list()
  2073. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2074. self.key_modifiers = None
  2075. # Variable to hold the status of the axis
  2076. self.toggle_axis = True
  2077. # Variable to store the status of the fullscreen event
  2078. self.toggle_fscreen = False
  2079. # Variable to store the status of the code editor
  2080. self.toggle_codeeditor = False
  2081. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2082. self.click_noproject = False
  2083. self.cursor = None
  2084. # Variable to store the GCODE that was edited
  2085. self.gcode_edited = ""
  2086. # reference for the self.ui.code_editor
  2087. self.reference_code_editor = None
  2088. self.script_code = ''
  2089. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2090. self.preferences_changed_flag = False
  2091. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2092. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2093. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2094. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2095. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2096. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2097. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2098. 'tap', 'xpi']
  2099. self.svg_list = ['svg']
  2100. self.dxf_list = ['dxf']
  2101. self.pdf_list = ['pdf']
  2102. self.prj_list = ['flatprj']
  2103. self.conf_list = ['flatconfig']
  2104. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2105. # flag for polygons not cleared
  2106. self.poly_not_cleared = False
  2107. # VisPy visuals
  2108. self.isHovering = False
  2109. self.notHovering = True
  2110. # when True, the app has to return from any thread
  2111. self.abort_flag = False
  2112. # ###############################################################################
  2113. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2114. # ############# It's done only once after install ###############
  2115. # ###############################################################################
  2116. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2117. fac_def_from_file = factory_file.read()
  2118. factory_defaults = json.loads(fac_def_from_file)
  2119. # if the file contain an empty dictionary then save the factory defaults into the file
  2120. if not factory_defaults:
  2121. self.save_factory_defaults(silent=False)
  2122. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2123. initial_lay = 'compact'
  2124. self.on_layout(lay=initial_lay)
  2125. # Set the combobox in Preferences to the current layout
  2126. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2127. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2128. factory_file.close()
  2129. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2130. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2131. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2132. # after the first run, this object should be False
  2133. self.defaults["first_run"] = False
  2134. # ###############################################################################
  2135. # ################# ADDING FlatCAM EDITORS section ##############################
  2136. # ###############################################################################
  2137. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2138. # at the first launch of the App , the editors will not be functional.
  2139. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2140. self.exc_editor = FlatCAMExcEditor(self)
  2141. self.grb_editor = FlatCAMGrbEditor(self)
  2142. self.log.debug("Finished adding FlatCAM Editor's.")
  2143. self.set_ui_title(name=_("New Project - Not saved"))
  2144. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2145. current_platform = platform.architecture()[0]
  2146. if current_platform != '64bit':
  2147. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2148. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2149. # ###############################################################################
  2150. # ####################### Finished the CONSTRUCTOR ##############################
  2151. # ###############################################################################
  2152. App.log.debug("END of constructor. Releasing control.")
  2153. # #####################################################################################
  2154. # ########################## SHOW GUI #################################################
  2155. # #####################################################################################
  2156. # if the app is not started as headless, show it
  2157. if self.cmd_line_headless != 1:
  2158. # finish the splash
  2159. self.splash.finish(self.ui)
  2160. settings = QSettings("Open Source", "FlatCAM")
  2161. if settings.contains("maximized_gui"):
  2162. maximized_ui = settings.value('maximized_gui', type=bool)
  2163. if maximized_ui is True:
  2164. self.ui.showMaximized()
  2165. else:
  2166. self.ui.show()
  2167. else:
  2168. self.ui.show()
  2169. if self.defaults["global_systray_icon"]:
  2170. self.trayIcon.show()
  2171. else:
  2172. log.warning("******************* RUNNING HEADLESS *******************")
  2173. # #####################################################################################
  2174. # ########################## START-UP ARGUMENTS #######################################
  2175. # #####################################################################################
  2176. # test if the program was started with a script as parameter
  2177. if self.cmd_line_shellvar:
  2178. try:
  2179. cnt = 0
  2180. command_tcl = 0
  2181. for i in self.cmd_line_shellvar.split(','):
  2182. if i is not None:
  2183. try:
  2184. command_tcl = eval(i)
  2185. except:
  2186. command_tcl = i
  2187. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2188. cnt += 1
  2189. # if there are Windows paths then replace the path separator with a Unix like one
  2190. if sys.platform == 'win32':
  2191. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2192. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2193. except Exception as ext:
  2194. print("ERROR: ", ext)
  2195. sys.exit(2)
  2196. if self.cmd_line_shellfile:
  2197. try:
  2198. if self.ui.shell_dock.isHidden():
  2199. self.ui.shell_dock.show()
  2200. with open(self.cmd_line_shellfile, "r") as myfile:
  2201. if show_splash:
  2202. self.splash.showMessage('%s: %ssec\n%s' % (
  2203. _("Canvas initialization started.\n"
  2204. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2205. _("Executing Tcl Script ...")),
  2206. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2207. color=QtGui.QColor("gray"))
  2208. cmd_line_shellfile_text = myfile.read()
  2209. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2210. except Exception as ext:
  2211. print("ERROR: ", ext)
  2212. sys.exit(2)
  2213. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2214. # the path/file_name must be enclosed in quotes if it contain spaces
  2215. if App.args:
  2216. self.args_at_startup.emit(App.args)
  2217. @staticmethod
  2218. def copy_and_overwrite(from_path, to_path):
  2219. """
  2220. From here:
  2221. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2222. :param from_path: source path
  2223. :param to_path: destination path
  2224. :return: None
  2225. """
  2226. if os.path.exists(to_path):
  2227. shutil.rmtree(to_path)
  2228. try:
  2229. shutil.copytree(from_path, to_path)
  2230. except FileNotFoundError:
  2231. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2232. shutil.copytree(from_new_path, to_path)
  2233. def on_startup_args(self, args, silent=False):
  2234. """
  2235. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2236. :param args: a list containing the application args at startup
  2237. :return: None
  2238. """
  2239. if args is not None:
  2240. args_to_process = args
  2241. else:
  2242. args_to_process = App.args
  2243. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2244. for argument in args_to_process:
  2245. if '.FlatPrj'.lower() in argument.lower():
  2246. try:
  2247. project_name = str(argument)
  2248. if project_name == "":
  2249. if silent is False:
  2250. self.inform.emit(_("Open cancelled."))
  2251. else:
  2252. # self.open_project(project_name)
  2253. run_from_arg = True
  2254. # self.worker_task.emit({'fcn': self.open_project,
  2255. # 'params': [project_name, run_from_arg]})
  2256. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2257. except Exception as e:
  2258. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2259. elif '.FlatConfig'.lower() in argument.lower():
  2260. try:
  2261. file_name = str(argument)
  2262. if file_name == "":
  2263. if silent is False:
  2264. self.inform.emit(_("Open Config file failed."))
  2265. else:
  2266. run_from_arg = True
  2267. # self.worker_task.emit({'fcn': self.open_config_file,
  2268. # 'params': [file_name, run_from_arg]})
  2269. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2270. except Exception as e:
  2271. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2272. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2273. try:
  2274. file_name = str(argument)
  2275. if file_name == "":
  2276. if silent is False:
  2277. self.inform.emit(_("Open Script file failed."))
  2278. else:
  2279. if silent is False:
  2280. self.on_fileopenscript(name=file_name)
  2281. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2282. self.on_filerunscript(name=file_name)
  2283. except Exception as e:
  2284. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2285. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2286. log.debug("App.on_startup_args() --> Quit event.")
  2287. sys.exit()
  2288. elif 'save'.lower() in argument.lower():
  2289. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2290. self.save_defaults()
  2291. else:
  2292. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2293. proc_arg = argument.lower()
  2294. for ext in exc_list:
  2295. proc_ext = ext.replace(' ', '')
  2296. proc_ext = '.%s' % proc_ext
  2297. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2298. file_name = str(argument)
  2299. if file_name == "":
  2300. if silent is False:
  2301. self.inform.emit(_("Open Excellon file failed."))
  2302. else:
  2303. self.on_fileopenexcellon(name=file_name)
  2304. return
  2305. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2306. for ext in gco_list:
  2307. proc_ext = ext.replace(' ', '')
  2308. proc_ext = '.%s' % proc_ext
  2309. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2310. print(proc_ext, proc_arg)
  2311. file_name = str(argument)
  2312. if file_name == "":
  2313. if silent is False:
  2314. self.inform.emit(_("Open GCode file failed."))
  2315. else:
  2316. self.on_fileopengcode(name=file_name)
  2317. return
  2318. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2319. for ext in grb_list:
  2320. proc_ext = ext.replace(' ', '')
  2321. proc_ext = '.%s' % proc_ext
  2322. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2323. file_name = str(argument)
  2324. if file_name == "":
  2325. if silent is False:
  2326. self.inform.emit(_("Open Gerber file failed."))
  2327. else:
  2328. self.on_fileopengerber(name=file_name)
  2329. return
  2330. # if it reached here without already returning then the app was registered with a file that it does not
  2331. # recognize therefore we must quit
  2332. sys.exit(2)
  2333. def set_ui_title(self, name):
  2334. """
  2335. Sets the title of the main window.
  2336. :param name: String that store the project path and project name
  2337. :return: None
  2338. """
  2339. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2340. (self.version,
  2341. ('BETA' if self.beta else ''),
  2342. platform.architecture()[0],
  2343. name)
  2344. )
  2345. def defaults_read_form(self):
  2346. """
  2347. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2348. :return: None
  2349. """
  2350. for option in self.defaults_form_fields:
  2351. try:
  2352. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2353. except Exception as e:
  2354. log.debug("App.defaults_read_form() --> %s" % str(e))
  2355. def defaults_write_form(self, factor=None, fl_units=None):
  2356. """
  2357. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2358. self.defaults dictionary.
  2359. :param factor: will apply a factor to the values that written in the GUI elements
  2360. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2361. :return: None
  2362. """
  2363. for option in self.defaults:
  2364. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2365. # try:
  2366. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2367. # except KeyError:
  2368. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2369. # # TODO: Rethink this?
  2370. # pass
  2371. def defaults_write_form_field(self, field, factor=None, units=None):
  2372. """
  2373. Basically it is the worker in the self.defaults_write_form()
  2374. :param field: the GUI element in Preferences GUI to be updated
  2375. :param factor: factor to be applied to the field parameter
  2376. :param units: current FLatCAM measuring units
  2377. :return: None, it updates GUI elements
  2378. """
  2379. try:
  2380. if factor is None:
  2381. if units is None:
  2382. self.defaults_form_fields[field].set_value(self.defaults[field])
  2383. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2384. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2385. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2386. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2387. else:
  2388. if units is None:
  2389. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2390. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2391. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2392. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2393. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2394. except KeyError:
  2395. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2396. # TODO: Rethink this?
  2397. pass
  2398. except AttributeError:
  2399. log.debug(field)
  2400. def clear_pool(self):
  2401. """
  2402. Clear the multiprocessing pool and calls garbage collector.
  2403. :return: None
  2404. """
  2405. self.pool.close()
  2406. self.pool = Pool()
  2407. self.pool_recreated.emit(self.pool)
  2408. gc.collect()
  2409. def install_tools(self):
  2410. """
  2411. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2412. Instantiation of the Tools classes.
  2413. The order that the tools are installed is important as they can depend on each other install position.
  2414. :return: None
  2415. """
  2416. self.dblsidedtool = DblSidedTool(self)
  2417. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2418. self.measurement_tool = Measurement(self)
  2419. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2420. self.panelize_tool = Panelize(self)
  2421. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2422. self.film_tool = Film(self)
  2423. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2424. self.paste_tool = SolderPaste(self)
  2425. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2426. self.calculator_tool = ToolCalculator(self)
  2427. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2428. self.sub_tool = ToolSub(self)
  2429. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2430. self.move_tool = ToolMove(self)
  2431. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2432. before=self.ui.menueditorigin)
  2433. self.cutout_tool = CutOut(self)
  2434. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2435. before=self.measurement_tool.menuAction)
  2436. self.ncclear_tool = NonCopperClear(self)
  2437. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2438. before=self.measurement_tool.menuAction, separator=True)
  2439. self.paint_tool = ToolPaint(self)
  2440. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2441. before=self.measurement_tool.menuAction, separator=True)
  2442. self.transform_tool = ToolTransform(self)
  2443. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2444. self.properties_tool = Properties(self)
  2445. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2446. self.pdf_tool = ToolPDF(self)
  2447. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2448. separator=True)
  2449. self.image_tool = ToolImage(self)
  2450. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2451. separator=True)
  2452. self.pcb_wizard_tool = PcbWizard(self)
  2453. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2454. self.log.debug("Tools are installed.")
  2455. def remove_tools(self):
  2456. """
  2457. Will remove all the actions in the Tool menu.
  2458. :return: None
  2459. """
  2460. for act in self.ui.menutool.actions():
  2461. self.ui.menutool.removeAction(act)
  2462. def init_tools(self):
  2463. """
  2464. Initialize the Tool tab in the notebook side of the central widget.
  2465. Remove the actions in the Tools menu.
  2466. Instantiate again the FlatCAM tools (plugins).
  2467. All this is required when changing the layout: standard, compact etc.
  2468. :return: None
  2469. """
  2470. log.debug("init_tools()")
  2471. # delete the data currently in the Tools Tab and the Tab itself
  2472. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2473. if widget is not None:
  2474. widget.deleteLater()
  2475. self.ui.notebook.removeTab(2)
  2476. # rebuild the Tools Tab
  2477. self.ui.tool_tab = QtWidgets.QWidget()
  2478. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2479. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2480. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2481. self.ui.tool_scroll_area = VerticalScrollArea()
  2482. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2483. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2484. # first remove all of them
  2485. self.remove_tools()
  2486. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2487. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2488. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2489. # third install all of them
  2490. self.install_tools()
  2491. self.log.debug("Tools are initialized.")
  2492. # def parse_system_fonts(self):
  2493. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2494. # 'params': []})
  2495. def connect_toolbar_signals(self):
  2496. """
  2497. Reconnect the signals to the actions in the toolbar.
  2498. This has to be done each time after the FlatCAM tools are removed/installed.
  2499. :return: None
  2500. """
  2501. # Toolbar
  2502. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2503. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2504. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2505. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2506. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2507. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2508. self.ui.replot_btn.triggered.connect(self.plot_all)
  2509. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2510. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2511. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2512. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2513. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2514. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2515. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2516. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2517. self.ui.delete_btn.triggered.connect(self.on_delete)
  2518. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2519. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2520. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2521. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2522. # Tools Toolbar Signals
  2523. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2524. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2525. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2526. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2527. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2528. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2529. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2530. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2531. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2532. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2533. def object2editor(self):
  2534. """
  2535. Send the current Geometry or Excellon object (if any) into the it's editor.
  2536. :return: None
  2537. """
  2538. self.report_usage("object2editor()")
  2539. edited_object = self.collection.get_active()
  2540. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2541. isinstance(edited_object, FlatCAMExcellon):
  2542. pass
  2543. else:
  2544. self.inform.emit('[WARNING_NOTCL] %s' %
  2545. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2546. return
  2547. if isinstance(edited_object, FlatCAMGeometry):
  2548. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2549. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2550. # we set the notebook to hidden
  2551. self.ui.splitter.setSizes([0, 1])
  2552. if edited_object.multigeo is True:
  2553. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2554. if len(edited_tools) > 1:
  2555. self.inform.emit('[WARNING_NOTCL] %s' %
  2556. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2557. "is not possible.\n"
  2558. "Edit only one geometry at a time."))
  2559. # determine the tool dia of the selected tool
  2560. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2561. # now find the key in the edited_object.tools that has this tooldia
  2562. multi_tool = 1
  2563. for tool in edited_object.tools:
  2564. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2565. multi_tool = tool
  2566. break
  2567. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2568. else:
  2569. self.geo_editor.edit_fcgeometry(edited_object)
  2570. # set call source to the Editor we go into
  2571. self.call_source = 'geo_editor'
  2572. elif isinstance(edited_object, FlatCAMExcellon):
  2573. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2574. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2575. if self.ui.splitter.sizes()[0] == 0:
  2576. self.ui.splitter.setSizes([1, 1])
  2577. self.exc_editor.edit_fcexcellon(edited_object)
  2578. # set call source to the Editor we go into
  2579. self.call_source = 'exc_editor'
  2580. elif isinstance(edited_object, FlatCAMGerber):
  2581. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2582. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2583. if self.ui.splitter.sizes()[0] == 0:
  2584. self.ui.splitter.setSizes([1, 1])
  2585. self.grb_editor.edit_fcgerber(edited_object)
  2586. # set call source to the Editor we go into
  2587. self.call_source = 'grb_editor'
  2588. # make sure that we can't select another object while in Editor Mode:
  2589. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2590. self.ui.project_frame.setDisabled(True)
  2591. # delete any selection shape that might be active as they are not relevant in Editor
  2592. self.delete_selection_shape()
  2593. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2594. self.ui.plot_tab_area.protectTab(0)
  2595. self.inform.emit('[WARNING_NOTCL] %s' %
  2596. _("Editor is activated ..."))
  2597. self.should_we_save = True
  2598. def editor2object(self, cleanup=None):
  2599. """
  2600. Transfers the Geometry or Excellon from it's editor to the current object.
  2601. :return: None
  2602. """
  2603. self.report_usage("editor2object()")
  2604. # do not update a geometry or excellon object unless it comes out of an editor
  2605. if self.call_source != 'app':
  2606. edited_obj = self.collection.get_active()
  2607. if cleanup is None:
  2608. msgbox = QtWidgets.QMessageBox()
  2609. msgbox.setText(_("Do you want to save the edited object?"))
  2610. msgbox.setWindowTitle(_("Close Editor"))
  2611. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2612. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2613. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2614. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2615. msgbox.setDefaultButton(bt_yes)
  2616. msgbox.exec_()
  2617. response = msgbox.clickedButton()
  2618. if response == bt_yes:
  2619. # clean the Tools Tab
  2620. self.ui.tool_scroll_area.takeWidget()
  2621. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2622. self.ui.notebook.setTabText(2, "Tool")
  2623. if isinstance(edited_obj, FlatCAMGeometry):
  2624. obj_type = "Geometry"
  2625. if cleanup is None:
  2626. self.geo_editor.update_fcgeometry(edited_obj)
  2627. self.geo_editor.update_options(edited_obj)
  2628. self.geo_editor.deactivate()
  2629. # update the geo object options so it is including the bounding box values
  2630. try:
  2631. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2632. edited_obj.options['xmin'] = xmin
  2633. edited_obj.options['ymin'] = ymin
  2634. edited_obj.options['xmax'] = xmax
  2635. edited_obj.options['ymax'] = ymax
  2636. except AttributeError as e:
  2637. self.inform.emit('[WARNING] %s' %
  2638. _("Object empty after edit."))
  2639. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2640. elif isinstance(edited_obj, FlatCAMGerber):
  2641. obj_type = "Gerber"
  2642. if cleanup is None:
  2643. self.grb_editor.update_fcgerber()
  2644. self.grb_editor.update_options(edited_obj)
  2645. self.grb_editor.deactivate_grb_editor()
  2646. # delete the old object (the source object) if it was an empty one
  2647. if len(edited_obj.solid_geometry) == 0:
  2648. old_name = edited_obj.options['name']
  2649. self.collection.set_active(old_name)
  2650. self.collection.delete_active()
  2651. elif isinstance(edited_obj, FlatCAMExcellon):
  2652. obj_type = "Excellon"
  2653. if cleanup is None:
  2654. self.exc_editor.update_fcexcellon(edited_obj)
  2655. self.exc_editor.update_options(edited_obj)
  2656. self.exc_editor.deactivate()
  2657. else:
  2658. self.inform.emit('[WARNING_NOTCL] %s' %
  2659. _("Select a Gerber, Geometry or Excellon Object to update."))
  2660. return
  2661. self.inform.emit('[selected] %s %s' %
  2662. (obj_type, _("is updated, returning to App...")))
  2663. elif response == bt_no:
  2664. # clean the Tools Tab
  2665. self.ui.tool_scroll_area.takeWidget()
  2666. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2667. self.ui.notebook.setTabText(2, "Tool")
  2668. if isinstance(edited_obj, FlatCAMGeometry):
  2669. self.geo_editor.deactivate()
  2670. elif isinstance(edited_obj, FlatCAMGerber):
  2671. self.grb_editor.deactivate_grb_editor()
  2672. elif isinstance(edited_obj, FlatCAMExcellon):
  2673. self.exc_editor.deactivate()
  2674. # set focus on the project tab
  2675. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2676. else:
  2677. self.inform.emit('[WARNING_NOTCL] %s' %
  2678. _("Select a Gerber, Geometry or Excellon Object to update."))
  2679. return
  2680. elif response == bt_cancel:
  2681. return
  2682. else:
  2683. if isinstance(edited_obj, FlatCAMGeometry):
  2684. self.geo_editor.deactivate()
  2685. elif isinstance(edited_obj, FlatCAMGerber):
  2686. self.grb_editor.deactivate_grb_editor()
  2687. elif isinstance(edited_obj, FlatCAMExcellon):
  2688. self.exc_editor.deactivate()
  2689. else:
  2690. self.inform.emit('[WARNING_NOTCL] %s' %
  2691. _("Select a Gerber, Geometry or Excellon Object to update."))
  2692. return
  2693. # if notebook is hidden we show it
  2694. if self.ui.splitter.sizes()[0] == 0:
  2695. self.ui.splitter.setSizes([1, 1])
  2696. # restore the call_source to app
  2697. self.call_source = 'app'
  2698. edited_obj.plot()
  2699. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2700. self.ui.plot_tab_area.protectTab(0)
  2701. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2702. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2703. self.ui.project_frame.setDisabled(False)
  2704. def get_last_folder(self):
  2705. """
  2706. Get the folder path from where the last file was opened.
  2707. :return: String, last opened folder path
  2708. """
  2709. return self.defaults["global_last_folder"]
  2710. def get_last_save_folder(self):
  2711. """
  2712. Get the folder path from where the last file was saved.
  2713. :return: String, last saved folder path
  2714. """
  2715. loc = self.defaults["global_last_save_folder"]
  2716. if loc is None:
  2717. loc = self.defaults["global_last_folder"]
  2718. if loc is None:
  2719. loc = os.path.dirname(__file__)
  2720. return loc
  2721. def report_usage(self, resource):
  2722. """
  2723. Increments usage counter for the given resource
  2724. in self.defaults['global_stats'].
  2725. :param resource: Name of the resource.
  2726. :return: None
  2727. """
  2728. if resource in self.defaults['global_stats']:
  2729. self.defaults['global_stats'][resource] += 1
  2730. else:
  2731. self.defaults['global_stats'][resource] = 1
  2732. def init_tcl(self):
  2733. """
  2734. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2735. :return: None
  2736. """
  2737. if hasattr(self, 'tcl'):
  2738. # self.tcl = None
  2739. # TODO we need to clean non default variables and procedures here
  2740. # new object cannot be used here as it will not remember values created for next passes,
  2741. # because tcl was execudted in old instance of TCL
  2742. pass
  2743. else:
  2744. self.tcl = tk.Tcl()
  2745. self.setup_shell()
  2746. self.log.debug("TCL Shell has been initialized.")
  2747. # TODO: This shouldn't be here.
  2748. class TclErrorException(Exception):
  2749. """
  2750. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2751. """
  2752. pass
  2753. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2754. """
  2755. Shows a message on the FlatCAM Shell
  2756. :param msg: Message to display.
  2757. :param show: Opens the shell.
  2758. :param error: Shows the message as an error.
  2759. :param warning: Shows the message as an warning.
  2760. :param success: Shows the message as an success.
  2761. :param selected: Indicate that something was selected on canvas
  2762. :return: None
  2763. """
  2764. if show:
  2765. self.ui.shell_dock.show()
  2766. try:
  2767. if error:
  2768. self.shell.append_error(msg + "\n")
  2769. elif warning:
  2770. self.shell.append_warning(msg + "\n")
  2771. elif success:
  2772. self.shell.append_success(msg + "\n")
  2773. elif selected:
  2774. self.shell.append_selected(msg + "\n")
  2775. else:
  2776. self.shell.append_output(msg + "\n")
  2777. except AttributeError:
  2778. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2779. def raise_tcl_unknown_error(self, unknownException):
  2780. """
  2781. Raise exception if is different type than TclErrorException
  2782. this is here mainly to show unknown errors inside TCL shell console.
  2783. :param unknownException:
  2784. :return:
  2785. """
  2786. if not isinstance(unknownException, self.TclErrorException):
  2787. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2788. else:
  2789. raise unknownException
  2790. def display_tcl_error(self, error, error_info=None):
  2791. """
  2792. Escape bracket [ with '\' otherwise there is error
  2793. "ERROR: missing close-bracket" instead of real error
  2794. :param error: it may be text or exception
  2795. :param error_info: Some informations about the error
  2796. :return: None
  2797. """
  2798. if isinstance(error, Exception):
  2799. exc_type, exc_value, exc_traceback = error_info
  2800. if not isinstance(error, self.TclErrorException):
  2801. show_trace = 1
  2802. else:
  2803. show_trace = int(self.defaults['global_verbose_error_level'])
  2804. if show_trace > 0:
  2805. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2806. trc_formated = []
  2807. for a in reversed(trc):
  2808. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2809. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2810. else:
  2811. text = "%s" % error
  2812. else:
  2813. text = error
  2814. text = text.replace('[', '\\[').replace('"', '\\"')
  2815. self.tcl.eval('return -code error "%s"' % text)
  2816. def raise_tcl_error(self, text):
  2817. """
  2818. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2819. :param text: text of error
  2820. :return: raise exception
  2821. """
  2822. self.display_tcl_error(text)
  2823. raise self.TclErrorException(text)
  2824. def exec_command(self, text, no_echo=False):
  2825. """
  2826. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2827. Also handles execution in separated threads
  2828. :param text: FlatCAM TclCommand with parameters
  2829. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2830. will create crashes of the _Expandable_Edit widget
  2831. :return: output if there was any
  2832. """
  2833. self.report_usage('exec_command')
  2834. result = self.exec_command_test(text, False, no_echo=no_echo)
  2835. # MS: added this method call so the geometry is updated once the TCL command is executed
  2836. # if no_plot is None:
  2837. # self.plot_all()
  2838. return result
  2839. def exec_command_test(self, text, reraise=True, no_echo=False):
  2840. """
  2841. Same as exec_command(...) with additional control over exceptions.
  2842. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2843. :param text: Input command
  2844. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2845. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2846. will create crashes of the _Expandable_Edit widget
  2847. :return: Output from the command
  2848. """
  2849. tcl_command_string = str(text)
  2850. try:
  2851. if no_echo is False:
  2852. self.shell.open_proccessing() # Disables input box.
  2853. result = self.tcl.eval(str(tcl_command_string))
  2854. if result != 'None' and no_echo is False:
  2855. self.shell.append_output(result + '\n')
  2856. except tk.TclError as e:
  2857. # This will display more precise answer if something in TCL shell fails
  2858. result = self.tcl.eval("set errorInfo")
  2859. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2860. if no_echo is False:
  2861. self.shell.append_error('ERROR: ' + result + '\n')
  2862. # Show error in console and just return or in test raise exception
  2863. if reraise:
  2864. raise e
  2865. finally:
  2866. if no_echo is False:
  2867. self.shell.close_proccessing()
  2868. pass
  2869. return result
  2870. # """
  2871. # Code below is unsused. Saved for later.
  2872. # """
  2873. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2874. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2875. # self.log.debug(parts)
  2876. # try:
  2877. # if parts[0] not in commands:
  2878. # self.shell.append_error("Unknown command\n")
  2879. # return
  2880. #
  2881. # #import inspect
  2882. # #inspect.getargspec(someMethod)
  2883. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2884. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2885. # self.shell.append_error(
  2886. # "Command %s takes %d arguments. %d given.\n" %
  2887. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2888. # )
  2889. # return
  2890. #
  2891. # cmdfcn = commands[parts[0]]["fcn"]
  2892. # cmdconv = commands[parts[0]]["converters"]
  2893. # if len(parts) - 1 > 0:
  2894. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2895. # else:
  2896. # retval = cmdfcn()
  2897. # retfcn = commands[parts[0]]["retfcn"]
  2898. # if retval and retfcn(retval):
  2899. # self.shell.append_output(retfcn(retval) + "\n")
  2900. #
  2901. # except Exception as e:
  2902. # #self.shell.append_error(''.join(traceback.format_exc()))
  2903. # #self.shell.append_error("?\n")
  2904. # self.shell.append_error(str(e) + "\n")
  2905. def info(self, msg):
  2906. """
  2907. Informs the user. Normally on the status bar, optionally
  2908. also on the shell.
  2909. :param msg: Text to write.
  2910. :return: None
  2911. """
  2912. # Type of message in brackets at the beginning of the message.
  2913. match = re.search("\[([^\]]+)\](.*)", msg)
  2914. if match:
  2915. level = match.group(1)
  2916. msg_ = match.group(2)
  2917. self.ui.fcinfo.set_status(str(msg_), level=level)
  2918. if level.lower() == "error":
  2919. self.shell_message(msg, error=True, show=True)
  2920. elif level.lower() == "warning":
  2921. self.shell_message(msg, warning=True, show=True)
  2922. elif level.lower() == "error_notcl":
  2923. self.shell_message(msg, error=True, show=False)
  2924. elif level.lower() == "warning_notcl":
  2925. self.shell_message(msg, warning=True, show=False)
  2926. elif level.lower() == "success":
  2927. self.shell_message(msg, success=True, show=False)
  2928. elif level.lower() == "selected":
  2929. self.shell_message(msg, selected=True, show=False)
  2930. else:
  2931. self.shell_message(msg, show=False)
  2932. else:
  2933. self.ui.fcinfo.set_status(str(msg), level="info")
  2934. # make sure that if the message is to clear the infobar with a space
  2935. # is not printed over and over on the shell
  2936. if msg != '':
  2937. self.shell_message(msg)
  2938. def restore_toolbar_view(self):
  2939. """
  2940. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2941. was saved in the defaults dictionary.
  2942. :return: None
  2943. """
  2944. tb = self.defaults["global_toolbar_view"]
  2945. if tb & 1:
  2946. self.ui.toolbarfile.setVisible(True)
  2947. else:
  2948. self.ui.toolbarfile.setVisible(False)
  2949. if tb & 2:
  2950. self.ui.toolbargeo.setVisible(True)
  2951. else:
  2952. self.ui.toolbargeo.setVisible(False)
  2953. if tb & 4:
  2954. self.ui.toolbarview.setVisible(True)
  2955. else:
  2956. self.ui.toolbarview.setVisible(False)
  2957. if tb & 8:
  2958. self.ui.toolbartools.setVisible(True)
  2959. else:
  2960. self.ui.toolbartools.setVisible(False)
  2961. if tb & 16:
  2962. self.ui.exc_edit_toolbar.setVisible(True)
  2963. else:
  2964. self.ui.exc_edit_toolbar.setVisible(False)
  2965. if tb & 32:
  2966. self.ui.geo_edit_toolbar.setVisible(True)
  2967. else:
  2968. self.ui.geo_edit_toolbar.setVisible(False)
  2969. if tb & 64:
  2970. self.ui.grb_edit_toolbar.setVisible(True)
  2971. else:
  2972. self.ui.grb_edit_toolbar.setVisible(False)
  2973. if tb & 128:
  2974. self.ui.snap_toolbar.setVisible(True)
  2975. else:
  2976. self.ui.snap_toolbar.setVisible(False)
  2977. if tb & 256:
  2978. self.ui.toolbarshell.setVisible(True)
  2979. else:
  2980. self.ui.toolbarshell.setVisible(False)
  2981. def load_defaults(self, filename):
  2982. """
  2983. Loads the aplication's default settings from current_defaults.FlatConfig into
  2984. ``self.defaults``.
  2985. :return: None
  2986. """
  2987. try:
  2988. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2989. options = f.read()
  2990. f.close()
  2991. except IOError:
  2992. self.log.error("Could not load defaults file.")
  2993. self.inform.emit('[ERROR] %s' %
  2994. _("Could not load defaults file."))
  2995. # in case the defaults file can't be loaded, show all toolbars
  2996. self.defaults["global_toolbar_view"] = 511
  2997. return
  2998. try:
  2999. defaults = json.loads(options)
  3000. except:
  3001. # in case the defaults file can't be loaded, show all toolbars
  3002. self.defaults["global_toolbar_view"] = 511
  3003. e = sys.exc_info()[0]
  3004. App.log.error(str(e))
  3005. self.inform.emit('[ERROR] %s' %
  3006. _("Failed to parse defaults file."))
  3007. return
  3008. self.defaults.update(defaults)
  3009. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3010. # restore the toolbar view
  3011. self.restore_toolbar_view()
  3012. def on_import_preferences(self):
  3013. """
  3014. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3015. ``self.defaults``.
  3016. :return: None
  3017. """
  3018. self.report_usage("on_import_preferences")
  3019. App.log.debug("on_import_preferences()")
  3020. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3021. try:
  3022. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3023. directory=self.data_path,
  3024. filter=filter_)
  3025. except TypeError:
  3026. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3027. filter=filter_)
  3028. filename = str(filename)
  3029. if filename == "":
  3030. self.inform.emit('[WARNING_NOTCL] %s' %
  3031. _("FlatCAM preferences import cancelled."))
  3032. else:
  3033. try:
  3034. f = open(filename)
  3035. options = f.read()
  3036. f.close()
  3037. except IOError:
  3038. self.log.error("Could not load defaults file.")
  3039. self.inform.emit('[ERROR_NOTCL] %s' %
  3040. _("Could not load defaults file."))
  3041. return
  3042. try:
  3043. defaults_from_file = json.loads(options)
  3044. except Exception as e:
  3045. e = sys.exc_info()[0]
  3046. App.log.error(str(e))
  3047. self.inform.emit('[ERROR_NOTCL] %s' %
  3048. _("Failed to parse defaults file."))
  3049. return
  3050. self.defaults.update(defaults_from_file)
  3051. self.on_preferences_edited()
  3052. self.inform.emit('[success] %s: %s' %
  3053. (_("Imported Defaults from"), filename))
  3054. def on_export_preferences(self):
  3055. """
  3056. Save the defaults dictionary to a file.
  3057. :return: None
  3058. """
  3059. self.report_usage("on_export_preferences")
  3060. App.log.debug("on_export_preferences()")
  3061. defaults_file_content = None
  3062. self.date = str(datetime.today()).rpartition('.')[0]
  3063. self.date = ''.join(c for c in self.date if c not in ':-')
  3064. self.date = self.date.replace(' ', '_')
  3065. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3066. try:
  3067. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3068. caption=_("Export FlatCAM Preferences"),
  3069. directory=self.data_path + '/preferences_' + self.date,
  3070. filter=filter__
  3071. )
  3072. except TypeError:
  3073. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3074. filter=filter__)
  3075. filename = str(filename)
  3076. defaults_from_file = {}
  3077. if filename == "":
  3078. self.inform.emit('[WARNING_NOTCL] %s' %
  3079. _("FlatCAM preferences export cancelled."))
  3080. return
  3081. else:
  3082. try:
  3083. f = open(filename, 'w')
  3084. defaults_file_content = f.read()
  3085. f.close()
  3086. except PermissionError:
  3087. self.inform.emit('[WARNING] %s' %
  3088. _("Permission denied, saving not possible.\n"
  3089. "Most likely another app is holding the file open and not accessible."))
  3090. return
  3091. except IOError:
  3092. App.log.debug('Creating a new preferences file ...')
  3093. f = open(filename, 'w')
  3094. json.dump({}, f)
  3095. f.close()
  3096. except:
  3097. e = sys.exc_info()[0]
  3098. App.log.error("Could not load defaults file.")
  3099. App.log.error(str(e))
  3100. self.inform.emit('[ERROR_NOTCL] %s' %
  3101. _("Could not load preferences file."))
  3102. return
  3103. try:
  3104. defaults_from_file = json.loads(defaults_file_content)
  3105. except:
  3106. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3107. # Update options
  3108. self.defaults_read_form()
  3109. defaults_from_file.update(self.defaults)
  3110. self.propagate_defaults(silent=True)
  3111. # Save update options
  3112. try:
  3113. f = open(filename, "w")
  3114. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3115. f.close()
  3116. except:
  3117. self.inform.emit('[ERROR_NOTCL] %s' %
  3118. _("Failed to write defaults to file."))
  3119. return
  3120. if self.defaults["global_open_style"] is False:
  3121. self.file_opened.emit("preferences", filename)
  3122. self.file_saved.emit("preferences", filename)
  3123. self.inform.emit('[success] %s: %s' %
  3124. (_("Exported preferences to"), filename))
  3125. def on_preferences_open_folder(self):
  3126. """
  3127. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3128. :return: None
  3129. """
  3130. self.report_usage("on_preferences_open_folder()")
  3131. if sys.platform == 'win32':
  3132. subprocess.Popen('explorer %s' % self.data_path)
  3133. elif sys.platform == 'darwin':
  3134. os.system('open "%s"' % self.data_path)
  3135. else:
  3136. subprocess.Popen(['xdg-open', self.data_path])
  3137. self.inform.emit('[success] %s' %
  3138. _("FlatCAM Preferences Folder opened."))
  3139. def save_geometry(self, x, y, width, height, notebook_width):
  3140. """
  3141. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3142. launch of the application.
  3143. :param x: X position of the main window
  3144. :param y: Y position of the main window
  3145. :param width: width of the main window
  3146. :param height: height of the main window
  3147. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3148. :return: None
  3149. """
  3150. self.defaults["global_def_win_x"] = x
  3151. self.defaults["global_def_win_y"] = y
  3152. self.defaults["global_def_win_w"] = width
  3153. self.defaults["global_def_win_h"] = height
  3154. self.defaults["global_def_notebook_width"] = notebook_width
  3155. self.save_defaults()
  3156. def message_dialog(self, title, message, kind="info"):
  3157. """
  3158. Builds and show a custom QMessageBox to be used in FlatCAM.
  3159. :param title: title of the QMessageBox
  3160. :param message: message to be displayed
  3161. :param kind: type of QMessageBox; will display a specific icon.
  3162. :return:
  3163. """
  3164. icon = {"info": QtWidgets.QMessageBox.Information,
  3165. "warning": QtWidgets.QMessageBox.Warning,
  3166. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3167. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3168. dlg.setText(message)
  3169. dlg.exec_()
  3170. def register_recent(self, kind, filename):
  3171. """
  3172. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3173. dictionary.
  3174. :param kind: type of file that was opened
  3175. :param filename: the path and file name for the file that was opened
  3176. :return:
  3177. """
  3178. self.log.debug("register_recent()")
  3179. self.log.debug(" %s" % kind)
  3180. self.log.debug(" %s" % filename)
  3181. record = {'kind': str(kind), 'filename': str(filename)}
  3182. if record in self.recent:
  3183. return
  3184. if record in self.recent_projects:
  3185. return
  3186. if record['kind'] == 'project':
  3187. self.recent_projects.insert(0, record)
  3188. else:
  3189. self.recent.insert(0, record)
  3190. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3191. self.recent.pop()
  3192. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3193. self.recent_projects.pop()
  3194. try:
  3195. f = open(self.data_path + '/recent.json', 'w')
  3196. except IOError:
  3197. App.log.error("Failed to open recent items file for writing.")
  3198. self.inform.emit('[ERROR_NOTCL] %s' %
  3199. _('Failed to open recent files file for writing.'))
  3200. return
  3201. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3202. f.close()
  3203. try:
  3204. fp = open(self.data_path + '/recent_projects.json', 'w')
  3205. except IOError:
  3206. App.log.error("Failed to open recent items file for writing.")
  3207. self.inform.emit('[ERROR_NOTCL] %s' %
  3208. _('Failed to open recent projects file for writing.'))
  3209. return
  3210. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3211. fp.close()
  3212. # Re-build the recent items menu
  3213. self.setup_recent_items()
  3214. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3215. """
  3216. Creates a new specialized FlatCAMObj and attaches it to the application,
  3217. this is, updates the GUI accordingly, any other records and plots it.
  3218. This method is thread-safe.
  3219. Notes:
  3220. * If the name is in use, the self.collection will modify it
  3221. when appending it to the collection. There is no need to handle
  3222. name conflicts here.
  3223. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3224. :type kind: str
  3225. :param name: Name for the object.
  3226. :type name: str
  3227. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3228. The function is called with 2 parameters: the new object and the App instance.
  3229. :type initialize: function
  3230. :param active:
  3231. :param fit:
  3232. :param plot: If to plot the resulting object
  3233. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3234. self.colleaction
  3235. :return: None
  3236. :rtype: None
  3237. """
  3238. App.log.debug("new_object()")
  3239. obj_plot = plot
  3240. obj_autoselected = autoselected
  3241. t0 = time.time() # Debug
  3242. # ## Create object
  3243. classdict = {
  3244. "gerber": FlatCAMGerber,
  3245. "excellon": FlatCAMExcellon,
  3246. "cncjob": FlatCAMCNCjob,
  3247. "geometry": FlatCAMGeometry
  3248. }
  3249. App.log.debug("Calling object constructor...")
  3250. obj = classdict[kind](name)
  3251. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3252. # Set options from "Project options" form
  3253. self.options_read_form()
  3254. # IMPORTANT
  3255. # The key names in defaults and options dictionary's are not random:
  3256. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3257. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3258. # the options from project options form into the self.options. After that, below, depending on the type of
  3259. # object that is created, it will strip the name of the object and the underline (if the original key was
  3260. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3261. # "toolchange"
  3262. for option in self.options:
  3263. if option.find(kind + "_") == 0:
  3264. oname = option[len(kind) + 1:]
  3265. obj.options[oname] = self.options[option]
  3266. obj.isHovering = False
  3267. obj.notHovering = True
  3268. # Initialize as per user request
  3269. # User must take care to implement initialize
  3270. # in a thread-safe way as is is likely that we
  3271. # have been invoked in a separate thread.
  3272. t1 = time.time()
  3273. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3274. try:
  3275. return_value = initialize(obj, self)
  3276. except Exception as e:
  3277. msg = '[ERROR_NOTCL] %s' % \
  3278. _("An internal error has ocurred. See shell.\n")
  3279. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3280. msg += traceback.format_exc()
  3281. self.inform.emit(msg)
  3282. # if str(e) == "Empty Geometry":
  3283. # self.inform.emit("[ERROR_NOTCL] )
  3284. # else:
  3285. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3286. return "fail"
  3287. t2 = time.time()
  3288. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3289. if return_value == 'fail':
  3290. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3291. return "fail"
  3292. # Check units and convert if necessary
  3293. # This condition CAN be true because initialize() can change obj.units
  3294. if self.options["units"].upper() != obj.units.upper():
  3295. self.inform.emit('%s: %s' %
  3296. (_("Converting units to "), self.options["units"]))
  3297. obj.convert_units(self.options["units"])
  3298. t3 = time.time()
  3299. self.log.debug("%f seconds converting units." % (t3 - t2))
  3300. # Create the bounding box for the object and then add the results to the obj.options
  3301. try:
  3302. xmin, ymin, xmax, ymax = obj.bounds()
  3303. obj.options['xmin'] = xmin
  3304. obj.options['ymin'] = ymin
  3305. obj.options['xmax'] = xmax
  3306. obj.options['ymax'] = ymax
  3307. except Exception as e:
  3308. log.warning("The object has no bounds properties. %s" % str(e))
  3309. return "fail"
  3310. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3311. # Move the object to the main thread and let the app know that it is available.
  3312. obj.moveToThread(self.main_thread)
  3313. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3314. return obj
  3315. def new_excellon_object(self):
  3316. """
  3317. Creates a new, blank Excellon object.
  3318. :return: None
  3319. """
  3320. self.report_usage("new_excellon_object()")
  3321. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3322. def new_geometry_object(self):
  3323. """
  3324. Creates a new, blank and single-tool Geometry object.
  3325. :return: None
  3326. """
  3327. self.report_usage("new_geometry_object()")
  3328. def initialize(obj, self):
  3329. obj.multitool = False
  3330. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3331. def new_gerber_object(self):
  3332. """
  3333. Creates a new, blank Gerber object.
  3334. :return: None
  3335. """
  3336. self.report_usage("new_gerber_object()")
  3337. def initialize(grb_obj, self):
  3338. grb_obj.multitool = False
  3339. grb_obj.source_file = []
  3340. grb_obj.multigeo = False
  3341. grb_obj.follow = False
  3342. grb_obj.apertures = {}
  3343. grb_obj.solid_geometry = []
  3344. try:
  3345. grb_obj.options['xmin'] = 0
  3346. grb_obj.options['ymin'] = 0
  3347. grb_obj.options['xmax'] = 0
  3348. grb_obj.options['ymax'] = 0
  3349. except KeyError:
  3350. pass
  3351. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3352. def on_object_created(self, obj, plot, autoselect):
  3353. """
  3354. Event callback for object creation.
  3355. It will add the new object to the collection. After that it will plot the object in a threaded way
  3356. :param obj: The newly created FlatCAM object.
  3357. :param plot: if the newly create object t obe plotted
  3358. :param autoselect: if the newly created object to be autoselected after creation
  3359. :return: None
  3360. """
  3361. t0 = time.time() # DEBUG
  3362. self.log.debug("on_object_created()")
  3363. # The Collection might change the name if there is a collision
  3364. self.collection.append(obj)
  3365. # after adding the object to the collection always update the list of objects that are in the collection
  3366. self.all_objects_list = self.collection.get_list()
  3367. # self.inform.emit('[selected] %s created & selected: %s' %
  3368. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3369. if obj.kind == 'gerber':
  3370. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3371. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3372. elif obj.kind == 'excellon':
  3373. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3374. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3375. elif obj.kind == 'cncjob':
  3376. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3377. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3378. elif obj.kind == 'geometry':
  3379. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3380. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3381. # update the SHELL auto-completer model with the name of the new object
  3382. self.myKeywords.append(obj.options['name'])
  3383. self.shell._edit.set_model_data(self.myKeywords)
  3384. self.ui.code_editor.set_model_data(self.myKeywords)
  3385. if autoselect:
  3386. # select the just opened object but deselect the previous ones
  3387. self.collection.set_all_inactive()
  3388. self.collection.set_active(obj.options["name"])
  3389. else:
  3390. self.collection.set_all_inactive()
  3391. # here it is done the object plotting
  3392. def worker_task(t_obj):
  3393. with self.proc_container.new(_("Plotting")):
  3394. if isinstance(t_obj, FlatCAMCNCjob):
  3395. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3396. else:
  3397. t_obj.plot()
  3398. t1 = time.time() # DEBUG
  3399. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3400. self.object_plotted.emit(t_obj)
  3401. # Send to worker
  3402. # self.worker.add_task(worker_task, [self])
  3403. if plot is True:
  3404. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3405. def on_object_changed(self, obj):
  3406. """
  3407. Called whenever the geometry of the object was changed in some way.
  3408. This require the update of it's bounding values so it can be the selected on canvas.
  3409. Update the bounding box data from obj.options
  3410. :param obj: the object that was changed
  3411. :return: None
  3412. """
  3413. xmin, ymin, xmax, ymax = obj.bounds()
  3414. obj.options['xmin'] = xmin
  3415. obj.options['ymin'] = ymin
  3416. obj.options['xmax'] = xmax
  3417. obj.options['ymax'] = ymax
  3418. log.debug("Object changed, updating the bounding box data on self.options")
  3419. # delete the old selection shape
  3420. self.delete_selection_shape()
  3421. self.should_we_save = True
  3422. def on_object_plotted(self, obj):
  3423. """
  3424. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3425. :param obj: object to be fit into view
  3426. :return: None
  3427. """
  3428. self.on_zoom_fit(None)
  3429. def options_read_form(self):
  3430. """
  3431. Same as it's equivalent from the defaults.
  3432. self.options use to store the preferences per project. No longer used.
  3433. :return: None
  3434. """
  3435. for option in self.options_form_fields:
  3436. self.options[option] = self.options_form_fields[option].get_value()
  3437. def options_write_form(self):
  3438. """
  3439. Same as it's equivalent from the defaults.
  3440. self.options use to store the preferences per project. No longer used.
  3441. :return: None
  3442. """
  3443. for option in self.options:
  3444. self.options_write_form_field(option)
  3445. def options_write_form_field(self, field):
  3446. """
  3447. Same as it's equivalent from the defaults.
  3448. self.options use to store the preferences per project. No longer used.
  3449. :return: None
  3450. """
  3451. try:
  3452. self.options_form_fields[field].set_value(self.options[field])
  3453. except KeyError:
  3454. # Changed from error to debug. This allows to have data stored
  3455. # which is not user-editable.
  3456. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3457. pass
  3458. def on_about(self):
  3459. """
  3460. Displays the "about" dialog found in the Menu --> Help.
  3461. :return: None
  3462. """
  3463. self.report_usage("on_about")
  3464. version = self.version
  3465. version_date = self.version_date
  3466. beta = self.beta
  3467. class AboutDialog(QtWidgets.QDialog):
  3468. def __init__(self, parent=None):
  3469. QtWidgets.QDialog.__init__(self, parent)
  3470. # Icon and title
  3471. self.setWindowIcon(parent.app_icon)
  3472. self.setWindowTitle(_("About FlatCAM"))
  3473. self.resize(600, 200)
  3474. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3475. # self.setStyleSheet(
  3476. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3477. # "background-attachment: fixed"
  3478. # )
  3479. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3480. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3481. # palette = QtGui.QPalette()
  3482. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3483. # self.setPalette(palette)
  3484. logo = QtWidgets.QLabel()
  3485. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3486. title = QtWidgets.QLabel(
  3487. "<font size=8><B>FlatCAM</B></font><BR>"
  3488. "{title}<BR>"
  3489. "<BR>"
  3490. "<BR>"
  3491. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3492. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3493. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3494. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3495. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3496. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3497. "<B>{issue}</B></a><BR>".format(
  3498. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3499. devel=_("Development"),
  3500. down=_("DOWNLOAD"),
  3501. issue=_("Issue tracker"))
  3502. )
  3503. title.setOpenExternalLinks(True)
  3504. closebtn = QtWidgets.QPushButton(_("Close"))
  3505. tab_widget = QtWidgets.QTabWidget()
  3506. description_label = QtWidgets.QLabel(
  3507. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3508. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3509. version=version,
  3510. beta=('BETA' if beta else ''),
  3511. date=version_date,
  3512. arch=platform.architecture()[0])
  3513. )
  3514. description_label.setOpenExternalLinks(True)
  3515. license_label = QtWidgets.QLabel(
  3516. _(
  3517. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3518. 'Licensed under the MIT license:\n'
  3519. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3520. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3521. 'of this software and associated documentation files (the "Software"), to deal\n'
  3522. 'in the Software without restriction, including without limitation the rights\n'
  3523. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3524. 'copies of the Software, and to permit persons to whom the Software is\n'
  3525. ' furnished to do so, subject to the following conditions:\n\n'
  3526. 'The above copyright notice and this permission notice shall be included in\n'
  3527. 'all copies or substantial portions of the Software.\n\n'
  3528. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3529. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3530. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3531. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3532. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3533. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3534. 'THE SOFTWARE.'
  3535. )
  3536. )
  3537. license_label.setOpenExternalLinks(True)
  3538. # layouts
  3539. layout1 = QtWidgets.QVBoxLayout()
  3540. layout1_1 = QtWidgets.QHBoxLayout()
  3541. layout1_2 = QtWidgets.QHBoxLayout()
  3542. layout2 = QtWidgets.QHBoxLayout()
  3543. layout3 = QtWidgets.QHBoxLayout()
  3544. self.setLayout(layout1)
  3545. layout1.addLayout(layout1_1)
  3546. layout1.addLayout(layout1_2)
  3547. layout1.addLayout(layout2)
  3548. layout1.addLayout(layout3)
  3549. layout1_1.addStretch()
  3550. layout1_1.addWidget(description_label)
  3551. layout1_2.addWidget(tab_widget)
  3552. self.splash_tab = QtWidgets.QWidget()
  3553. self.splash_tab.setObjectName("splash_about")
  3554. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3555. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3556. tab_widget.addTab(self.splash_tab, _("Splash"))
  3557. self.programmmers_tab = QtWidgets.QWidget()
  3558. self.programmmers_tab.setObjectName("programmers_about")
  3559. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3560. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3561. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3562. self.translators_tab = QtWidgets.QWidget()
  3563. self.translators_tab.setObjectName("translators_about")
  3564. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3565. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3566. tab_widget.addTab(self.translators_tab, _("Translators"))
  3567. self.license_tab = QtWidgets.QWidget()
  3568. self.license_tab.setObjectName("license_about")
  3569. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3570. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3571. tab_widget.addTab(self.license_tab, _("License"))
  3572. self.splash_tab_layout.addWidget(logo, stretch=0)
  3573. self.splash_tab_layout.addWidget(title, stretch=1)
  3574. pal = QtGui.QPalette()
  3575. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3576. self.prog_form_lay = QtWidgets.QFormLayout()
  3577. self.prog_form_lay.setHorizontalSpacing(20)
  3578. prog_widget = QtWidgets.QWidget()
  3579. prog_widget.setLayout(self.prog_form_lay)
  3580. prog_scroll = QtWidgets.QScrollArea()
  3581. prog_scroll.setWidget(prog_widget)
  3582. prog_scroll.setWidgetResizable(True)
  3583. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3584. prog_scroll.setPalette(pal)
  3585. self.programmmers_tab_layout.addWidget(prog_scroll)
  3586. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3587. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3588. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3589. QtWidgets.QLabel('%s' % _("Program Author")))
  3590. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3591. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3592. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3593. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3594. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3595. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3596. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3597. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3598. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3599. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3600. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3601. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3602. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3603. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3604. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3605. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3606. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3607. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3608. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3609. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3610. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3611. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3612. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3613. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3614. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3615. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3616. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3617. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3618. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3619. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3620. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3621. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3622. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3623. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3624. self.translator_grid_lay = QtWidgets.QGridLayout()
  3625. # trans_widget = QtWidgets.QWidget()
  3626. # trans_widget.setLayout(self.translator_grid_lay)
  3627. # self.translators_tab_layout.addWidget(trans_widget)
  3628. # self.translators_tab_layout.addStretch()
  3629. trans_widget = QtWidgets.QWidget()
  3630. trans_widget.setLayout(self.translator_grid_lay)
  3631. trans_scroll = QtWidgets.QScrollArea()
  3632. trans_scroll.setWidget(trans_widget)
  3633. trans_scroll.setWidgetResizable(True)
  3634. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3635. trans_scroll.setPalette(pal)
  3636. self.translators_tab_layout.addWidget(trans_scroll)
  3637. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3638. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3639. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3640. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3641. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3642. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3643. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3644. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3645. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3646. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3647. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3648. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3649. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3650. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3651. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3652. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3653. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3654. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3655. self.translator_grid_lay.setColumnStretch(0, 0)
  3656. self.translators_tab_layout.addStretch()
  3657. self.license_tab_layout.addWidget(license_label)
  3658. self.license_tab_layout.addStretch()
  3659. layout3.addStretch()
  3660. layout3.addWidget(closebtn)
  3661. closebtn.clicked.connect(self.accept)
  3662. AboutDialog(self.ui).exec_()
  3663. def on_file_savedefaults(self):
  3664. """
  3665. Callback for menu item File->Save Defaults. Saves application default options
  3666. ``self.defaults`` to current_defaults.FlatConfig.
  3667. :return: None
  3668. """
  3669. self.save_defaults()
  3670. # def on_app_exit(self):
  3671. # self.report_usage("on_app_exit()")
  3672. #
  3673. # if self.collection.get_list():
  3674. # msgbox = QtWidgets.QMessageBox()
  3675. # # msgbox.setText("<B>Save changes ...</B>")
  3676. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3677. # "\n"
  3678. # "Do you want to Save the project?")
  3679. # msgbox.setWindowTitle("Save changes")
  3680. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3681. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3682. # QtWidgets.QMessageBox.Cancel)
  3683. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3684. #
  3685. # response = msgbox.exec_()
  3686. #
  3687. # if response == QtWidgets.QMessageBox.Yes:
  3688. # self.on_file_saveprojectas(thread=False)
  3689. # elif response == QtWidgets.QMessageBox.Cancel:
  3690. # return
  3691. # self.save_defaults()
  3692. # else:
  3693. # self.save_defaults()
  3694. # log.debug("Application defaults saved ... Exit event.")
  3695. # QtWidgets.qApp.quit()
  3696. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3697. """
  3698. Saves application default options
  3699. ``self.defaults`` to current_defaults.FlatConfig file.
  3700. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3701. used at the next launch of the application.
  3702. :param silent: whether to display a message in status bar or not; boolean
  3703. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3704. When the application is portable it should be a mobile location.
  3705. :return: None
  3706. """
  3707. self.report_usage("save_defaults")
  3708. if data_path is None:
  3709. data_path = self.data_path
  3710. # Read options from file
  3711. try:
  3712. f = open(data_path + "/current_defaults.FlatConfig")
  3713. defaults_file_content = f.read()
  3714. f.close()
  3715. except:
  3716. e = sys.exc_info()[0]
  3717. App.log.error("Could not load defaults file.")
  3718. App.log.error(str(e))
  3719. self.inform.emit('[ERROR_NOTCL] %s' %
  3720. _("Could not load defaults file."))
  3721. return
  3722. try:
  3723. defaults = json.loads(defaults_file_content)
  3724. except:
  3725. e = sys.exc_info()[0]
  3726. App.log.error("Failed to parse defaults file.")
  3727. App.log.error(str(e))
  3728. self.inform.emit('[ERROR_NOTCL] %s' %
  3729. _("Failed to parse defaults file."))
  3730. return
  3731. # Update options
  3732. self.defaults_read_form()
  3733. defaults.update(self.defaults)
  3734. self.propagate_defaults(silent=True)
  3735. # Save the toolbar view
  3736. tb_status = 0
  3737. if self.ui.toolbarfile.isVisible():
  3738. tb_status += 1
  3739. if self.ui.toolbargeo.isVisible():
  3740. tb_status += 2
  3741. if self.ui.toolbarview.isVisible():
  3742. tb_status += 4
  3743. if self.ui.toolbartools.isVisible():
  3744. tb_status += 8
  3745. if self.ui.exc_edit_toolbar.isVisible():
  3746. tb_status += 16
  3747. if self.ui.geo_edit_toolbar.isVisible():
  3748. tb_status += 32
  3749. if self.ui.grb_edit_toolbar.isVisible():
  3750. tb_status += 64
  3751. if self.ui.snap_toolbar.isVisible():
  3752. tb_status += 128
  3753. if self.ui.toolbarshell.isVisible():
  3754. tb_status += 256
  3755. if first_time is False:
  3756. self.defaults["global_toolbar_view"] = tb_status
  3757. # Save update options
  3758. try:
  3759. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3760. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3761. f.close()
  3762. except:
  3763. self.inform.emit('[ERROR_NOTCL] %s' %
  3764. _("Failed to write defaults to file."))
  3765. return
  3766. if not silent:
  3767. self.inform.emit('[success] %s' %
  3768. _("Preferences saved."))
  3769. def save_factory_defaults(self, silent=False, data_path=None):
  3770. """
  3771. Saves application factory default options
  3772. ``self.defaults`` to factory_defaults.FlatConfig.
  3773. It's a one time job done just after the first install.
  3774. :param silent: whether to display a message in status bar or not; boolean
  3775. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3776. When the application is portable it should be a mobile location.
  3777. :return: None
  3778. """
  3779. self.report_usage("save_factory_defaults")
  3780. if data_path is None:
  3781. data_path = self.data_path
  3782. # Read options from file
  3783. try:
  3784. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3785. factory_defaults_file_content = f_f_def.read()
  3786. f_f_def.close()
  3787. except:
  3788. e = sys.exc_info()[0]
  3789. App.log.error("Could not load factory defaults file.")
  3790. App.log.error(str(e))
  3791. self.inform.emit('[ERROR_NOTCL] %s' %
  3792. _("Could not load factory defaults file."))
  3793. return
  3794. try:
  3795. factory_defaults = json.loads(factory_defaults_file_content)
  3796. except:
  3797. e = sys.exc_info()[0]
  3798. App.log.error("Failed to parse factory defaults file.")
  3799. App.log.error(str(e))
  3800. self.inform.emit('[ERROR_NOTCL] %s' %
  3801. _("Failed to parse factory defaults file."))
  3802. return
  3803. # Update options
  3804. self.defaults_read_form()
  3805. factory_defaults.update(self.defaults)
  3806. self.propagate_defaults(silent=True)
  3807. # Save update options
  3808. try:
  3809. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3810. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3811. f_f_def_s.close()
  3812. except:
  3813. self.inform.emit('[ERROR_NOTCL] %s' %
  3814. _("Failed to write factory defaults to file."))
  3815. return
  3816. if silent is False:
  3817. self.inform.emit(_("Factory defaults saved."))
  3818. def final_save(self):
  3819. """
  3820. Callback for doing a preferences save to file whenever the application is about to quit.
  3821. If the project has changes, it will ask the user to save the project.
  3822. :return: None
  3823. """
  3824. if self.save_in_progress:
  3825. self.inform.emit('[WARNING_NOTCL] %s' %
  3826. _("Application is saving the project. Please wait ..."))
  3827. return
  3828. if self.should_we_save and self.collection.get_list():
  3829. msgbox = QtWidgets.QMessageBox()
  3830. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3831. "\n"
  3832. "Do you want to Save the project?"))
  3833. msgbox.setWindowTitle(_("Save changes"))
  3834. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3835. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3836. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3837. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3838. msgbox.setDefaultButton(bt_yes)
  3839. msgbox.exec_()
  3840. response = msgbox.clickedButton()
  3841. if response == bt_yes:
  3842. try:
  3843. self.trayIcon.hide()
  3844. except:
  3845. pass
  3846. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3847. elif response == bt_no:
  3848. try:
  3849. self.trayIcon.hide()
  3850. except:
  3851. pass
  3852. self.quit_application()
  3853. elif response == bt_cancel:
  3854. return
  3855. else:
  3856. try:
  3857. self.trayIcon.hide()
  3858. except:
  3859. pass
  3860. self.quit_application()
  3861. def quit_application(self):
  3862. """
  3863. Called (as a pyslot or not) when the application is quit.
  3864. :return: None
  3865. """
  3866. self.save_defaults()
  3867. log.debug("App.final_save() --> App Defaults saved.")
  3868. if self.cmd_line_headless != 1:
  3869. # save app state to file
  3870. settings = QSettings("Open Source", "FlatCAM")
  3871. settings.setValue('saved_gui_state', self.ui.saveState())
  3872. settings.setValue('maximized_gui', self.ui.isMaximized())
  3873. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3874. settings.setValue(
  3875. 'notebook_font_size',
  3876. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3877. )
  3878. settings.setValue('axis_font_size',
  3879. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3880. settings.setValue(
  3881. 'textbox_font_size',
  3882. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  3883. )
  3884. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3885. # This will write the setting to the platform specific storage.
  3886. del settings
  3887. log.debug("App.final_save() --> App UI state saved.")
  3888. QtWidgets.qApp.quit()
  3889. def on_portable_checked(self, state):
  3890. """
  3891. Callback called when the checkbox in Preferences GUI is checked.
  3892. It will set the application as portable by creating the preferences and recent files in the
  3893. 'config' folder found in the FlatCAM installation folder.
  3894. :param state: boolean, the state of the checkbox when clicked/checked
  3895. :return:
  3896. """
  3897. line_no = 0
  3898. data = None
  3899. if sys.platform != 'win32':
  3900. # this won't work in Linux or MacOS
  3901. return
  3902. # test if the app was frozen and choose the path for the configuration file
  3903. if getattr(sys, "frozen", False) is True:
  3904. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3905. else:
  3906. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3907. config_file = current_data_path + '\\configuration.txt'
  3908. try:
  3909. with open(config_file, 'r') as f:
  3910. try:
  3911. data = f.readlines()
  3912. except Exception as e:
  3913. log.debug('App.__init__() -->%s' % str(e))
  3914. return
  3915. except FileNotFoundError:
  3916. pass
  3917. for line in data:
  3918. line = line.strip('\n')
  3919. param = str(line).rpartition('=')
  3920. if param[0] == 'portable':
  3921. break
  3922. line_no += 1
  3923. if state:
  3924. data[line_no] = 'portable=True\n'
  3925. # create the new defauults files
  3926. # create current_defaults.FlatConfig file if there is none
  3927. try:
  3928. f = open(current_data_path + '/current_defaults.FlatConfig')
  3929. f.close()
  3930. except IOError:
  3931. App.log.debug('Creating empty current_defaults.FlatConfig')
  3932. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3933. json.dump({}, f)
  3934. f.close()
  3935. # create factory_defaults.FlatConfig file if there is none
  3936. try:
  3937. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3938. f.close()
  3939. except IOError:
  3940. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3941. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3942. json.dump({}, f)
  3943. f.close()
  3944. try:
  3945. f = open(current_data_path + '/recent.json')
  3946. f.close()
  3947. except IOError:
  3948. App.log.debug('Creating empty recent.json')
  3949. f = open(current_data_path + '/recent.json', 'w')
  3950. json.dump([], f)
  3951. f.close()
  3952. try:
  3953. fp = open(current_data_path + '/recent_projects.json')
  3954. fp.close()
  3955. except IOError:
  3956. App.log.debug('Creating empty recent_projects.json')
  3957. fp = open(current_data_path + '/recent_projects.json', 'w')
  3958. json.dump([], fp)
  3959. fp.close()
  3960. # save the current defaults to the new defaults file
  3961. self.save_defaults(silent=True, data_path=current_data_path)
  3962. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3963. else:
  3964. data[line_no] = 'portable=False\n'
  3965. with open(config_file, 'w') as f:
  3966. f.writelines(data)
  3967. def on_toggle_shell(self):
  3968. """
  3969. Toggle shell: if is visible close it, if it is closed then open it
  3970. :return:
  3971. """
  3972. self.report_usage("on_toggle_shell()")
  3973. if self.ui.shell_dock.isVisible():
  3974. self.ui.shell_dock.hide()
  3975. else:
  3976. self.ui.shell_dock.show()
  3977. def on_register_files(self, obj_type=None):
  3978. """
  3979. Called whenever there is a need to register file extensions with FlatCAM.
  3980. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3981. :param obj_type: the type of object to be register for.
  3982. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3983. :return: None
  3984. """
  3985. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3986. new_reg_path = 'Software\\Classes\\'
  3987. # find if the current user is admin
  3988. try:
  3989. is_admin = os.getuid() == 0
  3990. except AttributeError:
  3991. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3992. if is_admin is True:
  3993. root_path = winreg.HKEY_LOCAL_MACHINE
  3994. else:
  3995. root_path = winreg.HKEY_CURRENT_USER
  3996. # create the keys
  3997. def set_reg(name, root_path, new_reg_path, value):
  3998. try:
  3999. winreg.CreateKey(root_path, new_reg_path)
  4000. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4001. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4002. return True
  4003. except WindowsError:
  4004. return False
  4005. # delete key in registry
  4006. def delete_reg(root_path, reg_path, key_to_del):
  4007. key_to_del_path = reg_path + key_to_del
  4008. try:
  4009. winreg.DeleteKey(root_path, key_to_del_path)
  4010. return True
  4011. except WindowsError:
  4012. return False
  4013. if obj_type is None or obj_type == 'excellon':
  4014. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4015. exc_list = [x for x in exc_list if x != '']
  4016. # register all keys in the Preferences window
  4017. for ext in exc_list:
  4018. new_k = new_reg_path + '.%s' % ext
  4019. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4020. # and unregister those that are no longer in the Preferences windows but are in the file
  4021. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4022. if ext not in exc_list:
  4023. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4024. # now write the updated extensions to the self.defaults
  4025. # new_ext = ''
  4026. # for ext in exc_list:
  4027. # new_ext = new_ext + ext + ', '
  4028. # self.defaults["fa_excellon"] = new_ext
  4029. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4030. if obj_type is None or obj_type == 'gcode':
  4031. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4032. gco_list = [x for x in gco_list if x != '']
  4033. # register all keys in the Preferences window
  4034. for ext in gco_list:
  4035. new_k = new_reg_path + '.%s' % ext
  4036. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4037. # and unregister those that are no longer in the Preferences windows but are in the file
  4038. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4039. if ext not in gco_list:
  4040. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4041. # now write the updated extensions to the self.defaults
  4042. # new_ext = ''
  4043. # for ext in gco_list:
  4044. # new_ext = new_ext + ext + ', '
  4045. # self.defaults["fa_gcode"] = new_ext
  4046. self.inform.emit('[success] %s' %
  4047. _("Selected GCode file extensions registered with FlatCAM."))
  4048. if obj_type is None or obj_type == 'gerber':
  4049. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4050. grb_list = [x for x in grb_list if x != '']
  4051. # register all keys in the Preferences window
  4052. for ext in grb_list:
  4053. new_k = new_reg_path + '.%s' % ext
  4054. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4055. # and unregister those that are no longer in the Preferences windows but are in the file
  4056. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4057. if ext not in grb_list:
  4058. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4059. # now write the updated extensions to the self.defaults
  4060. # new_ext = ''
  4061. # for ext in grb_list:
  4062. # new_ext = new_ext + ext + ', '
  4063. # self.defaults["fa_gerber"] = new_ext
  4064. self.inform.emit('[success] %s' %
  4065. _("Selected Gerber file extensions registered with FlatCAM."))
  4066. def add_extension(self, ext_type):
  4067. if ext_type == 'excellon':
  4068. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4069. if new_ext == '':
  4070. return
  4071. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4072. if new_ext in old_val:
  4073. return
  4074. old_val.append(new_ext)
  4075. old_val.sort()
  4076. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4077. if ext_type == 'gcode':
  4078. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4079. if new_ext == '':
  4080. return
  4081. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4082. if new_ext in old_val:
  4083. return
  4084. old_val.append(new_ext)
  4085. old_val.sort()
  4086. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4087. if ext_type == 'gerber':
  4088. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4089. if new_ext == '':
  4090. return
  4091. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4092. if new_ext in old_val:
  4093. return
  4094. old_val.append(new_ext)
  4095. old_val.sort()
  4096. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4097. if ext_type == 'keyword':
  4098. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4099. if new_kw == '':
  4100. return
  4101. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4102. if new_kw in old_val:
  4103. return
  4104. old_val.append(new_kw)
  4105. old_val.sort()
  4106. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4107. # update the self.myKeywords so the model is updated
  4108. self.autocomplete_kw_list = \
  4109. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4110. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4111. self.shell._edit.set_model_data(self.myKeywords)
  4112. self.ui.code_editor.set_model_data(self.myKeywords)
  4113. def del_extension(self, ext_type):
  4114. if ext_type == 'excellon':
  4115. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4116. if new_ext == '':
  4117. return
  4118. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4119. if new_ext not in old_val:
  4120. return
  4121. old_val.remove(new_ext)
  4122. old_val.sort()
  4123. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4124. if ext_type == 'gcode':
  4125. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4126. if new_ext == '':
  4127. return
  4128. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4129. if new_ext not in old_val:
  4130. return
  4131. old_val.remove(new_ext)
  4132. old_val.sort()
  4133. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4134. if ext_type == 'gerber':
  4135. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4136. if new_ext == '':
  4137. return
  4138. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4139. if new_ext not in old_val:
  4140. return
  4141. old_val.remove(new_ext)
  4142. old_val.sort()
  4143. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4144. if ext_type == 'keyword':
  4145. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4146. if new_kw == '':
  4147. return
  4148. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4149. if new_kw not in old_val:
  4150. return
  4151. old_val.remove(new_kw)
  4152. old_val.sort()
  4153. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4154. # update the self.myKeywords so the model is updated
  4155. self.autocomplete_kw_list = \
  4156. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4157. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4158. self.shell._edit.set_model_data(self.myKeywords)
  4159. self.ui.code_editor.set_model_data(self.myKeywords)
  4160. def restore_extensions(self, ext_type):
  4161. if ext_type == 'excellon':
  4162. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4163. # for the ability to open Excellon files with .txt extension
  4164. new_exc_list = deepcopy(self.exc_list)
  4165. try:
  4166. new_exc_list.remove('txt')
  4167. except ValueError:
  4168. pass
  4169. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4170. if ext_type == 'gcode':
  4171. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4172. if ext_type == 'gerber':
  4173. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4174. if ext_type == 'keyword':
  4175. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4176. # update the self.myKeywords so the model is updated
  4177. self.autocomplete_kw_list = self.default_keywords
  4178. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4179. self.shell._edit.set_model_data(self.myKeywords)
  4180. self.ui.code_editor.set_model_data(self.myKeywords)
  4181. def delete_all_extensions(self, ext_type):
  4182. if ext_type == 'excellon':
  4183. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4184. if ext_type == 'gcode':
  4185. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4186. if ext_type == 'gerber':
  4187. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4188. if ext_type == 'keyword':
  4189. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4190. # update the self.myKeywords so the model is updated
  4191. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4192. self.shell._edit.set_model_data(self.myKeywords)
  4193. self.ui.code_editor.set_model_data(self.myKeywords)
  4194. def on_edit_join(self, name=None):
  4195. """
  4196. Callback for Edit->Join. Joins the selected geometry objects into
  4197. a new one.
  4198. :return: None
  4199. """
  4200. self.report_usage("on_edit_join()")
  4201. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4202. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4203. tooldias = []
  4204. geo_type_list = set()
  4205. objs = self.collection.get_selected()
  4206. if len(objs) < 2:
  4207. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4208. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4209. return 'fail'
  4210. for obj in objs:
  4211. geo_type_list.add(obj.multigeo)
  4212. # if len(geo_type_list) == 1 means that all list elements are the same
  4213. if len(geo_type_list) != 1:
  4214. self.inform.emit('[ERROR] %s' %
  4215. _("Failed join. The Geometry objects are of different types.\n"
  4216. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4217. "convert from one to another and retry joining \n"
  4218. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4219. "the result may not be what was expected. \n"
  4220. "Check the generated GCODE."))
  4221. return
  4222. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4223. if True in geo_type_list:
  4224. def initialize(obj, app):
  4225. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4226. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4227. for v in obj.tools.values():
  4228. v['data']['name'] = obj_name_multi
  4229. self.new_object("geometry", obj_name_multi, initialize)
  4230. else:
  4231. def initialize(obj, app):
  4232. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4233. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4234. for v in obj.tools.values():
  4235. v['data']['name'] = obj_name_single
  4236. self.new_object("geometry", obj_name_single, initialize)
  4237. self.should_we_save = True
  4238. def on_edit_join_exc(self):
  4239. """
  4240. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4241. a new Excellon.
  4242. :return: None
  4243. """
  4244. self.report_usage("on_edit_join_exc()")
  4245. objs = self.collection.get_selected()
  4246. for obj in objs:
  4247. if not isinstance(obj, FlatCAMExcellon):
  4248. self.inform.emit('[ERROR_NOTCL] %s' %
  4249. _("Failed. Excellon joining works only on Excellon objects."))
  4250. return
  4251. if len(objs) < 2:
  4252. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4253. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4254. return 'fail'
  4255. def initialize(obj, app):
  4256. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4257. self.new_object("excellon", 'Combo_Excellon', initialize)
  4258. self.should_we_save = True
  4259. def on_edit_join_grb(self):
  4260. """
  4261. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4262. a new Gerber object.
  4263. :return: None
  4264. """
  4265. self.report_usage("on_edit_join_grb()")
  4266. objs = self.collection.get_selected()
  4267. for obj in objs:
  4268. if not isinstance(obj, FlatCAMGerber):
  4269. self.inform.emit('[ERROR_NOTCL] %s' %
  4270. _("Failed. Gerber joining works only on Gerber objects."))
  4271. return
  4272. if len(objs) < 2:
  4273. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4274. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4275. return 'fail'
  4276. def initialize(obj, app):
  4277. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4278. self.new_object("gerber", 'Combo_Gerber', initialize)
  4279. self.should_we_save = True
  4280. def on_convert_singlegeo_to_multigeo(self):
  4281. """
  4282. Called for converting a Geometry object from single-geo to multi-geo.
  4283. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4284. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4285. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4286. the solid-geometry of that tool.
  4287. :return: None
  4288. """
  4289. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4290. obj = self.collection.get_active()
  4291. if obj is None:
  4292. self.inform.emit('[ERROR_NOTCL] %s' %
  4293. _("Failed. Select a Geometry Object and try again."))
  4294. return
  4295. if not isinstance(obj, FlatCAMGeometry):
  4296. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4297. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4298. return
  4299. obj.multigeo = True
  4300. for tooluid, dict_value in obj.tools.items():
  4301. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4302. if not isinstance(obj.solid_geometry, list):
  4303. obj.solid_geometry = [obj.solid_geometry]
  4304. obj.solid_geometry[:] = []
  4305. obj.plot()
  4306. self.should_we_save = True
  4307. self.inform.emit('[success] %s' %
  4308. _("A Geometry object was converted to MultiGeo type."))
  4309. def on_convert_multigeo_to_singlegeo(self):
  4310. """
  4311. Called for converting a Geometry object from multi-geo to single-geo.
  4312. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4313. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4314. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4315. the solid-geometry of that tool.
  4316. :return: None
  4317. """
  4318. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4319. obj = self.collection.get_active()
  4320. if obj is None:
  4321. self.inform.emit('[ERROR_NOTCL] %s' %
  4322. _("Failed. Select a Geometry Object and try again."))
  4323. return
  4324. if not isinstance(obj, FlatCAMGeometry):
  4325. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4326. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4327. return
  4328. obj.multigeo = False
  4329. total_solid_geometry = []
  4330. for tooluid, dict_value in obj.tools.items():
  4331. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4332. # clear the original geometry
  4333. dict_value['solid_geometry'][:] = []
  4334. obj.solid_geometry = deepcopy(total_solid_geometry)
  4335. obj.plot()
  4336. self.should_we_save = True
  4337. self.inform.emit('[success] %s' %
  4338. _("A Geometry object was converted to SingleGeo type."))
  4339. def on_options_dict_change(self, field):
  4340. """
  4341. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4342. current project. This feature is no longer used.
  4343. :param field:
  4344. :return:
  4345. """
  4346. self.options_write_form_field(field)
  4347. if field == "units":
  4348. self.set_screen_units(self.options['units'])
  4349. def on_defaults_dict_change(self, field):
  4350. """
  4351. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4352. Edit -> Preferences tab window.
  4353. :param field: the key of the self.defaults dictionary that was changed.
  4354. :return: None
  4355. """
  4356. self.defaults_write_form_field(field)
  4357. if field == "units":
  4358. self.set_screen_units(self.defaults['units'])
  4359. def set_screen_units(self, units):
  4360. """
  4361. Set the FlatCAM units on the status bar.
  4362. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4363. :return: None
  4364. """
  4365. self.ui.units_label.setText("[" + units.lower() + "]")
  4366. def on_toggle_units(self, no_pref=False):
  4367. """
  4368. Callback for the Units radio-button change in the Preferences tab.
  4369. Changes the application's default units adn for the project too.
  4370. If changing the project's units, the change propagates to all of
  4371. the objects in the project.
  4372. :return: None
  4373. """
  4374. self.report_usage("on_toggle_units")
  4375. if self.toggle_units_ignore:
  4376. return
  4377. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4378. # If option is the same, then ignore
  4379. if new_units == self.defaults["units"].upper():
  4380. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4381. return
  4382. # Options to scale
  4383. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4384. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4385. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4386. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4387. "excellon_z_pdepth",
  4388. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4389. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4390. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4391. "geometry_feedrate_probe",
  4392. 'cncjob_tooldia',
  4393. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4394. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4395. "tools_2sided_drilldia", "tools_film_boundary",
  4396. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4397. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4398. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4399. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4400. "tools_transform_offset_y",
  4401. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4402. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4403. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4404. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4405. 'global_gridx', 'global_gridy', 'global_snap_max']
  4406. def scale_options(sfactor):
  4407. for dim in dimensions:
  4408. if dim == 'excellon_toolchangexy':
  4409. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4410. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4411. coords_xy[0] *= sfactor
  4412. coords_xy[1] *= sfactor
  4413. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4414. elif dim == 'geometry_toolchangexy':
  4415. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4416. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4417. coords_xy[0] *= sfactor
  4418. coords_xy[1] *= sfactor
  4419. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4420. elif dim == 'geometry_cnctooldia':
  4421. tools_diameters = []
  4422. try:
  4423. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4424. tools_diameters = [eval(a) for a in tools_string if a != '']
  4425. except Exception as e:
  4426. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4427. self.options['geometry_cnctooldia'] = ''
  4428. for t in range(len(tools_diameters)):
  4429. tools_diameters[t] *= sfactor
  4430. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4431. elif dim == 'tools_ncctools':
  4432. ncctools = []
  4433. try:
  4434. tools_string = self.defaults["tools_ncctools"].split(",")
  4435. ncctools = [eval(a) for a in tools_string if a != '']
  4436. except Exception as e:
  4437. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4438. self.options['tools_ncctools'] = ''
  4439. for t in range(len(ncctools)):
  4440. ncctools[t] *= sfactor
  4441. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4442. elif dim == 'tools_solderpaste_tools':
  4443. sptools = []
  4444. try:
  4445. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4446. sptools = [eval(a) for a in tools_string if a != '']
  4447. except Exception as e:
  4448. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4449. self.options['tools_solderpaste_tools'] = ""
  4450. for t in range(len(sptools)):
  4451. sptools[t] *= sfactor
  4452. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4453. elif dim == 'tools_solderpaste_xy_toolchange':
  4454. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4455. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4456. sp_coords[0] *= sfactor
  4457. sp_coords[1] *= sfactor
  4458. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4459. elif dim == 'global_gridx' or dim == 'global_gridy':
  4460. if new_units == 'IN':
  4461. val = 0.1
  4462. try:
  4463. val = float(self.defaults[dim]) * sfactor
  4464. except Exception as e:
  4465. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4466. self.options[dim] = float('%.6f' % val)
  4467. else:
  4468. val = 0.1
  4469. try:
  4470. val = float(self.defaults[dim]) * sfactor
  4471. except Exception as e:
  4472. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4473. self.options[dim] = float('%.4f' % val)
  4474. else:
  4475. val = 0.1
  4476. try:
  4477. val = float(self.options[dim]) * sfactor
  4478. except Exception as e:
  4479. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4480. self.options[dim] = val
  4481. def scale_defaults(sfactor):
  4482. for dim in dimensions:
  4483. if dim == 'excellon_toolchangexy':
  4484. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4485. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4486. coords_xy[0] *= sfactor
  4487. coords_xy[1] *= sfactor
  4488. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4489. elif dim == 'geometry_toolchangexy':
  4490. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4491. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4492. coords_xy[0] *= sfactor
  4493. coords_xy[1] *= sfactor
  4494. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4495. elif dim == 'geometry_cnctooldia':
  4496. tools_diameters = []
  4497. try:
  4498. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4499. tools_diameters = [eval(a) for a in tools_string if a != '']
  4500. except Exception as e:
  4501. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4502. self.defaults['geometry_cnctooldia'] = ''
  4503. for t in range(len(tools_diameters)):
  4504. tools_diameters[t] *= sfactor
  4505. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4506. elif dim == 'tools_ncctools':
  4507. ncctools = []
  4508. try:
  4509. tools_string = self.defaults["tools_ncctools"].split(",")
  4510. ncctools = [eval(a) for a in tools_string if a != '']
  4511. except Exception as e:
  4512. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4513. self.defaults['tools_ncctools'] = ''
  4514. for t in range(len(ncctools)):
  4515. ncctools[t] *= sfactor
  4516. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4517. elif dim == 'tools_solderpaste_tools':
  4518. sptools = []
  4519. try:
  4520. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4521. sptools = [eval(a) for a in tools_string if a != '']
  4522. except Exception as e:
  4523. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4524. self.defaults['tools_solderpaste_tools'] = ""
  4525. for t in range(len(sptools)):
  4526. sptools[t] *= sfactor
  4527. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4528. elif dim == 'tools_solderpaste_xy_toolchange':
  4529. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4530. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4531. sp_coords[0] *= sfactor
  4532. sp_coords[1] *= sfactor
  4533. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4534. elif dim == 'global_gridx' or dim == 'global_gridy':
  4535. if new_units == 'IN':
  4536. val = 0.1
  4537. try:
  4538. val = float(self.defaults[dim]) * sfactor
  4539. except Exception as e:
  4540. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4541. self.defaults[dim] = float('%.6f' % val)
  4542. else:
  4543. val = 0.1
  4544. try:
  4545. val = float(self.defaults[dim]) * sfactor
  4546. except Exception as e:
  4547. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4548. self.defaults[dim] = float('%.4f' % val)
  4549. else:
  4550. val = 0.1
  4551. try:
  4552. val = float(self.defaults[dim]) * sfactor
  4553. except Exception as e:
  4554. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4555. self.defaults[dim] = val
  4556. # The scaling factor depending on choice of units.
  4557. factor = 1/25.4
  4558. if new_units == 'MM':
  4559. factor = 25.4
  4560. # Changing project units. Warn user.
  4561. msgbox = QtWidgets.QMessageBox()
  4562. msgbox.setWindowTitle(_("Toggle Units"))
  4563. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4564. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4565. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4566. "properties of all objects to be scaled accordingly.\nContinue?"))
  4567. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4568. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4569. msgbox.setDefaultButton(bt_ok)
  4570. msgbox.exec_()
  4571. response = msgbox.clickedButton()
  4572. if response == bt_ok:
  4573. if no_pref is False:
  4574. self.options_read_form()
  4575. scale_options(factor)
  4576. self.options_write_form()
  4577. self.defaults_read_form()
  4578. scale_defaults(factor)
  4579. self.defaults_write_form(fl_units=new_units)
  4580. # save the defaults to file, some may assume that the conversion is enough and it's not
  4581. self.on_save_button()
  4582. self.should_we_save = True
  4583. # change this only if the workspace is active
  4584. if self.defaults['global_workspace'] is True:
  4585. self.plotcanvas.draw_workspace()
  4586. # adjust the grid values on the main toolbar
  4587. dec = 6 if new_units == 'IN'else 4
  4588. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4589. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4590. if not self.ui.grid_gap_link_cb.isChecked():
  4591. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4592. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4593. for obj in self.collection.get_list():
  4594. obj.convert_units(new_units)
  4595. # make that the properties stored in the object are also updated
  4596. self.object_changed.emit(obj)
  4597. obj.build_ui()
  4598. current = self.collection.get_active()
  4599. if current is not None:
  4600. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4601. if not isinstance(current, FlatCAMGeometry):
  4602. current.to_form()
  4603. self.plot_all()
  4604. self.inform.emit('[success] %s: %s' %
  4605. (_("Converted units to"), new_units))
  4606. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4607. self.set_screen_units(new_units)
  4608. else:
  4609. # Undo toggling
  4610. self.toggle_units_ignore = True
  4611. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4612. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4613. else:
  4614. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4615. self.toggle_units_ignore = False
  4616. self.inform.emit('[WARNING_NOTCL]%s' %
  4617. _(" Units conversion cancelled."))
  4618. self.options_read_form()
  4619. self.defaults_read_form()
  4620. def on_toggle_units_click(self):
  4621. try:
  4622. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4623. except (TypeError, AttributeError):
  4624. pass
  4625. if self.defaults["units"] == 'MM':
  4626. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4627. else:
  4628. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4629. self.on_toggle_units(no_pref=True)
  4630. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4631. lambda: self.on_toggle_units(no_pref=False))
  4632. def on_fullscreen(self):
  4633. self.report_usage("on_fullscreen()")
  4634. if self.toggle_fscreen is False:
  4635. if sys.platform == 'win32':
  4636. self.ui.showFullScreen()
  4637. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4638. tb.setVisible(False)
  4639. self.ui.splitter_left.setVisible(False)
  4640. self.toggle_fscreen = True
  4641. else:
  4642. if sys.platform == 'win32':
  4643. self.ui.showNormal()
  4644. self.restore_toolbar_view()
  4645. self.ui.splitter_left.setVisible(True)
  4646. self.toggle_fscreen = False
  4647. def on_toggle_plotarea(self):
  4648. self.report_usage("on_toggle_plotarea()")
  4649. try:
  4650. name = self.ui.plot_tab_area.widget(0).objectName()
  4651. except AttributeError:
  4652. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4653. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4654. self.ui.plot_tab_area.protectTab(0)
  4655. return
  4656. if name != 'plotarea':
  4657. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4658. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4659. self.ui.plot_tab_area.protectTab(0)
  4660. else:
  4661. self.ui.plot_tab_area.closeTab(0)
  4662. def on_toggle_notebook(self):
  4663. if self.ui.splitter.sizes()[0] == 0:
  4664. self.ui.splitter.setSizes([1, 1])
  4665. else:
  4666. self.ui.splitter.setSizes([0, 1])
  4667. def on_toggle_axis(self):
  4668. self.report_usage("on_toggle_axis()")
  4669. if self.toggle_axis is False:
  4670. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4671. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4672. self.plotcanvas.redraw()
  4673. self.toggle_axis = True
  4674. else:
  4675. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4676. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4677. self.plotcanvas.redraw()
  4678. self.toggle_axis = False
  4679. def on_toggle_grid(self):
  4680. self.report_usage("on_toggle_grid()")
  4681. self.ui.grid_snap_btn.trigger()
  4682. def on_options_combo_change(self, sel):
  4683. """
  4684. Called when the combo box to choose between application defaults and
  4685. project option changes value. The corresponding variables are
  4686. copied to the UI.
  4687. :param sel: The option index that was chosen.
  4688. :return: None
  4689. """
  4690. # combo_sel = self.ui.notebook.combo_options.get_active()
  4691. App.log.debug("Options --> %s" % sel)
  4692. # form = [self.defaults_form, self.options_form][sel]
  4693. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4694. if sel == 0:
  4695. self.gen_form = self.ui.general_defaults_form
  4696. self.ger_form = self.ui.gerber_defaults_form
  4697. self.exc_form = self.ui.excellon_defaults_form
  4698. self.geo_form = self.ui.geometry_defaults_form
  4699. self.cnc_form = self.ui.cncjob_defaults_form
  4700. self.tools_form = self.ui.tools_defaults_form
  4701. self.fa_form = self.ui.util_defaults_form
  4702. elif sel == 1:
  4703. self.gen_form = self.ui.general_options_form
  4704. self.ger_form = self.ui.gerber_options_form
  4705. self.exc_form = self.ui.excellon_options_form
  4706. self.geo_form = self.ui.geometry_options_form
  4707. self.cnc_form = self.ui.cncjob_options_form
  4708. self.tools_form = self.ui.tools_options_form
  4709. self.fa_form = self.ui.util_options_form
  4710. else:
  4711. return
  4712. try:
  4713. self.ui.general_scroll_area.takeWidget()
  4714. except:
  4715. self.log.debug("Nothing to remove")
  4716. self.ui.general_scroll_area.setWidget(self.gen_form)
  4717. self.gen_form.show()
  4718. try:
  4719. self.ui.gerber_scroll_area.takeWidget()
  4720. except:
  4721. self.log.debug("Nothing to remove")
  4722. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4723. self.ger_form.show()
  4724. try:
  4725. self.ui.excellon_scroll_area.takeWidget()
  4726. except:
  4727. self.log.debug("Nothing to remove")
  4728. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4729. self.exc_form.show()
  4730. try:
  4731. self.ui.geometry_scroll_area.takeWidget()
  4732. except:
  4733. self.log.debug("Nothing to remove")
  4734. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4735. self.geo_form.show()
  4736. try:
  4737. self.ui.cncjob_scroll_area.takeWidget()
  4738. except:
  4739. self.log.debug("Nothing to remove")
  4740. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4741. self.cnc_form.show()
  4742. try:
  4743. self.ui.tools_scroll_area.takeWidget()
  4744. except:
  4745. self.log.debug("Nothing to remove")
  4746. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4747. self.tools_form.show()
  4748. try:
  4749. self.ui.fa_scroll_area.takeWidget()
  4750. except:
  4751. self.log.debug("Nothing to remove")
  4752. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4753. self.fa_form.show()
  4754. self.log.debug("Finished GUI form initialization.")
  4755. # self.options2form()
  4756. def on_excellon_defaults_button(self):
  4757. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4758. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4759. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4760. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4761. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4762. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4763. log.debug("Excellon app defaults loaded ...")
  4764. def on_excellon_options_button(self):
  4765. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4766. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4767. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4768. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4769. self.options_form_fields["excellon_zeros"].set_value('L')
  4770. self.options_form_fields["excellon_units"].set_value('INCH')
  4771. log.debug("Excellon options defaults loaded ...")
  4772. def on_update_exc_export(self, state):
  4773. """
  4774. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4775. if the update_excellon_cb checkbox is checked
  4776. :param state: state of the checkbox whose signals is tied to his slot
  4777. :return:
  4778. """
  4779. if state:
  4780. # first try to disconnect
  4781. try:
  4782. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4783. disconnect(self.on_excellon_format_changed)
  4784. except TypeError:
  4785. pass
  4786. try:
  4787. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4788. disconnect(self.on_excellon_format_changed)
  4789. except TypeError:
  4790. pass
  4791. try:
  4792. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4793. disconnect(self.on_excellon_format_changed)
  4794. except TypeError:
  4795. pass
  4796. try:
  4797. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4798. disconnect(self.on_excellon_format_changed)
  4799. except TypeError:
  4800. pass
  4801. try:
  4802. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4803. disconnect(self.on_excellon_zeros_changed)
  4804. except TypeError:
  4805. pass
  4806. try:
  4807. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4808. disconnect(self.on_excellon_zeros_changed)
  4809. except TypeError:
  4810. pass
  4811. # the connect them
  4812. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4813. self.on_excellon_format_changed)
  4814. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4815. self.on_excellon_format_changed)
  4816. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4817. self.on_excellon_format_changed)
  4818. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4819. self.on_excellon_format_changed)
  4820. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4821. self.on_excellon_zeros_changed)
  4822. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4823. self.on_excellon_units_changed)
  4824. else:
  4825. # disconnect the signals
  4826. try:
  4827. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_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_format_lower_in_entry.textChanged. \
  4833. disconnect(self.on_excellon_format_changed)
  4834. except TypeError:
  4835. pass
  4836. try:
  4837. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4838. disconnect(self.on_excellon_format_changed)
  4839. except TypeError:
  4840. pass
  4841. try:
  4842. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4843. disconnect(self.on_excellon_format_changed)
  4844. except TypeError:
  4845. pass
  4846. try:
  4847. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4848. disconnect(self.on_excellon_zeros_changed)
  4849. except TypeError:
  4850. pass
  4851. try:
  4852. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4853. disconnect(self.on_excellon_zeros_changed)
  4854. except TypeError:
  4855. pass
  4856. def on_excellon_format_changed(self):
  4857. """
  4858. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4859. :return: None
  4860. """
  4861. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4862. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4863. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4864. )
  4865. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4866. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4867. )
  4868. else:
  4869. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4870. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4871. )
  4872. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4873. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4874. )
  4875. def on_excellon_zeros_changed(self):
  4876. """
  4877. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4878. :return: None
  4879. """
  4880. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4881. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4882. )
  4883. def on_excellon_units_changed(self):
  4884. """
  4885. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4886. :return: None
  4887. """
  4888. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4889. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4890. )
  4891. self.on_excellon_format_changed()
  4892. # Setting plot colors handlers
  4893. def on_pf_color_entry(self):
  4894. self.defaults['global_plot_fill'] = \
  4895. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4896. self.defaults['global_plot_fill'][7:9]
  4897. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4898. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4899. def on_pf_color_button(self):
  4900. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4901. c_dialog = QtWidgets.QColorDialog()
  4902. plot_fill_color = c_dialog.getColor(initial=current_color)
  4903. if plot_fill_color.isValid() is False:
  4904. return
  4905. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4906. "background-color:%s" % str(plot_fill_color.name()))
  4907. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4908. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4909. self.defaults['global_plot_fill'] = new_val
  4910. def on_pf_color_spinner(self):
  4911. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4912. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4913. self.defaults['global_plot_fill'] = \
  4914. self.defaults['global_plot_fill'][:7] + \
  4915. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4916. self.defaults['global_plot_line'] = \
  4917. self.defaults['global_plot_line'][:7] + \
  4918. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4919. def on_pf_color_slider(self):
  4920. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4921. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4922. def on_pl_color_entry(self):
  4923. self.defaults['global_plot_line'] = \
  4924. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4925. self.defaults['global_plot_line'][7:9]
  4926. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4927. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4928. def on_pl_color_button(self):
  4929. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4930. # print(current_color)
  4931. c_dialog = QtWidgets.QColorDialog()
  4932. plot_line_color = c_dialog.getColor(initial=current_color)
  4933. if plot_line_color.isValid() is False:
  4934. return
  4935. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4936. "background-color:%s" % str(plot_line_color.name()))
  4937. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4938. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4939. self.defaults['global_plot_line'] = new_val_line
  4940. # Setting selection colors (left - right) handlers
  4941. def on_sf_color_entry(self):
  4942. self.defaults['global_sel_fill'] = \
  4943. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4944. self.defaults['global_sel_fill'][7:9]
  4945. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4946. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4947. def on_sf_color_button(self):
  4948. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4949. c_dialog = QtWidgets.QColorDialog()
  4950. plot_fill_color = c_dialog.getColor(initial=current_color)
  4951. if plot_fill_color.isValid() is False:
  4952. return
  4953. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4954. "background-color:%s" % str(plot_fill_color.name()))
  4955. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4956. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4957. self.defaults['global_sel_fill'] = new_val
  4958. def on_sf_color_spinner(self):
  4959. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4960. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4961. self.defaults['global_sel_fill'] = \
  4962. self.defaults['global_sel_fill'][:7] + \
  4963. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4964. self.defaults['global_sel_line'] = \
  4965. self.defaults['global_sel_line'][:7] + \
  4966. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4967. def on_sf_color_slider(self):
  4968. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4969. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4970. def on_sl_color_entry(self):
  4971. self.defaults['global_sel_line'] = \
  4972. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4973. self.defaults['global_sel_line'][7:9]
  4974. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4975. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4976. def on_sl_color_button(self):
  4977. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4978. c_dialog = QtWidgets.QColorDialog()
  4979. plot_line_color = c_dialog.getColor(initial=current_color)
  4980. if plot_line_color.isValid() is False:
  4981. return
  4982. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4983. "background-color:%s" % str(plot_line_color.name()))
  4984. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4985. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4986. self.defaults['global_sel_line'] = new_val_line
  4987. # Setting selection colors (right - left) handlers
  4988. def on_alt_sf_color_entry(self):
  4989. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4990. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4991. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4992. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4993. def on_alt_sf_color_button(self):
  4994. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4995. c_dialog = QtWidgets.QColorDialog()
  4996. plot_fill_color = c_dialog.getColor(initial=current_color)
  4997. if plot_fill_color.isValid() is False:
  4998. return
  4999. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5000. "background-color:%s" % str(plot_fill_color.name()))
  5001. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5002. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5003. self.defaults['global_alt_sel_fill'] = new_val
  5004. def on_alt_sf_color_spinner(self):
  5005. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5006. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5007. self.defaults['global_alt_sel_fill'] = \
  5008. self.defaults['global_alt_sel_fill'][:7] + \
  5009. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5010. self.defaults['global_alt_sel_line'] = \
  5011. self.defaults['global_alt_sel_line'][:7] + \
  5012. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5013. def on_alt_sf_color_slider(self):
  5014. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5015. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5016. def on_alt_sl_color_entry(self):
  5017. self.defaults['global_alt_sel_line'] = \
  5018. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5019. self.defaults['global_alt_sel_line'][7:9]
  5020. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5021. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5022. def on_alt_sl_color_button(self):
  5023. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5024. c_dialog = QtWidgets.QColorDialog()
  5025. plot_line_color = c_dialog.getColor(initial=current_color)
  5026. if plot_line_color.isValid() is False:
  5027. return
  5028. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5029. "background-color:%s" % str(plot_line_color.name()))
  5030. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5031. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5032. self.defaults['global_alt_sel_line'] = new_val_line
  5033. # Setting Editor colors
  5034. def on_draw_color_entry(self):
  5035. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5036. .draw_color_entry.get_value()
  5037. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5038. "background-color:%s" % str(self.defaults['global_draw_color']))
  5039. def on_draw_color_button(self):
  5040. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5041. c_dialog = QtWidgets.QColorDialog()
  5042. draw_color = c_dialog.getColor(initial=current_color)
  5043. if draw_color.isValid() is False:
  5044. return
  5045. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5046. "background-color:%s" % str(draw_color.name()))
  5047. new_val = str(draw_color.name())
  5048. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5049. self.defaults['global_draw_color'] = new_val
  5050. def on_sel_draw_color_entry(self):
  5051. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5052. .sel_draw_color_entry.get_value()
  5053. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5054. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5055. def on_sel_draw_color_button(self):
  5056. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5057. c_dialog = QtWidgets.QColorDialog()
  5058. sel_draw_color = c_dialog.getColor(initial=current_color)
  5059. if sel_draw_color.isValid() is False:
  5060. return
  5061. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5062. "background-color:%s" % str(sel_draw_color.name()))
  5063. new_val_sel = str(sel_draw_color.name())
  5064. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5065. self.defaults['global_sel_draw_color'] = new_val_sel
  5066. def on_proj_color_entry(self):
  5067. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5068. .proj_color_entry.get_value()
  5069. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5070. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5071. def on_proj_color_button(self):
  5072. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5073. c_dialog = QtWidgets.QColorDialog()
  5074. proj_color = c_dialog.getColor(initial=current_color)
  5075. if proj_color.isValid() is False:
  5076. return
  5077. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5078. "background-color:%s" % str(proj_color.name()))
  5079. new_val_sel = str(proj_color.name())
  5080. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5081. self.defaults['global_proj_item_color'] = new_val_sel
  5082. def on_proj_color_dis_entry(self):
  5083. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5084. .proj_color_dis_entry.get_value()
  5085. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5086. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5087. def on_proj_color_dis_button(self):
  5088. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5089. c_dialog = QtWidgets.QColorDialog()
  5090. proj_color = c_dialog.getColor(initial=current_color)
  5091. if proj_color.isValid() is False:
  5092. return
  5093. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5094. "background-color:%s" % str(proj_color.name()))
  5095. new_val_sel = str(proj_color.name())
  5096. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5097. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5098. def on_annotation_fontcolor_entry(self):
  5099. self.defaults['cncjob_annotation_fontcolor'] = \
  5100. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5101. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5102. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5103. def on_annotation_fontcolor_button(self):
  5104. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5105. c_dialog = QtWidgets.QColorDialog()
  5106. annotation_color = c_dialog.getColor(initial=current_color)
  5107. if annotation_color.isValid() is False:
  5108. return
  5109. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5110. "background-color:%s" % str(annotation_color.name()))
  5111. new_val_sel = str(annotation_color.name())
  5112. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5113. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5114. def on_film_color_entry(self):
  5115. self.defaults['tools_film_color'] = \
  5116. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5117. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5118. "background-color:%s" % str(self.defaults['tools_film_color']))
  5119. def on_film_color_button(self):
  5120. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5121. c_dialog = QtWidgets.QColorDialog()
  5122. film_color = c_dialog.getColor(initial=current_color)
  5123. if film_color.isValid() is False:
  5124. return
  5125. # if new color is different then mark that the Preferences are changed
  5126. if film_color != current_color:
  5127. self.on_preferences_edited()
  5128. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5129. "background-color:%s" % str(film_color.name()))
  5130. new_val_sel = str(film_color.name())
  5131. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5132. self.defaults['tools_film_color'] = new_val_sel
  5133. def on_splash_changed(self, state):
  5134. settings = QSettings("Open Source", "FlatCAM")
  5135. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5136. # This will write the setting to the platform specific storage.
  5137. del settings
  5138. def on_notebook_tab_rmb_click(self, checked):
  5139. self.ui.notebook.set_detachable(val=checked)
  5140. self.defaults["global_tabs_detachable"] = checked
  5141. self.ui.plot_tab_area.set_detachable(val=checked)
  5142. self.defaults["global_tabs_detachable"] = checked
  5143. def on_deselect_all(self):
  5144. self.collection.set_all_inactive()
  5145. self.delete_selection_shape()
  5146. def on_workspace_modified(self):
  5147. self.save_defaults(silent=True)
  5148. self.plotcanvas.draw_workspace()
  5149. def on_workspace(self):
  5150. self.report_usage("on_workspace()")
  5151. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5152. self.plotcanvas.restore_workspace()
  5153. else:
  5154. self.plotcanvas.delete_workspace()
  5155. self.save_defaults(silent=True)
  5156. def on_workspace_menu(self):
  5157. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5158. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5159. else:
  5160. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5161. self.on_workspace()
  5162. def on_layout(self, index=None, lay=None):
  5163. self.report_usage("on_layout()")
  5164. if lay:
  5165. current_layout = lay
  5166. else:
  5167. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5168. settings = QSettings("Open Source", "FlatCAM")
  5169. settings.setValue('layout', current_layout)
  5170. # This will write the setting to the platform specific storage.
  5171. del settings
  5172. # first remove the toolbars:
  5173. try:
  5174. self.ui.removeToolBar(self.ui.toolbarfile)
  5175. self.ui.removeToolBar(self.ui.toolbargeo)
  5176. self.ui.removeToolBar(self.ui.toolbarview)
  5177. self.ui.removeToolBar(self.ui.toolbarshell)
  5178. self.ui.removeToolBar(self.ui.toolbartools)
  5179. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5180. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5181. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5182. self.ui.removeToolBar(self.ui.snap_toolbar)
  5183. self.ui.removeToolBar(self.ui.toolbarshell)
  5184. except Exception as e:
  5185. pass
  5186. if current_layout == 'standard':
  5187. # ## TOOLBAR INSTALLATION # ##
  5188. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5189. self.ui.toolbarfile.setObjectName('File_TB')
  5190. self.ui.addToolBar(self.ui.toolbarfile)
  5191. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5192. self.ui.toolbargeo.setObjectName('Edit_TB')
  5193. self.ui.addToolBar(self.ui.toolbargeo)
  5194. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5195. self.ui.toolbarview.setObjectName('View_TB')
  5196. self.ui.addToolBar(self.ui.toolbarview)
  5197. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5198. self.ui.toolbarshell.setObjectName('Shell_TB')
  5199. self.ui.addToolBar(self.ui.toolbarshell)
  5200. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5201. self.ui.toolbartools.setObjectName('Tools_TB')
  5202. self.ui.addToolBar(self.ui.toolbartools)
  5203. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5204. # self.ui.exc_edit_toolbar.setVisible(False)
  5205. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5206. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5207. self.ui.addToolBarBreak()
  5208. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5209. # self.ui.geo_edit_toolbar.setVisible(False)
  5210. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5211. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5212. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5213. # self.ui.grb_edit_toolbar.setVisible(False)
  5214. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5215. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5216. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5217. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5218. # self.ui.snap_toolbar.setMaximumHeight(30)
  5219. self.ui.addToolBar(self.ui.snap_toolbar)
  5220. self.ui.corner_snap_btn.setVisible(False)
  5221. self.ui.snap_magnet.setVisible(False)
  5222. elif current_layout == 'compact':
  5223. # ## TOOLBAR INSTALLATION # ##
  5224. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5225. self.ui.toolbarfile.setObjectName('File_TB')
  5226. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5227. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5228. self.ui.toolbargeo.setObjectName('Edit_TB')
  5229. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5230. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5231. self.ui.toolbarshell.setObjectName('Shell_TB')
  5232. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5233. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5234. self.ui.toolbartools.setObjectName('Tools_TB')
  5235. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5236. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5237. # self.ui.geo_edit_toolbar.setVisible(False)
  5238. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5239. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5240. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5241. self.ui.toolbarview.setObjectName('View_TB')
  5242. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5243. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5244. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5245. # self.ui.grb_edit_toolbar.setVisible(False)
  5246. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5247. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5248. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5249. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5250. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5251. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5252. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5253. self.ui.snap_toolbar.setMaximumHeight(30)
  5254. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5255. self.ui.corner_snap_btn.setVisible(True)
  5256. self.ui.snap_magnet.setVisible(True)
  5257. # add all the actions to the toolbars
  5258. self.ui.populate_toolbars()
  5259. # reconnect all the signals to the toolbar actions
  5260. self.connect_toolbar_signals()
  5261. self.ui.grid_snap_btn.setChecked(True)
  5262. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5263. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5264. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5265. self.ui.grid_gap_link_cb.setChecked(True)
  5266. def on_cnc_custom_parameters(self, signal_text):
  5267. if signal_text == 'Parameters':
  5268. return
  5269. else:
  5270. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5271. def on_save_button(self):
  5272. log.debug("App.on_save_button() --> Saving preferences to file.")
  5273. self.preferences_changed_flag = False
  5274. self.save_defaults(silent=False)
  5275. # load the defaults so they are updated into the app
  5276. self.load_defaults(filename='current_defaults')
  5277. # Re-fresh project options
  5278. self.on_options_app2project()
  5279. settings = QSettings("Open Source", "FlatCAM")
  5280. # save the notebook font size
  5281. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5282. settings.setValue('notebook_font_size', fsize)
  5283. # save the axis font size
  5284. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5285. settings.setValue('axis_font_size', g_fsize)
  5286. # save the textbox font size
  5287. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5288. settings.setValue('textbox_font_size', tb_fsize)
  5289. # This will write the setting to the platform specific storage.
  5290. del settings
  5291. def handlePrint(self):
  5292. self.report_usage("handlePrint()")
  5293. dialog = QtPrintSupport.QPrintDialog()
  5294. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5295. self.ui.code_editor.document().print_(dialog.printer())
  5296. def handlePreview(self):
  5297. self.report_usage("handlePreview()")
  5298. dialog = QtPrintSupport.QPrintPreviewDialog()
  5299. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5300. dialog.exec_()
  5301. def handleTextChanged(self):
  5302. # enable = not self.ui.code_editor.document().isEmpty()
  5303. # self.ui.buttonPrint.setEnabled(enable)
  5304. # self.ui.buttonPreview.setEnabled(enable)
  5305. pass
  5306. def handleOpen(self, filt=None):
  5307. self.report_usage("handleOpen()")
  5308. if filt:
  5309. _filter_ = filt
  5310. else:
  5311. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5312. "All Files (*.*)"
  5313. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5314. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5315. if path:
  5316. file = QtCore.QFile(path)
  5317. if file.open(QtCore.QIODevice.ReadOnly):
  5318. stream = QtCore.QTextStream(file)
  5319. self.gcode_edited = stream.readAll()
  5320. self.ui.code_editor.setPlainText(self.gcode_edited)
  5321. file.close()
  5322. def handleSaveGCode(self, name=None, filt=None):
  5323. self.report_usage("handleSaveGCode()")
  5324. if filt:
  5325. _filter_ = filt
  5326. else:
  5327. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5328. "All Files (*.*)"
  5329. if name:
  5330. obj_name = name
  5331. else:
  5332. try:
  5333. obj_name = self.collection.get_active().options['name']
  5334. except AttributeError:
  5335. obj_name = 'file'
  5336. if filt is None:
  5337. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5338. try:
  5339. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5340. caption=_("Export G-Code ..."),
  5341. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5342. filter=_filter_
  5343. )[0])
  5344. except TypeError:
  5345. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5346. if filename == "":
  5347. self.inform.emit('[WARNING_NOTCL] %s' %
  5348. _("Export Code cancelled."))
  5349. return
  5350. else:
  5351. try:
  5352. my_gcode = self.ui.code_editor.toPlainText()
  5353. with open(filename, 'w') as f:
  5354. for line in my_gcode:
  5355. f.write(line)
  5356. except FileNotFoundError:
  5357. self.inform.emit('[WARNING] %s' %
  5358. _("No such file or directory"))
  5359. return
  5360. except PermissionError:
  5361. self.inform.emit('[WARNING] %s' %
  5362. _("Permission denied, saving not possible.\n"
  5363. "Most likely another app is holding the file open and not accessible."))
  5364. return
  5365. # Just for adding it to the recent files list.
  5366. if self.defaults["global_open_style"] is False:
  5367. self.file_opened.emit("cncjob", filename)
  5368. self.file_saved.emit("cncjob", filename)
  5369. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5370. def handleFindGCode(self):
  5371. self.report_usage("handleFindGCode()")
  5372. flags = QtGui.QTextDocument.FindCaseSensitively
  5373. text_to_be_found = self.ui.entryFind.get_value()
  5374. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5375. if r is False:
  5376. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5377. def handleReplaceGCode(self):
  5378. self.report_usage("handleReplaceGCode()")
  5379. old = self.ui.entryFind.get_value()
  5380. new = self.ui.entryReplace.get_value()
  5381. if self.ui.sel_all_cb.isChecked():
  5382. while True:
  5383. cursor = self.ui.code_editor.textCursor()
  5384. cursor.beginEditBlock()
  5385. flags = QtGui.QTextDocument.FindCaseSensitively
  5386. # self.ui.editor is the QPlainTextEdit
  5387. r = self.ui.code_editor.find(str(old), flags)
  5388. if r:
  5389. qc = self.ui.code_editor.textCursor()
  5390. if qc.hasSelection():
  5391. qc.insertText(new)
  5392. else:
  5393. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5394. break
  5395. # Mark end of undo block
  5396. cursor.endEditBlock()
  5397. else:
  5398. cursor = self.ui.code_editor.textCursor()
  5399. cursor.beginEditBlock()
  5400. qc = self.ui.code_editor.textCursor()
  5401. if qc.hasSelection():
  5402. qc.insertText(new)
  5403. # Mark end of undo block
  5404. cursor.endEditBlock()
  5405. def handleRunCode(self):
  5406. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5407. # tries to print on a hidden widget, therefore show the dock if hidden
  5408. if self.ui.shell_dock.isHidden():
  5409. self.ui.shell_dock.show()
  5410. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5411. # self.shell._sysShell.exec_command(script_code)
  5412. old_line = ''
  5413. for tcl_command_line in self.script_code.splitlines():
  5414. # do not process lines starting with '#' = comment and empty lines
  5415. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5416. # id FlatCAM is run in Windows then replace all the slashes with
  5417. # the UNIX style slash that TCL understands
  5418. if sys.platform == 'win32':
  5419. if "open" in tcl_command_line:
  5420. tcl_command_line = tcl_command_line.replace('\\', '/')
  5421. if old_line != '':
  5422. new_command = old_line + tcl_command_line + '\n'
  5423. else:
  5424. new_command = tcl_command_line
  5425. # execute the actual Tcl command
  5426. try:
  5427. self.shell.open_proccessing() # Disables input box.
  5428. result = self.tcl.eval(str(new_command))
  5429. if result != 'None':
  5430. self.shell.append_output(result + '\n')
  5431. old_line = ''
  5432. except tk.TclError:
  5433. old_line = old_line + tcl_command_line + '\n'
  5434. except Exception as e:
  5435. log.debug("App.handleRunCode() --> %s" % str(e))
  5436. if old_line != '':
  5437. # it means that the script finished with an error
  5438. result = self.tcl.eval("set errorInfo")
  5439. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5440. self.shell.append_error('ERROR: ' + result + '\n')
  5441. self.shell.close_proccessing()
  5442. def on_tool_add_keypress(self):
  5443. # ## Current application units in Upper Case
  5444. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5445. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5446. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5447. if notebook_widget_name == 'selected_tab':
  5448. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5449. # Tool add works for Geometry only if Advanced is True in Preferences
  5450. if self.defaults["global_app_level"] == 'a':
  5451. tool_add_popup = FCInputDialog(title="New Tool ...",
  5452. text='Enter a Tool Diameter:',
  5453. min=0.0000, max=99.9999, decimals=4)
  5454. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5455. val, ok = tool_add_popup.get_value()
  5456. if ok:
  5457. if float(val) == 0:
  5458. self.inform.emit('[WARNING_NOTCL] %s' %
  5459. _("Please enter a tool diameter with non-zero value, in Float format."))
  5460. return
  5461. self.collection.get_active().on_tool_add(dia=float(val))
  5462. else:
  5463. self.inform.emit('[WARNING_NOTCL] %s...' %
  5464. _("Adding Tool cancelled"))
  5465. else:
  5466. msgbox = QtWidgets.QMessageBox()
  5467. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5468. "Go to Preferences -> General - Show Advanced Options."))
  5469. msgbox.setWindowTitle("Tool adding ...")
  5470. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5471. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5472. msgbox.setDefaultButton(bt_ok)
  5473. msgbox.exec_()
  5474. # work only if the notebook tab on focus is the Tools_Tab
  5475. if notebook_widget_name == 'tool_tab':
  5476. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5477. tool_add_popup = FCInputDialog(title="New Tool ...",
  5478. text='Enter a Tool Diameter:',
  5479. min=0.0000, max=99.9999, decimals=4)
  5480. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5481. val, ok = tool_add_popup.get_value()
  5482. # and only if the tool is NCC Tool
  5483. if tool_widget == self.ncclear_tool.toolName:
  5484. if ok:
  5485. if float(val) == 0:
  5486. self.inform.emit('[WARNING_NOTCL] %s' %
  5487. _("Please enter a tool diameter with non-zero value, in Float format."))
  5488. return
  5489. self.ncclear_tool.on_tool_add(dia=float(val))
  5490. else:
  5491. self.inform.emit('[WARNING_NOTCL] %s...' %
  5492. _("Adding Tool cancelled"))
  5493. # and only if the tool is Paint Area Tool
  5494. elif tool_widget == self.paint_tool.toolName:
  5495. if ok:
  5496. if float(val) == 0:
  5497. self.inform.emit('[WARNING_NOTCL] %s' %
  5498. _("Please enter a tool diameter with non-zero value, in Float format."))
  5499. return
  5500. self.paint_tool.on_tool_add(dia=float(val))
  5501. else:
  5502. self.inform.emit('[WARNING_NOTCL] %s...' %
  5503. _("Adding Tool cancelled"))
  5504. # and only if the tool is Solder Paste Dispensing Tool
  5505. elif tool_widget == self.paste_tool.toolName:
  5506. if ok:
  5507. if float(val) == 0:
  5508. self.inform.emit('[WARNING_NOTCL] %s' %
  5509. _("Please enter a tool diameter with non-zero value, in Float format."))
  5510. return
  5511. self.paste_tool.on_tool_add(dia=float(val))
  5512. else:
  5513. self.inform.emit('[WARNING_NOTCL] %s...' %
  5514. _("Adding Tool cancelled"))
  5515. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5516. # See description bellow.
  5517. def on_delete_keypress(self):
  5518. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5519. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5520. if notebook_widget_name == 'selected_tab':
  5521. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5522. self.collection.get_active().on_tool_delete()
  5523. # work only if the notebook tab on focus is the Tools_Tab
  5524. elif notebook_widget_name == 'tool_tab':
  5525. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5526. # and only if the tool is NCC Tool
  5527. if tool_widget == self.ncclear_tool.toolName:
  5528. self.ncclear_tool.on_tool_delete()
  5529. # and only if the tool is Paint Tool
  5530. elif tool_widget == self.paint_tool.toolName:
  5531. self.paint_tool.on_tool_delete()
  5532. # and only if the tool is Solder Paste Dispensing Tool
  5533. elif tool_widget == self.paste_tool.toolName:
  5534. self.paste_tool.on_tool_delete()
  5535. else:
  5536. self.on_delete()
  5537. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5538. # some screens you have to be careful where you hover with your mouse.
  5539. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5540. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5541. # Complicated, I know :)
  5542. def on_delete(self):
  5543. """
  5544. Delete the currently selected FlatCAMObjs.
  5545. :return: None
  5546. """
  5547. self.report_usage("on_delete()")
  5548. response = None
  5549. bt_ok = None
  5550. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5551. # a geometry object before we update it.
  5552. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5553. and self.grb_editor.editor_active is False:
  5554. if self.defaults["global_delete_confirmation"] is True:
  5555. msgbox = QtWidgets.QMessageBox()
  5556. msgbox.setWindowTitle(_("Delete objects"))
  5557. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5558. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5559. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5560. "the selected objects?"))
  5561. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5562. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5563. msgbox.setDefaultButton(bt_ok)
  5564. msgbox.exec_()
  5565. response = msgbox.clickedButton()
  5566. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5567. if self.collection.get_active():
  5568. self.log.debug("App.on_delete()")
  5569. while self.collection.get_active():
  5570. obj_active = self.collection.get_active()
  5571. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5572. if isinstance(obj_active, FlatCAMGerber):
  5573. for el in obj_active.mark_shapes:
  5574. obj_active.mark_shapes[el].clear(update=True)
  5575. obj_active.mark_shapes[el].enabled = False
  5576. # obj_active.mark_shapes[el] = None
  5577. del el
  5578. elif isinstance(obj_active, FlatCAMCNCjob):
  5579. try:
  5580. obj_active.annotation.clear(update=True)
  5581. obj_active.annotation.enabled = False
  5582. except AttributeError:
  5583. pass
  5584. self.delete_first_selected()
  5585. self.inform.emit('%s...' %
  5586. _("Object(s) deleted"))
  5587. # make sure that the selection shape is deleted, too
  5588. self.delete_selection_shape()
  5589. else:
  5590. self.inform.emit(_("Failed. No object(s) selected..."))
  5591. else:
  5592. self.inform.emit(_("Save the work in Editor and try again ..."))
  5593. def delete_first_selected(self):
  5594. # Keep this for later
  5595. try:
  5596. sel_obj = self.collection.get_active()
  5597. name = sel_obj.options["name"]
  5598. isPlotted = sel_obj.options["plot"]
  5599. except AttributeError:
  5600. self.log.debug("Nothing selected for deletion")
  5601. return
  5602. if self.is_legacy is True:
  5603. # Remove plot only if the object was plotted otherwise delaxes will fail
  5604. if isPlotted:
  5605. self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5606. self.plotcanvas.auto_adjust_axes()
  5607. # Remove from dictionary
  5608. self.collection.delete_active()
  5609. # Clear form
  5610. self.setup_component_editor()
  5611. self.inform.emit('%s: %s' %
  5612. (_("Object deleted"), name))
  5613. def on_set_origin(self):
  5614. """
  5615. Set the origin to the left mouse click position
  5616. :return: None
  5617. """
  5618. # display the message for the user
  5619. # and ask him to click on the desired position
  5620. self.report_usage("on_set_origin()")
  5621. def origin_replot():
  5622. def worker_task():
  5623. with self.proc_container.new('%s...' % _("Plotting")):
  5624. for obj in self.collection.get_list():
  5625. obj.plot()
  5626. self.plotcanvas.fit_view()
  5627. if self.is_legacy:
  5628. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5629. else:
  5630. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5631. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5632. self.inform.emit(_('Click to set the origin ...'))
  5633. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5634. # first disconnect it as it may have been used by something else
  5635. try:
  5636. self.replot_signal.disconnect()
  5637. except TypeError:
  5638. pass
  5639. self.replot_signal[list].connect(origin_replot)
  5640. def on_set_zero_click(self, event):
  5641. # this function will be available only for mouse left click
  5642. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5643. if event.button == 1:
  5644. if self.grid_status() == True:
  5645. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5646. else:
  5647. pos = pos_canvas
  5648. x = 0 - pos[0]
  5649. y = 0 - pos[1]
  5650. def worker_task():
  5651. with self.proc_container.new(_("Setting Origin...")):
  5652. for obj in self.collection.get_list():
  5653. obj.offset((x, y))
  5654. self.object_changed.emit(obj)
  5655. # Update the object bounding box options
  5656. a, b, c, d = obj.bounds()
  5657. obj.options['xmin'] = a
  5658. obj.options['ymin'] = b
  5659. obj.options['xmax'] = c
  5660. obj.options['ymax'] = d
  5661. self.inform.emit('[success]%s...' %
  5662. _('Origin set'))
  5663. self.replot_signal.emit([])
  5664. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5665. self.should_we_save = True
  5666. def on_jump_to(self, custom_location=None, fit_center=True):
  5667. """
  5668. Jump to a location by setting the mouse cursor location
  5669. :return:
  5670. """
  5671. self.report_usage("on_jump_to()")
  5672. if self.is_legacy is True:
  5673. self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5674. return
  5675. if not custom_location:
  5676. dia_box = Dialog_box(title=_("Jump to ..."),
  5677. label=_("Enter the coordinates in format X,Y:"),
  5678. icon=QtGui.QIcon('share/jump_to16.png'))
  5679. if dia_box.ok is True:
  5680. try:
  5681. location = eval(dia_box.location)
  5682. if not isinstance(location, tuple):
  5683. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5684. return
  5685. except:
  5686. return
  5687. else:
  5688. return
  5689. else:
  5690. location = custom_location
  5691. if fit_center:
  5692. if self.is_legacy is False:
  5693. self.plotcanvas.fit_center(loc=location)
  5694. else:
  5695. pass
  5696. # self.plotcanvas.fit_view()
  5697. cursor = QtGui.QCursor()
  5698. if self.is_legacy is False:
  5699. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5700. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5701. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5702. else:
  5703. # the origin finding works but not mapping the location to pixels
  5704. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5705. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5706. x0, y0 = x0 + self.plotcanvas.axes.transData.transform((0, 0))[0], y0 - \
  5707. self.plotcanvas.axes.transData.transform((0, 0))[1]
  5708. loc = self.plotcanvas.axes.transData.transform(location)
  5709. cursor.setPos(x0 + loc[0]/50, y0 - loc[1]/50)
  5710. self.inform.emit('[success] %s' %
  5711. _("Done."))
  5712. return location
  5713. def on_copy_object(self):
  5714. self.report_usage("on_copy_object()")
  5715. def initialize(obj_init, app):
  5716. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5717. try:
  5718. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5719. except AttributeError:
  5720. pass
  5721. try:
  5722. obj_init.apertures = deepcopy(obj.apertures)
  5723. except AttributeError:
  5724. pass
  5725. try:
  5726. if obj.tools:
  5727. obj_init.tools = deepcopy(obj.tools)
  5728. except Exception as e:
  5729. log.debug("App.on_copy_object() --> %s" % str(e))
  5730. def initialize_excellon(obj_init, app):
  5731. obj_init.tools = deepcopy(obj.tools)
  5732. # drills are offset, so they need to be deep copied
  5733. obj_init.drills = deepcopy(obj.drills)
  5734. # slots are offset, so they need to be deep copied
  5735. obj_init.slots = deepcopy(obj.slots)
  5736. obj_init.create_geometry()
  5737. for obj in self.collection.get_selected():
  5738. obj_name = obj.options["name"]
  5739. try:
  5740. if isinstance(obj, FlatCAMExcellon):
  5741. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5742. elif isinstance(obj, FlatCAMGerber):
  5743. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5744. elif isinstance(obj, FlatCAMGeometry):
  5745. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5746. except Exception as e:
  5747. return "Operation failed: %s" % str(e)
  5748. def on_copy_object2(self, custom_name):
  5749. def initialize_geometry(obj_init, app):
  5750. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5751. try:
  5752. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5753. except AttributeError:
  5754. pass
  5755. try:
  5756. obj_init.apertures = deepcopy(obj.apertures)
  5757. except AttributeError:
  5758. pass
  5759. try:
  5760. if obj.tools:
  5761. obj_init.tools = deepcopy(obj.tools)
  5762. except Exception as e:
  5763. log.debug("on_copy_object2() --> %s" % str(e))
  5764. def initialize_gerber(obj_init, app):
  5765. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5766. obj_init.apertures = deepcopy(obj.apertures)
  5767. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5768. def initialize_excellon(obj_init, app):
  5769. obj_init.tools = deepcopy(obj.tools)
  5770. # drills are offset, so they need to be deep copied
  5771. obj_init.drills = deepcopy(obj.drills)
  5772. # slots are offset, so they need to be deep copied
  5773. obj_init.slots = deepcopy(obj.slots)
  5774. obj_init.create_geometry()
  5775. for obj in self.collection.get_selected():
  5776. obj_name = obj.options["name"]
  5777. try:
  5778. if isinstance(obj, FlatCAMExcellon):
  5779. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5780. elif isinstance(obj, FlatCAMGerber):
  5781. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5782. elif isinstance(obj, FlatCAMGeometry):
  5783. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5784. except Exception as e:
  5785. return "Operation failed: %s" % str(e)
  5786. def on_rename_object(self, text):
  5787. self.report_usage("on_rename_object()")
  5788. named_obj = self.collection.get_active()
  5789. for obj in named_obj:
  5790. if obj is list:
  5791. self.on_rename_object(text)
  5792. else:
  5793. try:
  5794. obj.options['name'] = text
  5795. except Exception as e:
  5796. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5797. def convert_any2geo(self):
  5798. self.report_usage("convert_any2geo()")
  5799. def initialize(obj_init, app):
  5800. obj_init.solid_geometry = obj.solid_geometry
  5801. try:
  5802. obj_init.follow_geometry = obj.follow_geometry
  5803. except AttributeError:
  5804. pass
  5805. try:
  5806. obj_init.apertures = obj.apertures
  5807. except AttributeError:
  5808. pass
  5809. try:
  5810. if obj.tools:
  5811. obj_init.tools = obj.tools
  5812. except AttributeError:
  5813. pass
  5814. def initialize_excellon(obj_init, app):
  5815. # objs = self.collection.get_selected()
  5816. # FlatCAMGeometry.merge(objs, obj)
  5817. solid_geo = []
  5818. for tool in obj.tools:
  5819. for geo in obj.tools[tool]['solid_geometry']:
  5820. solid_geo.append(geo)
  5821. obj_init.solid_geometry = deepcopy(solid_geo)
  5822. if not self.collection.get_selected():
  5823. log.warning("App.convert_any2geo --> No object selected")
  5824. self.inform.emit('[WARNING_NOTCL] %s' %
  5825. _("No object is selected. Select an object and try again."))
  5826. return
  5827. for obj in self.collection.get_selected():
  5828. obj_name = obj.options["name"]
  5829. try:
  5830. if isinstance(obj, FlatCAMExcellon):
  5831. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5832. else:
  5833. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5834. except Exception as e:
  5835. return "Operation failed: %s" % str(e)
  5836. def convert_any2gerber(self):
  5837. self.report_usage("convert_any2gerber()")
  5838. def initialize_geometry(obj_init, app):
  5839. apertures = {}
  5840. apid = 0
  5841. apertures[str(apid)] = {}
  5842. apertures[str(apid)]['geometry'] = []
  5843. for obj_orig in obj.solid_geometry:
  5844. new_elem = dict()
  5845. new_elem['solid'] = obj_orig
  5846. new_elem['follow'] = obj_orig.exterior
  5847. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5848. apertures[str(apid)]['size'] = 0.0
  5849. apertures[str(apid)]['type'] = 'C'
  5850. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5851. obj_init.apertures = deepcopy(apertures)
  5852. def initialize_excellon(obj_init, app):
  5853. apertures = {}
  5854. apid = 10
  5855. for tool in obj.tools:
  5856. apertures[str(apid)] = {}
  5857. apertures[str(apid)]['geometry'] = []
  5858. for geo in obj.tools[tool]['solid_geometry']:
  5859. new_el = dict()
  5860. new_el['solid'] = geo
  5861. new_el['follow'] = geo.exterior
  5862. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5863. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5864. apertures[str(apid)]['type'] = 'C'
  5865. apid += 1
  5866. # create solid_geometry
  5867. solid_geometry = []
  5868. for apid in apertures:
  5869. for geo_el in apertures[apid]['geometry']:
  5870. solid_geometry.append(geo_el['solid'])
  5871. solid_geometry = MultiPolygon(solid_geometry)
  5872. solid_geometry = solid_geometry.buffer(0.0000001)
  5873. obj_init.solid_geometry = deepcopy(solid_geometry)
  5874. obj_init.apertures = deepcopy(apertures)
  5875. # clear the working objects (perhaps not necessary due of Python GC)
  5876. apertures.clear()
  5877. if not self.collection.get_selected():
  5878. log.warning("App.convert_any2gerber --> No object selected")
  5879. self.inform.emit('[WARNING_NOTCL] %s' %
  5880. _("No object is selected. Select an object and try again."))
  5881. return
  5882. for obj in self.collection.get_selected():
  5883. obj_name = obj.options["name"]
  5884. try:
  5885. if isinstance(obj, FlatCAMExcellon):
  5886. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5887. elif isinstance(obj, FlatCAMGeometry):
  5888. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5889. else:
  5890. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5891. except Exception as e:
  5892. return "Operation failed: %s" % str(e)
  5893. def abort_all_tasks(self):
  5894. if self.abort_flag is False:
  5895. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5896. self.abort_flag = True
  5897. def app_is_idle(self):
  5898. if self.abort_flag:
  5899. self.inform.emit('[WARNING_NOTCL] %s' %
  5900. _("The current task was gracefully closed on user request..."))
  5901. self.abort_flag = False
  5902. def on_selectall(self):
  5903. self.report_usage("on_selectall()")
  5904. # delete the possible selection box around a possible selected object
  5905. self.delete_selection_shape()
  5906. for name in self.collection.get_names():
  5907. self.collection.set_active(name)
  5908. curr_sel_obj = self.collection.get_by_name(name)
  5909. # create the selection box around the selected object
  5910. if self.defaults['global_selection_shape'] is True:
  5911. self.draw_selection_shape(curr_sel_obj)
  5912. def on_preferences(self):
  5913. # add the tab if it was closed
  5914. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5915. # delete the absolute and relative position and messages in the infobar
  5916. self.ui.position_label.setText("")
  5917. self.ui.rel_position_label.setText("")
  5918. # Switch plot_area to preferences page
  5919. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5920. # self.ui.show()
  5921. # this disconnect() is done so the slot will be connected only once
  5922. try:
  5923. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5924. except (TypeError, AttributeError):
  5925. pass
  5926. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5927. # detect changes in the preferences
  5928. for idx in range(self.ui.pref_tab_area.count()):
  5929. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5930. try:
  5931. try:
  5932. tb.textEdited.disconnect(self.on_preferences_edited)
  5933. except (TypeError, AttributeError):
  5934. pass
  5935. tb.textEdited.connect(self.on_preferences_edited)
  5936. except AttributeError:
  5937. pass
  5938. try:
  5939. try:
  5940. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5941. except (TypeError, AttributeError):
  5942. pass
  5943. tb.modificationChanged.connect(self.on_preferences_edited)
  5944. except AttributeError:
  5945. pass
  5946. try:
  5947. try:
  5948. tb.toggled.disconnect(self.on_preferences_edited)
  5949. except (TypeError, AttributeError):
  5950. pass
  5951. tb.toggled.connect(self.on_preferences_edited)
  5952. except AttributeError:
  5953. pass
  5954. try:
  5955. try:
  5956. tb.valueChanged.disconnect(self.on_preferences_edited)
  5957. except (TypeError, AttributeError):
  5958. pass
  5959. tb.valueChanged.connect(self.on_preferences_edited)
  5960. except AttributeError:
  5961. pass
  5962. try:
  5963. try:
  5964. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5965. except (TypeError, AttributeError):
  5966. pass
  5967. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5968. except AttributeError:
  5969. pass
  5970. def on_preferences_edited(self):
  5971. self.inform.emit('[WARNING_NOTCL] %s' %
  5972. _("Preferences edited but not saved."))
  5973. self.preferences_changed_flag = True
  5974. def on_preferences_closed(self):
  5975. # disconnect
  5976. for idx in range(self.ui.pref_tab_area.count()):
  5977. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5978. try:
  5979. tb.textEdited.disconnect(self.on_preferences_edited)
  5980. except (TypeError, AttributeError):
  5981. pass
  5982. try:
  5983. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5984. except (TypeError, AttributeError):
  5985. pass
  5986. try:
  5987. tb.toggled.disconnect(self.on_preferences_edited)
  5988. except (TypeError, AttributeError):
  5989. pass
  5990. try:
  5991. tb.valueChanged.disconnect(self.on_preferences_edited)
  5992. except (TypeError, AttributeError):
  5993. pass
  5994. try:
  5995. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5996. except (TypeError, AttributeError):
  5997. pass
  5998. if self.preferences_changed_flag is True:
  5999. msgbox = QtWidgets.QMessageBox()
  6000. msgbox.setText(_("One or more values are changed.\n"
  6001. "Do you want to save the Preferences?"))
  6002. msgbox.setWindowTitle(_("Save Preferences"))
  6003. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6004. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6005. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6006. msgbox.setDefaultButton(bt_yes)
  6007. msgbox.exec_()
  6008. response = msgbox.clickedButton()
  6009. if response == bt_yes:
  6010. self.on_save_button()
  6011. self.inform.emit('[success] %s' %
  6012. _("Preferences saved."))
  6013. else:
  6014. self.preferences_changed_flag = False
  6015. return
  6016. def on_flipy(self):
  6017. self.report_usage("on_flipy()")
  6018. obj_list = self.collection.get_selected()
  6019. xminlist = []
  6020. yminlist = []
  6021. xmaxlist = []
  6022. ymaxlist = []
  6023. if not obj_list:
  6024. self.inform.emit('[WARNING_NOTCL] %s' %
  6025. _("No object selected to Flip on Y axis."))
  6026. else:
  6027. try:
  6028. # first get a bounding box to fit all
  6029. for obj in obj_list:
  6030. xmin, ymin, xmax, ymax = obj.bounds()
  6031. xminlist.append(xmin)
  6032. yminlist.append(ymin)
  6033. xmaxlist.append(xmax)
  6034. ymaxlist.append(ymax)
  6035. # get the minimum x,y and maximum x,y for all objects selected
  6036. xminimal = min(xminlist)
  6037. yminimal = min(yminlist)
  6038. xmaximal = max(xmaxlist)
  6039. ymaximal = max(ymaxlist)
  6040. px = 0.5 * (xminimal + xmaximal)
  6041. py = 0.5 * (yminimal + ymaximal)
  6042. # execute mirroring
  6043. for obj in obj_list:
  6044. obj.mirror('X', [px, py])
  6045. obj.plot()
  6046. self.object_changed.emit(obj)
  6047. self.inform.emit('[success] %s' %
  6048. _("Flip on Y axis done."))
  6049. except Exception as e:
  6050. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6051. (_("Flip action was not executed."), str(e)))
  6052. return
  6053. def on_flipx(self):
  6054. self.report_usage("on_flipx()")
  6055. obj_list = self.collection.get_selected()
  6056. xminlist = []
  6057. yminlist = []
  6058. xmaxlist = []
  6059. ymaxlist = []
  6060. if not obj_list:
  6061. self.inform.emit('[WARNING_NOTCL] %s' %
  6062. _("No object selected to Flip on X axis."))
  6063. else:
  6064. try:
  6065. # first get a bounding box to fit all
  6066. for obj in obj_list:
  6067. xmin, ymin, xmax, ymax = obj.bounds()
  6068. xminlist.append(xmin)
  6069. yminlist.append(ymin)
  6070. xmaxlist.append(xmax)
  6071. ymaxlist.append(ymax)
  6072. # get the minimum x,y and maximum x,y for all objects selected
  6073. xminimal = min(xminlist)
  6074. yminimal = min(yminlist)
  6075. xmaximal = max(xmaxlist)
  6076. ymaximal = max(ymaxlist)
  6077. px = 0.5 * (xminimal + xmaximal)
  6078. py = 0.5 * (yminimal + ymaximal)
  6079. # execute mirroring
  6080. for obj in obj_list:
  6081. obj.mirror('Y', [px, py])
  6082. obj.plot()
  6083. self.object_changed.emit(obj)
  6084. self.inform.emit('[success] %s' %
  6085. _("Flip on X axis done."))
  6086. except Exception as e:
  6087. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6088. (_("Flip action was not executed."), str(e)))
  6089. return
  6090. def on_rotate(self, silent=False, preset=None):
  6091. self.report_usage("on_rotate()")
  6092. obj_list = self.collection.get_selected()
  6093. xminlist = []
  6094. yminlist = []
  6095. xmaxlist = []
  6096. ymaxlist = []
  6097. if not obj_list:
  6098. self.inform.emit('[WARNING_NOTCL] %s' %
  6099. _("No object selected to Rotate."))
  6100. else:
  6101. if silent is False:
  6102. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6103. min=-360, max=360, decimals=4,
  6104. init_val=float(self.defaults['tools_transform_rotate']))
  6105. num, ok = rotatebox.get_value()
  6106. else:
  6107. num = preset
  6108. ok = True
  6109. if ok:
  6110. try:
  6111. # first get a bounding box to fit all
  6112. for obj in obj_list:
  6113. xmin, ymin, xmax, ymax = obj.bounds()
  6114. xminlist.append(xmin)
  6115. yminlist.append(ymin)
  6116. xmaxlist.append(xmax)
  6117. ymaxlist.append(ymax)
  6118. # get the minimum x,y and maximum x,y for all objects selected
  6119. xminimal = min(xminlist)
  6120. yminimal = min(yminlist)
  6121. xmaximal = max(xmaxlist)
  6122. ymaximal = max(ymaxlist)
  6123. px = 0.5 * (xminimal + xmaximal)
  6124. py = 0.5 * (yminimal + ymaximal)
  6125. for sel_obj in obj_list:
  6126. sel_obj.rotate(-float(num), point=(px, py))
  6127. sel_obj.plot()
  6128. self.object_changed.emit(sel_obj)
  6129. self.inform.emit('[success] %s' %
  6130. _("Rotation done."))
  6131. except Exception as e:
  6132. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6133. (_("Rotation movement was not executed."), str(e)))
  6134. return
  6135. def on_skewx(self):
  6136. self.report_usage("on_skewx()")
  6137. obj_list = self.collection.get_selected()
  6138. xminlist = []
  6139. yminlist = []
  6140. if not obj_list:
  6141. self.inform.emit('[WARNING_NOTCL] %s' %
  6142. _("No object selected to Skew/Shear on X axis."))
  6143. else:
  6144. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6145. min=-360, max=360, decimals=4,
  6146. init_val=float(self.defaults['tools_transform_skew_x']))
  6147. num, ok = skewxbox.get_value()
  6148. if ok:
  6149. # first get a bounding box to fit all
  6150. for obj in obj_list:
  6151. xmin, ymin, xmax, ymax = obj.bounds()
  6152. xminlist.append(xmin)
  6153. yminlist.append(ymin)
  6154. # get the minimum x,y and maximum x,y for all objects selected
  6155. xminimal = min(xminlist)
  6156. yminimal = min(yminlist)
  6157. for obj in obj_list:
  6158. obj.skew(num, 0, point=(xminimal, yminimal))
  6159. obj.plot()
  6160. self.object_changed.emit(obj)
  6161. self.inform.emit('[success] %s' %
  6162. _("Skew on X axis done."))
  6163. def on_skewy(self):
  6164. self.report_usage("on_skewy()")
  6165. obj_list = self.collection.get_selected()
  6166. xminlist = []
  6167. yminlist = []
  6168. if not obj_list:
  6169. self.inform.emit('[WARNING_NOTCL] %s' %
  6170. _("No object selected to Skew/Shear on Y axis."))
  6171. else:
  6172. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6173. min=-360, max=360, decimals=4,
  6174. init_val=float(self.defaults['tools_transform_skew_y']))
  6175. num, ok = skewybox.get_value()
  6176. if ok:
  6177. # first get a bounding box to fit all
  6178. for obj in obj_list:
  6179. xmin, ymin, xmax, ymax = obj.bounds()
  6180. xminlist.append(xmin)
  6181. yminlist.append(ymin)
  6182. # get the minimum x,y and maximum x,y for all objects selected
  6183. xminimal = min(xminlist)
  6184. yminimal = min(yminlist)
  6185. for obj in obj_list:
  6186. obj.skew(0, num, point=(xminimal, yminimal))
  6187. obj.plot()
  6188. self.object_changed.emit(obj)
  6189. self.inform.emit('[success] %s' %
  6190. _("Skew on Y axis done."))
  6191. def on_plots_updated(self):
  6192. """
  6193. Callback used to report when the plots have changed.
  6194. Adjust axes and zooms to fit.
  6195. :return: None
  6196. """
  6197. if self.is_legacy is False:
  6198. self.plotcanvas.update() # TODO: Need update canvas?
  6199. else:
  6200. self.plotcanvas.auto_adjust_axes()
  6201. self.on_zoom_fit(None)
  6202. self.collection.update_view()
  6203. # self.inform.emit(_("Plots updated ..."))
  6204. # TODO: Rework toolbar 'clear', 'replot' functions
  6205. def on_toolbar_replot(self):
  6206. """
  6207. Callback for toolbar button. Re-plots all objects.
  6208. :return: None
  6209. """
  6210. self.report_usage("on_toolbar_replot")
  6211. self.log.debug("on_toolbar_replot()")
  6212. try:
  6213. self.collection.get_active().read_form()
  6214. except AttributeError:
  6215. self.log.debug("on_toolbar_replot(): AttributeError")
  6216. pass
  6217. self.plot_all()
  6218. def on_row_activated(self, index):
  6219. if index.isValid():
  6220. if index.internalPointer().parent_item != self.collection.root_item:
  6221. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6222. self.collection.on_item_activated(index)
  6223. def grid_status(self):
  6224. if self.ui.grid_snap_btn.isChecked():
  6225. return True
  6226. else:
  6227. return False
  6228. def populate_cmenu_grids(self):
  6229. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6230. self.ui.cmenu_gridmenu.clear()
  6231. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6232. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6233. grid_toggle.setCheckable(True)
  6234. if self.grid_status() == True:
  6235. grid_toggle.setChecked(True)
  6236. else:
  6237. grid_toggle.setChecked(False)
  6238. self.ui.cmenu_gridmenu.addSeparator()
  6239. for grid in sorted_list:
  6240. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6241. action.triggered.connect(self.set_grid)
  6242. self.ui.cmenu_gridmenu.addSeparator()
  6243. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6244. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6245. grid_add.triggered.connect(self.on_grid_add)
  6246. grid_delete.triggered.connect(self.on_grid_delete)
  6247. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6248. def set_grid(self):
  6249. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6250. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6251. def on_grid_add(self):
  6252. # ## Current application units in lower Case
  6253. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6254. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6255. text=_('Enter a Grid Value:'),
  6256. min=0.0000, max=99.9999, decimals=4)
  6257. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6258. val, ok = grid_add_popup.get_value()
  6259. if ok:
  6260. if float(val) == 0:
  6261. self.inform.emit('[WARNING_NOTCL] %s' %
  6262. _("Please enter a grid value with non-zero value, in Float format."))
  6263. return
  6264. else:
  6265. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6266. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6267. self.inform.emit('[success] %s...' %
  6268. _("New Grid added"))
  6269. else:
  6270. self.inform.emit('[WARNING_NOTCL] %s...' %
  6271. _("Grid already exists"))
  6272. else:
  6273. self.inform.emit('[WARNING_NOTCL] %s...' %
  6274. _("Adding New Grid cancelled"))
  6275. def on_grid_delete(self):
  6276. # ## Current application units in lower Case
  6277. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6278. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6279. text='Enter a Grid Value:',
  6280. min=0.0000, max=99.9999, decimals=4)
  6281. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6282. val, ok = grid_del_popup.get_value()
  6283. if ok:
  6284. if float(val) == 0:
  6285. self.inform.emit('[WARNING_NOTCL] %s' %
  6286. _("Please enter a grid value with non-zero value, in Float format."))
  6287. return
  6288. else:
  6289. try:
  6290. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6291. except ValueError:
  6292. self.inform.emit('[ERROR_NOTCL]%s...' %
  6293. _(" Grid Value does not exist"))
  6294. return
  6295. self.inform.emit('[success] %s...' %
  6296. _("Grid Value deleted"))
  6297. else:
  6298. self.inform.emit('[WARNING_NOTCL] %s...' %
  6299. _("Delete Grid value cancelled"))
  6300. def on_shortcut_list(self):
  6301. self.report_usage("on_shortcut_list()")
  6302. # add the tab if it was closed
  6303. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6304. # delete the absolute and relative position and messages in the infobar
  6305. self.ui.position_label.setText("")
  6306. self.ui.rel_position_label.setText("")
  6307. # Switch plot_area to preferences page
  6308. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6309. # self.ui.show()
  6310. def on_select_tab(self, name):
  6311. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6312. if self.ui.splitter.sizes()[0] == 0:
  6313. self.ui.splitter.setSizes([1, 1])
  6314. else:
  6315. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6316. self.ui.splitter.setSizes([0, 1])
  6317. if name == 'project':
  6318. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6319. elif name == 'selected':
  6320. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6321. elif name == 'tool':
  6322. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6323. def on_copy_name(self):
  6324. self.report_usage("on_copy_name()")
  6325. obj = self.collection.get_active()
  6326. try:
  6327. name = obj.options["name"]
  6328. except AttributeError:
  6329. log.debug("on_copy_name() --> No object selected to copy it's name")
  6330. self.inform.emit('[WARNING_NOTCL]%s' %
  6331. _(" No object selected to copy it's name"))
  6332. return
  6333. self.clipboard.setText(name)
  6334. self.inform.emit(_("Name copied on clipboard ..."))
  6335. def on_mouse_click_over_plot(self, event):
  6336. """
  6337. Default actions are:
  6338. :param event: Contains information about the event, like which button
  6339. was clicked, the pixel coordinates and the axes coordinates.
  6340. :return: None
  6341. """
  6342. self.pos = []
  6343. if self.is_legacy is False:
  6344. event_pos = event.pos
  6345. if self.defaults["global_pan_button"] == '2':
  6346. pan_button = 2
  6347. else:
  6348. pan_button = 3
  6349. # Set the mouse button for panning
  6350. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6351. else:
  6352. event_pos = (event.xdata, event.ydata)
  6353. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6354. if self.defaults["global_pan_button"] == '2':
  6355. pan_button = 3
  6356. else:
  6357. pan_button = 2
  6358. # So it can receive key presses
  6359. self.plotcanvas.native.setFocus()
  6360. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6361. if self.grid_status() == True:
  6362. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6363. else:
  6364. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6365. try:
  6366. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6367. if event.button == 1:
  6368. # Reset here the relative coordinates so there is a new reference on the click position
  6369. if self.rel_point1 is None:
  6370. self.rel_point1 = self.pos
  6371. else:
  6372. self.rel_point2 = copy(self.rel_point1)
  6373. self.rel_point1 = self.pos
  6374. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6375. if modifiers == QtCore.Qt.ShiftModifier:
  6376. # do not auto open the Project Tab
  6377. self.click_noproject = True
  6378. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6379. self.inform.emit('[success] %s' %
  6380. _("Coordinates copied to clipboard."))
  6381. return
  6382. self.on_mouse_move_over_plot(event, origin_click=True)
  6383. except Exception as e:
  6384. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6385. def on_double_click_over_plot(self, event):
  6386. if event.button == 1:
  6387. self.doubleclick = True
  6388. def on_mouse_move_over_plot(self, event, origin_click=None):
  6389. """
  6390. Callback for the mouse motion event over the plot.
  6391. :param event: Contains information about the event.
  6392. :param origin_click
  6393. :return: None
  6394. """
  6395. if self.is_legacy is False:
  6396. event_pos = event.pos
  6397. if self.defaults["global_pan_button"] == '2':
  6398. pan_button = 2
  6399. else:
  6400. pan_button = 3
  6401. event_is_dragging = event.is_dragging
  6402. else:
  6403. event_pos = (event.xdata, event.ydata)
  6404. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6405. if self.defaults["global_pan_button"] == '2':
  6406. pan_button = 3
  6407. else:
  6408. pan_button = 2
  6409. event_is_dragging = self.plotcanvas.is_dragging
  6410. # So it can receive key presses
  6411. self.plotcanvas.native.setFocus()
  6412. self.pos_jump = event_pos
  6413. self.ui.popMenu.mouse_is_panning = False
  6414. if not origin_click:
  6415. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6416. if event.button == pan_button and event_is_dragging == 1:
  6417. self.ui.popMenu.mouse_is_panning = True
  6418. return
  6419. if self.rel_point1 is not None:
  6420. try: # May fail in case mouse not within axes
  6421. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6422. if self.grid_status() == True:
  6423. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6424. if self.is_legacy is False:
  6425. # Update cursor
  6426. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6427. symbol='++', edge_color='black', size=20)
  6428. else:
  6429. self.app_cursor.set_data(event, (pos[0], pos[1]))
  6430. else:
  6431. pos = (pos_canvas[0], pos_canvas[1])
  6432. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6433. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6434. dx = pos[0] - self.rel_point1[0]
  6435. dy = pos[1] - self.rel_point1[1]
  6436. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6437. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6438. self.mouse = [pos[0], pos[1]]
  6439. # if the mouse is moved and the LMB is clicked then the action is a selection
  6440. if event_is_dragging == 1 and event.button == 1:
  6441. self.delete_selection_shape()
  6442. if dx < 0:
  6443. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6444. face_color=self.defaults['global_alt_sel_fill'])
  6445. self.selection_type = False
  6446. else:
  6447. self.draw_moving_selection_shape(self.pos, pos)
  6448. self.selection_type = True
  6449. # hover effect - enabled in Preferences -> General -> GUI Settings
  6450. if self.defaults['global_hover']:
  6451. for obj in self.collection.get_list():
  6452. try:
  6453. # select the object(s) only if it is enabled (plotted)
  6454. if obj.options['plot']:
  6455. if obj not in self.collection.get_selected():
  6456. poly_obj = Polygon(
  6457. [(obj.options['xmin'], obj.options['ymin']),
  6458. (obj.options['xmax'], obj.options['ymin']),
  6459. (obj.options['xmax'], obj.options['ymax']),
  6460. (obj.options['xmin'], obj.options['ymax'])]
  6461. )
  6462. if Point(pos).within(poly_obj):
  6463. if obj.isHovering is False:
  6464. obj.isHovering = True
  6465. obj.notHovering = True
  6466. # create the selection box around the selected object
  6467. self.draw_hover_shape(obj, color='#d1e0e0')
  6468. else:
  6469. if obj.notHovering is True:
  6470. obj.notHovering = False
  6471. obj.isHovering = False
  6472. self.delete_hover_shape()
  6473. except:
  6474. # the Exception here will happen if we try to select on screen and we have an
  6475. # newly (and empty) just created Geometry or Excellon object that do not have the
  6476. # xmin, xmax, ymin, ymax options.
  6477. # In this case poly_obj creation (see above) will fail
  6478. pass
  6479. except:
  6480. self.ui.position_label.setText("")
  6481. self.ui.rel_position_label.setText("")
  6482. self.mouse = None
  6483. def on_mouse_click_release_over_plot(self, event):
  6484. """
  6485. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6486. and has been registered in ''self.__init__()''.
  6487. :param event: contains information about the event.
  6488. :return:
  6489. """
  6490. pos = 0, 0
  6491. if self.is_legacy is False:
  6492. event_pos = event.pos
  6493. right_button = 2
  6494. else:
  6495. event_pos = (event.xdata, event.ydata)
  6496. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6497. right_button = 3
  6498. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6499. if self.grid_status() == True:
  6500. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6501. else:
  6502. pos = (pos_canvas[0], pos_canvas[1])
  6503. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6504. # canvas menu
  6505. if event.button == right_button: # right click
  6506. if self.ui.popMenu.mouse_is_panning is False:
  6507. self.cursor = QtGui.QCursor()
  6508. self.populate_cmenu_grids()
  6509. self.ui.popMenu.popup(self.cursor.pos())
  6510. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6511. # selection and then select a type of selection ("enclosing" or "touching")
  6512. try:
  6513. if event.button == 1: # left click
  6514. if self.doubleclick is True:
  6515. self.doubleclick = False
  6516. if self.collection.get_selected():
  6517. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6518. if self.ui.splitter.sizes()[0] == 0:
  6519. self.ui.splitter.setSizes([1, 1])
  6520. # delete the selection shape(S) as it may be in the way
  6521. self.delete_selection_shape()
  6522. self.delete_hover_shape()
  6523. else:
  6524. if self.selection_type is not None:
  6525. self.selection_area_handler(self.pos, pos, self.selection_type)
  6526. self.selection_type = None
  6527. else:
  6528. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6529. if key_modifier == QtCore.Qt.ShiftModifier:
  6530. mod_key = 'Shift'
  6531. elif key_modifier == QtCore.Qt.ControlModifier:
  6532. mod_key = 'Control'
  6533. else:
  6534. mod_key = None
  6535. if mod_key == self.defaults["global_mselect_key"]:
  6536. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6537. # deselect, and if it's not selected then it will be selected
  6538. # If there is no active command (self.command_active is None) then we check if we clicked
  6539. # on a object by checking the bounding limits against mouse click position
  6540. if self.command_active is None:
  6541. self.select_objects(key='CTRL')
  6542. self.delete_hover_shape()
  6543. else:
  6544. # If there is no active command (self.command_active is None) then we check if we clicked
  6545. # on a object by checking the bounding limits against mouse click position
  6546. if self.command_active is None:
  6547. self.select_objects()
  6548. self.delete_hover_shape()
  6549. except Exception as e:
  6550. log.warning("Error: %s" % str(e))
  6551. return
  6552. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6553. """
  6554. :param start_pos: mouse position when the selection LMB click was done
  6555. :param end_pos: mouse position when the left mouse button is released
  6556. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6557. :return:
  6558. """
  6559. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6560. self.delete_selection_shape()
  6561. for obj in self.collection.get_list():
  6562. try:
  6563. # select the object(s) only if it is enabled (plotted)
  6564. if obj.options['plot']:
  6565. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6566. (obj.options['xmax'], obj.options['ymin']),
  6567. (obj.options['xmax'], obj.options['ymax']),
  6568. (obj.options['xmin'], obj.options['ymax'])])
  6569. if sel_type is True:
  6570. if poly_obj.within(poly_selection):
  6571. # create the selection box around the selected object
  6572. if self.defaults['global_selection_shape'] is True:
  6573. self.draw_selection_shape(obj)
  6574. self.collection.set_active(obj.options['name'])
  6575. else:
  6576. if poly_selection.intersects(poly_obj):
  6577. # create the selection box around the selected object
  6578. if self.defaults['global_selection_shape'] is True:
  6579. self.draw_selection_shape(obj)
  6580. self.collection.set_active(obj.options['name'])
  6581. except Exception as e:
  6582. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6583. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6584. # In this case poly_obj creation (see above) will fail
  6585. log.debug("App.selection_area_handler() --> %s" % str(e))
  6586. def select_objects(self, key=None):
  6587. # list where we store the overlapped objects under our mouse left click position
  6588. objects_under_the_click_list = []
  6589. # Populate the list with the overlapped objects on the click position
  6590. curr_x, curr_y = self.pos
  6591. for obj in self.all_objects_list:
  6592. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6593. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6594. if obj.options['name'] not in objects_under_the_click_list:
  6595. if obj.options['plot']:
  6596. # add objects to the objects_under_the_click list only if the object is plotted
  6597. # (active and not disabled)
  6598. objects_under_the_click_list.append(obj.options['name'])
  6599. try:
  6600. # If there is no element in the overlapped objects list then make everyone inactive
  6601. # because we selected "nothing"
  6602. if not objects_under_the_click_list:
  6603. self.collection.set_all_inactive()
  6604. # delete the possible selection box around a possible selected object
  6605. self.delete_selection_shape()
  6606. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6607. # only when working on App
  6608. if self.call_source == 'app':
  6609. if self.click_noproject is False:
  6610. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6611. else:
  6612. # restore auto open the Project Tab
  6613. self.click_noproject = False
  6614. # delete any text in the status bar, implicitly the last object name that was selected
  6615. self.inform.emit("")
  6616. else:
  6617. self.call_source = 'app'
  6618. else:
  6619. # case when there is only an object under the click and we toggle it
  6620. if len(objects_under_the_click_list) == 1:
  6621. if self.collection.get_active() is None:
  6622. self.collection.set_active(objects_under_the_click_list[0])
  6623. # create the selection box around the selected object
  6624. curr_sel_obj = self.collection.get_active()
  6625. if self.defaults['global_selection_shape'] is True:
  6626. self.draw_selection_shape(curr_sel_obj)
  6627. # self.inform.emit('[selected] %s: %s selected' %
  6628. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6629. if curr_sel_obj.kind == 'gerber':
  6630. self.inform.emit(
  6631. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6632. color='green', name=str(curr_sel_obj.options['name'])))
  6633. elif curr_sel_obj.kind == 'excellon':
  6634. self.inform.emit(
  6635. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6636. color='brown', name=str(curr_sel_obj.options['name'])))
  6637. elif curr_sel_obj.kind == 'cncjob':
  6638. self.inform.emit(
  6639. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6640. color='blue', name=str(curr_sel_obj.options['name'])))
  6641. elif curr_sel_obj.kind == 'geometry':
  6642. self.inform.emit(
  6643. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6644. color='red', name=str(curr_sel_obj.options['name'])))
  6645. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6646. self.collection.set_all_inactive()
  6647. self.delete_selection_shape()
  6648. self.collection.set_active(objects_under_the_click_list[0])
  6649. # create the selection box around the selected object
  6650. curr_sel_obj = self.collection.get_active()
  6651. if self.defaults['global_selection_shape'] is True:
  6652. self.draw_selection_shape(curr_sel_obj)
  6653. # self.inform.emit('[selected] %s: %s selected' %
  6654. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6655. if curr_sel_obj.kind == 'gerber':
  6656. self.inform.emit(
  6657. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6658. color='green', name=str(curr_sel_obj.options['name'])))
  6659. elif curr_sel_obj.kind == 'excellon':
  6660. self.inform.emit(
  6661. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6662. color='brown', name=str(curr_sel_obj.options['name'])))
  6663. elif curr_sel_obj.kind == 'cncjob':
  6664. self.inform.emit(
  6665. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6666. color='blue', name=str(curr_sel_obj.options['name'])))
  6667. elif curr_sel_obj.kind == 'geometry':
  6668. self.inform.emit(
  6669. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6670. color='red', name=str(curr_sel_obj.options['name'])))
  6671. else:
  6672. self.collection.set_all_inactive()
  6673. self.delete_selection_shape()
  6674. if self.call_source == 'app':
  6675. # delete any text in the status bar, implicitly the last object name that was selected
  6676. self.inform.emit("")
  6677. else:
  6678. self.call_source = 'app'
  6679. else:
  6680. # If there is no selected object
  6681. # make active the first element of the overlapped objects list
  6682. if self.collection.get_active() is None:
  6683. self.collection.set_active(objects_under_the_click_list[0])
  6684. name_sel_obj = self.collection.get_active().options['name']
  6685. # In case that there is a selected object but it is not in the overlapped object list
  6686. # make that object inactive and activate the first element in the overlapped object list
  6687. if name_sel_obj not in objects_under_the_click_list:
  6688. self.collection.set_inactive(name_sel_obj)
  6689. name_sel_obj = objects_under_the_click_list[0]
  6690. self.collection.set_active(name_sel_obj)
  6691. else:
  6692. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6693. self.collection.set_all_inactive()
  6694. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6695. len(objects_under_the_click_list)])
  6696. curr_sel_obj = self.collection.get_active()
  6697. # delete the possible selection box around a possible selected object
  6698. self.delete_selection_shape()
  6699. # create the selection box around the selected object
  6700. if self.defaults['global_selection_shape'] is True:
  6701. self.draw_selection_shape(curr_sel_obj)
  6702. # self.inform.emit('[selected] %s: %s selected' %
  6703. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6704. if curr_sel_obj.kind == 'gerber':
  6705. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6706. color='green', name=str(curr_sel_obj.options['name'])))
  6707. elif curr_sel_obj.kind == 'excellon':
  6708. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6709. color='brown', name=str(curr_sel_obj.options['name'])))
  6710. elif curr_sel_obj.kind == 'cncjob':
  6711. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6712. color='blue', name=str(curr_sel_obj.options['name'])))
  6713. elif curr_sel_obj.kind == 'geometry':
  6714. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6715. color='red', name=str(curr_sel_obj.options['name'])))
  6716. # for obj in self.collection.get_list():
  6717. # obj.plot()
  6718. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6719. # TODO: on selected objects change the object colors and do not draw the selection box
  6720. # self.plotcanvas.update() # this updates the canvas
  6721. except Exception as e:
  6722. log.error("[ERROR] Something went bad. %s" % str(e))
  6723. return
  6724. def delete_hover_shape(self):
  6725. self.hover_shapes.clear()
  6726. self.hover_shapes.redraw()
  6727. def draw_hover_shape(self, sel_obj, color=None):
  6728. """
  6729. :param sel_obj: the object for which the hover shape must be drawn
  6730. :return:
  6731. """
  6732. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6733. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6734. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6735. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6736. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6737. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6738. hover_rect = hover_rect.buffer(-0.1)
  6739. hover_rect = hover_rect.buffer(0.2)
  6740. else:
  6741. hover_rect = hover_rect.buffer(-0.00393)
  6742. hover_rect = hover_rect.buffer(0.00787)
  6743. if color:
  6744. face = Color(color)
  6745. face.alpha = 0.2
  6746. outline = Color(color, alpha=0.8)
  6747. else:
  6748. face = Color(self.defaults['global_sel_fill'])
  6749. face.alpha = 0.2
  6750. outline = self.defaults['global_sel_line']
  6751. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6752. def delete_selection_shape(self):
  6753. self.move_tool.sel_shapes.clear()
  6754. self.move_tool.sel_shapes.redraw()
  6755. def draw_selection_shape(self, sel_obj, color=None):
  6756. """
  6757. :param sel_obj: the object for which the selection shape must be drawn
  6758. :return:
  6759. """
  6760. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6761. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6762. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6763. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6764. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6765. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6766. sel_rect = sel_rect.buffer(-0.1)
  6767. sel_rect = sel_rect.buffer(0.2)
  6768. else:
  6769. sel_rect = sel_rect.buffer(-0.00393)
  6770. sel_rect = sel_rect.buffer(0.00787)
  6771. if color:
  6772. face = Color(color, alpha=0.2)
  6773. outline = Color(color, alpha=0.8)
  6774. else:
  6775. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6776. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6777. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6778. color=outline,
  6779. face_color=face,
  6780. update=True,
  6781. layer=0,
  6782. tolerance=None))
  6783. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6784. """
  6785. :param old_coords: old coordinates
  6786. :param coords: new coordinates
  6787. :return:
  6788. """
  6789. if 'color' in kwargs:
  6790. color = kwargs['color']
  6791. else:
  6792. color = self.defaults['global_sel_line']
  6793. if 'face_color' in kwargs:
  6794. face_color = kwargs['face_color']
  6795. else:
  6796. face_color = self.defaults['global_sel_fill']
  6797. if 'face_alpha' in kwargs:
  6798. face_alpha = kwargs['face_alpha']
  6799. else:
  6800. face_alpha = 0.3
  6801. x0, y0 = old_coords
  6802. x1, y1 = coords
  6803. pt1 = (x0, y0)
  6804. pt2 = (x1, y0)
  6805. pt3 = (x1, y1)
  6806. pt4 = (x0, y1)
  6807. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6808. color_t = Color(face_color)
  6809. color_t.alpha = face_alpha
  6810. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6811. layer=0, tolerance=None)
  6812. def on_file_new_click(self):
  6813. if self.collection.get_list() and self.should_we_save:
  6814. msgbox = QtWidgets.QMessageBox()
  6815. # msgbox.setText("<B>Save changes ...</B>")
  6816. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6817. "Creating a New project will delete them.\n"
  6818. "Do you want to Save the project?"))
  6819. msgbox.setWindowTitle(_("Save changes"))
  6820. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6821. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6822. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6823. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6824. msgbox.setDefaultButton(bt_yes)
  6825. msgbox.exec_()
  6826. response = msgbox.clickedButton()
  6827. if response == bt_yes:
  6828. self.on_file_saveprojectas()
  6829. elif response == bt_cancel:
  6830. return
  6831. elif response == bt_no:
  6832. self.on_file_new()
  6833. else:
  6834. self.on_file_new()
  6835. self.inform.emit('[success] %s...' %
  6836. _("New Project created"))
  6837. def on_file_new(self, cli=None):
  6838. """
  6839. Callback for menu item File->New. Returns the application to its
  6840. startup state. This method is thread-safe.
  6841. :return: None
  6842. """
  6843. self.report_usage("on_file_new")
  6844. # Remove everything from memory
  6845. App.log.debug("on_file_new()")
  6846. if self.call_source != 'app':
  6847. self.editor2object(cleanup=True)
  6848. # ## EDITOR section
  6849. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6850. self.exc_editor = FlatCAMExcEditor(self)
  6851. self.grb_editor = FlatCAMGrbEditor(self)
  6852. # Clear pool
  6853. self.clear_pool()
  6854. for obj in self.collection.get_list():
  6855. # delete shapes left drawn from mark shape_collections, if any
  6856. if isinstance(obj, FlatCAMGerber):
  6857. try:
  6858. obj.mark_shapes.enabled = False
  6859. obj.mark_shapes.clear(update=True)
  6860. except AttributeError:
  6861. pass
  6862. # also delete annotation shapes, if any
  6863. elif isinstance(obj, FlatCAMCNCjob):
  6864. try:
  6865. obj.annotation.enabled = False
  6866. obj.annotation.clear(update=True)
  6867. except AttributeError:
  6868. pass
  6869. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6870. self.init_tcl()
  6871. self.delete_selection_shape()
  6872. self.collection.delete_all()
  6873. self.setup_component_editor()
  6874. # Clear project filename
  6875. self.project_filename = None
  6876. # Load the application defaults
  6877. self.load_defaults(filename='current_defaults')
  6878. # Re-fresh project options
  6879. self.on_options_app2project()
  6880. # Init Tools
  6881. self.init_tools()
  6882. if cli is None:
  6883. # Close any Tabs opened in the Plot Tab Area section
  6884. for index in range(self.ui.plot_tab_area.count()):
  6885. self.ui.plot_tab_area.closeTab(index)
  6886. # for whatever reason previous command does not close the last tab so I do it manually
  6887. self.ui.plot_tab_area.closeTab(0)
  6888. # # And then add again the Plot Area
  6889. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6890. self.ui.plot_tab_area.protectTab(0)
  6891. # take the focus of the Notebook on Project Tab.
  6892. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6893. self.set_ui_title(name=_("New Project - Not saved"))
  6894. def obj_properties(self):
  6895. self.report_usage("obj_properties()")
  6896. self.properties_tool.run(toggle=False)
  6897. def on_project_context_save(self):
  6898. obj = self.collection.get_active()
  6899. if type(obj) == FlatCAMGeometry:
  6900. self.on_file_exportdxf()
  6901. elif type(obj) == FlatCAMExcellon:
  6902. self.on_file_saveexcellon()
  6903. elif type(obj) == FlatCAMCNCjob:
  6904. obj.on_exportgcode_button_click()
  6905. elif type(obj) == FlatCAMGerber:
  6906. self.on_file_savegerber()
  6907. def obj_move(self):
  6908. self.report_usage("obj_move()")
  6909. self.move_tool.run(toggle=False)
  6910. def on_fileopengerber(self, checked=None, name=None):
  6911. """
  6912. File menu callback for opening a Gerber.
  6913. :return: None
  6914. """
  6915. self.report_usage("on_fileopengerber")
  6916. App.log.debug("on_fileopengerber()")
  6917. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6918. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6919. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6920. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6921. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6922. "*.mil);;" \
  6923. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6924. "Allegro Files (*.art);;" \
  6925. "Mentor Files (*.pho *.gdo);;" \
  6926. "All Files (*.*)"
  6927. if name is None:
  6928. try:
  6929. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6930. directory=self.get_last_folder(),
  6931. filter=_filter_)
  6932. except TypeError:
  6933. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6934. filenames = [str(filename) for filename in filenames]
  6935. else:
  6936. filenames = [name]
  6937. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6938. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6939. _("Opening Gerber file.")),
  6940. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6941. color=QtGui.QColor("gray"))
  6942. if len(filenames) == 0:
  6943. self.inform.emit('[WARNING_NOTCL] %s' %
  6944. _("Open Gerber cancelled."))
  6945. else:
  6946. for filename in filenames:
  6947. if filename != '':
  6948. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6949. def on_fileopenexcellon(self, checked=None, name=None):
  6950. """
  6951. File menu callback for opening an Excellon file.
  6952. :return: None
  6953. """
  6954. self.report_usage("on_fileopenexcellon")
  6955. App.log.debug("on_fileopenexcellon()")
  6956. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6957. "All Files (*.*)"
  6958. if name is None:
  6959. try:
  6960. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6961. directory=self.get_last_folder(),
  6962. filter=_filter_)
  6963. except TypeError:
  6964. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6965. filenames = [str(filename) for filename in filenames]
  6966. else:
  6967. filenames = [str(name)]
  6968. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6969. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6970. _("Opening Excellon file.")),
  6971. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6972. color=QtGui.QColor("gray"))
  6973. if len(filenames) == 0:
  6974. self.inform.emit('[WARNING_NOTCL]%s' %
  6975. _(" Open Excellon cancelled."))
  6976. else:
  6977. for filename in filenames:
  6978. if filename != '':
  6979. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6980. def on_fileopengcode(self, checked=None, name=None):
  6981. """
  6982. File menu call back for opening gcode.
  6983. :return: None
  6984. """
  6985. self.report_usage("on_fileopengcode")
  6986. App.log.debug("on_fileopengcode()")
  6987. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6988. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6989. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6990. "All Files (*.*)"
  6991. if name is None:
  6992. try:
  6993. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6994. directory=self.get_last_folder(),
  6995. filter=_filter_)
  6996. except TypeError:
  6997. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6998. filenames = [str(filename) for filename in filenames]
  6999. else:
  7000. filenames = [name]
  7001. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7002. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7003. _("Opening G-Code file.")),
  7004. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7005. color=QtGui.QColor("gray"))
  7006. if len(filenames) == 0:
  7007. self.inform.emit('[WARNING_NOTCL] %s' %
  7008. _("Open G-Code cancelled."))
  7009. else:
  7010. for filename in filenames:
  7011. if filename != '':
  7012. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7013. def on_file_openproject(self, checked=None):
  7014. """
  7015. File menu callback for opening a project.
  7016. :return: None
  7017. """
  7018. self.report_usage("on_file_openproject")
  7019. App.log.debug("on_file_openproject()")
  7020. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7021. try:
  7022. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7023. directory=self.get_last_folder(), filter=_filter_)
  7024. except TypeError:
  7025. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7026. # The Qt methods above will return a QString which can cause problems later.
  7027. # So far json.dump() will fail to serialize it.
  7028. # TODO: Improve the serialization methods and remove this fix.
  7029. filename = str(filename)
  7030. if filename == "":
  7031. self.inform.emit('[WARNING_NOTCL] %s' %
  7032. _("Open Project cancelled."))
  7033. else:
  7034. # self.worker_task.emit({'fcn': self.open_project,
  7035. # 'params': [filename]})
  7036. # The above was failing because open_project() is not
  7037. # thread safe. The new_project()
  7038. self.open_project(filename)
  7039. def on_file_openconfig(self, checked=None):
  7040. """
  7041. File menu callback for opening a config file.
  7042. :return: None
  7043. """
  7044. self.report_usage("on_file_openconfig")
  7045. App.log.debug("on_file_openconfig()")
  7046. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7047. try:
  7048. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7049. directory=self.data_path, filter=_filter_)
  7050. except TypeError:
  7051. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7052. filter=_filter_)
  7053. if filename == "":
  7054. self.inform.emit('[WARNING_NOTCL] %s' %
  7055. _("Open Config cancelled."))
  7056. else:
  7057. self.open_config_file(filename)
  7058. def on_file_exportsvg(self):
  7059. """
  7060. Callback for menu item File->Export SVG.
  7061. :return: None
  7062. """
  7063. self.report_usage("on_file_exportsvg")
  7064. App.log.debug("on_file_exportsvg()")
  7065. obj = self.collection.get_active()
  7066. if obj is None:
  7067. self.inform.emit('[WARNING_NOTCL] %s' %
  7068. _("No object selected."))
  7069. msg = _("Please Select a Geometry object to export")
  7070. msgbox = QtWidgets.QMessageBox()
  7071. msgbox.setInformativeText(msg)
  7072. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7073. msgbox.setDefaultButton(bt_ok)
  7074. msgbox.exec_()
  7075. return
  7076. # Check for more compatible types and add as required
  7077. if (not isinstance(obj, FlatCAMGeometry)
  7078. and not isinstance(obj, FlatCAMGerber)
  7079. and not isinstance(obj, FlatCAMCNCjob)
  7080. and not isinstance(obj, FlatCAMExcellon)):
  7081. msg = '[ERROR_NOTCL] %s' % \
  7082. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7083. msgbox = QtWidgets.QMessageBox()
  7084. msgbox.setInformativeText(msg)
  7085. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7086. msgbox.setDefaultButton(bt_ok)
  7087. msgbox.exec_()
  7088. return
  7089. name = obj.options["name"]
  7090. _filter = "SVG File (*.svg);;All Files (*.*)"
  7091. try:
  7092. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7093. caption=_("Export SVG"),
  7094. directory=self.get_last_save_folder() + '/' + str(name),
  7095. filter=_filter)
  7096. except TypeError:
  7097. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7098. filename = str(filename)
  7099. if filename == "":
  7100. self.inform.emit('[WARNING_NOTCL]%s' %
  7101. _(" Export SVG cancelled."))
  7102. return
  7103. else:
  7104. self.export_svg(name, filename)
  7105. if self.defaults["global_open_style"] is False:
  7106. self.file_opened.emit("SVG", filename)
  7107. self.file_saved.emit("SVG", filename)
  7108. def on_file_exportpng(self):
  7109. self.report_usage("on_file_exportpng")
  7110. App.log.debug("on_file_exportpng()")
  7111. self.date = str(datetime.today()).rpartition('.')[0]
  7112. self.date = ''.join(c for c in self.date if c not in ':-')
  7113. self.date = self.date.replace(' ', '_')
  7114. image = _screenshot()
  7115. data = np.asarray(image)
  7116. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7117. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7118. _('Data must be a 3D array with last dimension 3 or 4'))
  7119. return
  7120. filter_ = "PNG File (*.png);;All Files (*.*)"
  7121. try:
  7122. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7123. caption=_("Export PNG Image"),
  7124. directory=self.get_last_save_folder() + '/png_' + self.date,
  7125. filter=filter_)
  7126. except TypeError:
  7127. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7128. filename = str(filename)
  7129. if filename == "":
  7130. self.inform.emit(_("Export PNG cancelled."))
  7131. return
  7132. else:
  7133. write_png(filename, data)
  7134. if self.defaults["global_open_style"] is False:
  7135. self.file_opened.emit("png", filename)
  7136. self.file_saved.emit("png", filename)
  7137. def on_file_savegerber(self):
  7138. """
  7139. Callback for menu item in Project context menu.
  7140. :return: None
  7141. """
  7142. self.report_usage("on_file_savegerber")
  7143. App.log.debug("on_file_savegerber()")
  7144. obj = self.collection.get_active()
  7145. if obj is None:
  7146. self.inform.emit('[WARNING_NOTCL] %s' %
  7147. _("No object selected. Please select an Gerber object to export."))
  7148. return
  7149. # Check for more compatible types and add as required
  7150. if not isinstance(obj, FlatCAMGerber):
  7151. self.inform.emit('[ERROR_NOTCL] %s' %
  7152. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7153. return
  7154. name = self.collection.get_active().options["name"]
  7155. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7156. try:
  7157. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7158. caption="Save Gerber source file",
  7159. directory=self.get_last_save_folder() + '/' + name,
  7160. filter=_filter)
  7161. except TypeError:
  7162. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7163. filename = str(filename)
  7164. if filename == "":
  7165. self.inform.emit('[WARNING_NOTCL] %s' %
  7166. _("Save Gerber source file cancelled."))
  7167. return
  7168. else:
  7169. self.save_source_file(name, filename)
  7170. if self.defaults["global_open_style"] is False:
  7171. self.file_opened.emit("Gerber", filename)
  7172. self.file_saved.emit("Gerber", filename)
  7173. def on_file_saveexcellon(self):
  7174. """
  7175. Callback for menu item in project context menu.
  7176. :return: None
  7177. """
  7178. self.report_usage("on_file_saveexcellon")
  7179. App.log.debug("on_file_saveexcellon()")
  7180. obj = self.collection.get_active()
  7181. if obj is None:
  7182. self.inform.emit('[WARNING_NOTCL] %s' %
  7183. _("No object selected. Please select an Excellon object to export."))
  7184. return
  7185. # Check for more compatible types and add as required
  7186. if not isinstance(obj, FlatCAMExcellon):
  7187. self.inform.emit('[ERROR_NOTCL] %s' %
  7188. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7189. return
  7190. name = self.collection.get_active().options["name"]
  7191. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7192. try:
  7193. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7194. caption=_("Save Excellon source file"),
  7195. directory=self.get_last_save_folder() + '/' + name,
  7196. filter=_filter)
  7197. except TypeError:
  7198. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7199. filename = str(filename)
  7200. if filename == "":
  7201. self.inform.emit('[WARNING_NOTCL] %s' %
  7202. _("Saving Excellon source file cancelled."))
  7203. return
  7204. else:
  7205. self.save_source_file(name, filename)
  7206. if self.defaults["global_open_style"] is False:
  7207. self.file_opened.emit("Excellon", filename)
  7208. self.file_saved.emit("Excellon", filename)
  7209. def on_file_exportexcellon(self):
  7210. """
  7211. Callback for menu item File->Export->Excellon.
  7212. :return: None
  7213. """
  7214. self.report_usage("on_file_exportexcellon")
  7215. App.log.debug("on_file_exportexcellon()")
  7216. obj = self.collection.get_active()
  7217. if obj is None:
  7218. self.inform.emit('[WARNING_NOTCL] %s' %
  7219. _("No object selected. Please Select an Excellon object to export."))
  7220. return
  7221. # Check for more compatible types and add as required
  7222. if not isinstance(obj, FlatCAMExcellon):
  7223. self.inform.emit('[ERROR_NOTCL] %s' %
  7224. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7225. return
  7226. name = self.collection.get_active().options["name"]
  7227. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7228. try:
  7229. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7230. caption=_("Export Excellon"),
  7231. directory=self.get_last_save_folder() + '/' + name,
  7232. filter=_filter)
  7233. except TypeError:
  7234. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7235. filename = str(filename)
  7236. if filename == "":
  7237. self.inform.emit('[WARNING_NOTCL] %s' %
  7238. _("Export Excellon cancelled."))
  7239. return
  7240. else:
  7241. self.export_excellon(name, filename)
  7242. if self.defaults["global_open_style"] is False:
  7243. self.file_opened.emit("Excellon", filename)
  7244. self.file_saved.emit("Excellon", filename)
  7245. def on_file_exportgerber(self):
  7246. """
  7247. Callback for menu item File->Export->Gerber.
  7248. :return: None
  7249. """
  7250. self.report_usage("on_file_exportgerber")
  7251. App.log.debug("on_file_exportgerber()")
  7252. obj = self.collection.get_active()
  7253. if obj is None:
  7254. self.inform.emit('[WARNING_NOTCL] %s' %
  7255. _("No object selected. Please Select an Gerber object to export."))
  7256. return
  7257. # Check for more compatible types and add as required
  7258. if not isinstance(obj, FlatCAMGerber):
  7259. self.inform.emit('[ERROR_NOTCL] %s' %
  7260. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7261. return
  7262. name = self.collection.get_active().options["name"]
  7263. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7264. try:
  7265. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7266. caption=_("Export Gerber"),
  7267. directory=self.get_last_save_folder() + '/' + name,
  7268. filter=_filter_)
  7269. except TypeError:
  7270. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7271. filename = str(filename)
  7272. if filename == "":
  7273. self.inform.emit('[WARNING_NOTCL] %s' %
  7274. _("Export Gerber cancelled."))
  7275. return
  7276. else:
  7277. self.export_gerber(name, filename)
  7278. if self.defaults["global_open_style"] is False:
  7279. self.file_opened.emit("Gerber", filename)
  7280. self.file_saved.emit("Gerber", filename)
  7281. def on_file_exportdxf(self):
  7282. """
  7283. Callback for menu item File->Export DXF.
  7284. :return: None
  7285. """
  7286. self.report_usage("on_file_exportdxf")
  7287. App.log.debug("on_file_exportdxf()")
  7288. obj = self.collection.get_active()
  7289. if obj is None:
  7290. self.inform.emit('[WARNING_NOTCL] %s' %
  7291. _("No object selected."))
  7292. msg = _("Please Select a Geometry object to export")
  7293. msgbox = QtWidgets.QMessageBox()
  7294. msgbox.setInformativeText(msg)
  7295. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7296. msgbox.setDefaultButton(bt_ok)
  7297. msgbox.exec_()
  7298. return
  7299. # Check for more compatible types and add as required
  7300. if not isinstance(obj, FlatCAMGeometry):
  7301. msg = '[ERROR_NOTCL] %s' % \
  7302. _("Only Geometry objects can be used.")
  7303. msgbox = QtWidgets.QMessageBox()
  7304. msgbox.setInformativeText(msg)
  7305. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7306. msgbox.setDefaultButton(bt_ok)
  7307. msgbox.exec_()
  7308. return
  7309. name = self.collection.get_active().options["name"]
  7310. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7311. try:
  7312. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7313. caption=_("Export DXF"),
  7314. directory=self.get_last_save_folder() + '/' + name,
  7315. filter=_filter_)
  7316. except TypeError:
  7317. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7318. filter=_filter_)
  7319. filename = str(filename)
  7320. if filename == "":
  7321. self.inform.emit('[WARNING_NOTCL] %s' %
  7322. _("Export DXF cancelled."))
  7323. return
  7324. else:
  7325. self.export_dxf(name, filename)
  7326. if self.defaults["global_open_style"] is False:
  7327. self.file_opened.emit("DXF", filename)
  7328. self.file_saved.emit("DXF", filename)
  7329. def on_file_importsvg(self, type_of_obj):
  7330. """
  7331. Callback for menu item File->Import SVG.
  7332. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7333. :type type_of_obj: str
  7334. :return: None
  7335. """
  7336. self.report_usage("on_file_importsvg")
  7337. App.log.debug("on_file_importsvg()")
  7338. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7339. try:
  7340. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7341. directory=self.get_last_folder(), filter=_filter_)
  7342. except TypeError:
  7343. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7344. filter=_filter_)
  7345. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7346. type_of_obj = "geometry"
  7347. filenames = [str(filename) for filename in filenames]
  7348. if len(filenames) == 0:
  7349. self.inform.emit('[WARNING_NOTCL] %s' %
  7350. _("Open SVG cancelled."))
  7351. else:
  7352. for filename in filenames:
  7353. if filename != '':
  7354. self.worker_task.emit({'fcn': self.import_svg,
  7355. 'params': [filename, type_of_obj]})
  7356. def on_file_importdxf(self, type_of_obj):
  7357. """
  7358. Callback for menu item File->Import DXF.
  7359. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7360. :type type_of_obj: str
  7361. :return: None
  7362. """
  7363. self.report_usage("on_file_importdxf")
  7364. App.log.debug("on_file_importdxf()")
  7365. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7366. try:
  7367. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7368. directory=self.get_last_folder(),
  7369. filter=_filter_)
  7370. except TypeError:
  7371. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7372. filter=_filter_)
  7373. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7374. type_of_obj = "geometry"
  7375. filenames = [str(filename) for filename in filenames]
  7376. if len(filenames) == 0:
  7377. self.inform.emit('[WARNING_NOTCL] %s' %
  7378. _("Open DXF cancelled."))
  7379. else:
  7380. for filename in filenames:
  7381. if filename != '':
  7382. self.worker_task.emit({'fcn': self.import_dxf,
  7383. 'params': [filename, type_of_obj]})
  7384. # ###############################################################################################################
  7385. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7386. # ###############################################################################################################
  7387. def init_code_editor(self, name):
  7388. # Signals section
  7389. # Disconnect the old signals
  7390. try:
  7391. self.ui.buttonOpen.clicked.disconnect()
  7392. except TypeError:
  7393. pass
  7394. try:
  7395. self.ui.buttonSave.clicked.disconnect()
  7396. except TypeError:
  7397. pass
  7398. # add the tab if it was closed
  7399. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7400. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7401. # delete the absolute and relative position and messages in the infobar
  7402. self.ui.position_label.setText("")
  7403. self.ui.rel_position_label.setText("")
  7404. # first clear previous text in text editor (if any)
  7405. self.ui.code_editor.clear()
  7406. self.ui.code_editor.setReadOnly(False)
  7407. self.toggle_codeeditor = True
  7408. self.ui.code_editor.completer_enable = False
  7409. self.ui.buttonRun.hide()
  7410. # make sure to keep a reference to the code editor
  7411. self.reference_code_editor = self.ui.code_editor
  7412. # Switch plot_area to CNCJob tab
  7413. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7414. def on_view_source(self):
  7415. self.inform.emit('%s' %
  7416. _("Viewing the source code of the selected object."))
  7417. self.proc_container.view.set_busy(_("Loading..."))
  7418. try:
  7419. obj = self.collection.get_active()
  7420. except Exception as e:
  7421. log.debug("App.on_view_source() --> %s" % str(e))
  7422. self.inform.emit('[WARNING_NOTCL] %s' %
  7423. _("Select an Gerber or Excellon file to view it's source file."))
  7424. return 'fail'
  7425. if obj.kind == 'gerber':
  7426. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7427. elif obj.kind == 'excellon':
  7428. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7429. elif obj.kind == 'cncjob':
  7430. "GCode Files (*.NC);;All Files (*.*)"
  7431. else:
  7432. flt = "All Files (*.*)"
  7433. self.init_code_editor(name=_("Source Editor"))
  7434. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7435. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7436. # then append the text from GCode to the text editor
  7437. if obj.kind == 'cncjob':
  7438. try:
  7439. file = obj.export_gcode(
  7440. preamble=self.defaults["cncjob_prepend"],
  7441. postamble=self.defaults["cncjob_append"],
  7442. to_file=True)
  7443. if file == 'fail':
  7444. return 'fail'
  7445. except AttributeError:
  7446. self.inform.emit('[WARNING_NOTCL] %s' %
  7447. _("There is no selected object for which to see it's source file code."))
  7448. return 'fail'
  7449. else:
  7450. try:
  7451. file = StringIO(obj.source_file)
  7452. except AttributeError:
  7453. self.inform.emit('[WARNING_NOTCL] %s' %
  7454. _("There is no selected object for which to see it's source file code."))
  7455. return 'fail'
  7456. self.ui.cncjob_frame.hide()
  7457. try:
  7458. for line in file:
  7459. QtWidgets.QApplication.processEvents()
  7460. proc_line = str(line).strip('\n')
  7461. self.ui.code_editor.append(proc_line)
  7462. except Exception as e:
  7463. log.debug('App.on_view_source() -->%s' % str(e))
  7464. self.inform.emit('[ERROR] %s: %s' %
  7465. (_('Failed to load the source code for the selected object'), str(e)))
  7466. return
  7467. self.handleTextChanged()
  7468. self.ui.cncjob_frame.show()
  7469. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7470. self.proc_container.view.set_idle()
  7471. # self.ui.show()
  7472. def on_toggle_code_editor(self):
  7473. self.report_usage("on_toggle_code_editor()")
  7474. if self.toggle_codeeditor is False:
  7475. self.init_code_editor(name=_("Code Editor"))
  7476. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7477. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7478. else:
  7479. for idx in range(self.ui.plot_tab_area.count()):
  7480. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7481. self.ui.plot_tab_area.closeTab(idx)
  7482. break
  7483. self.toggle_codeeditor = False
  7484. def on_filenewscript(self, silent=False):
  7485. """
  7486. Will create a new script file and open it in the Code Editor
  7487. :param silent: if True will not display status messages
  7488. :return: None
  7489. """
  7490. if silent is False:
  7491. self.inform.emit('[success] %s' %
  7492. _("New TCL script file created in Code Editor."))
  7493. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7494. self.init_code_editor(name=_("Script Editor"))
  7495. self.ui.code_editor.completer_enable = True
  7496. self.ui.code_editor.append(_(
  7497. "#\n"
  7498. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7499. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7500. "#\n\n"
  7501. "# FlatCAM commands list:\n"
  7502. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7503. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7504. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7505. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7506. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7507. "# SubtractRectangle, Version, WriteGCode\n"
  7508. "#\n\n"
  7509. ))
  7510. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7511. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7512. self.ui.buttonRun.show()
  7513. try:
  7514. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7515. except TypeError:
  7516. pass
  7517. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7518. self.handleTextChanged()
  7519. self.ui.code_editor.show()
  7520. def on_fileopenscript(self, name=None, silent=False):
  7521. """
  7522. Will open a Tcl script file into the Code Editor
  7523. :param silent: if True will not display status messages
  7524. :param name: name of a Tcl script file to open
  7525. :return:
  7526. """
  7527. if name:
  7528. filename = name
  7529. else:
  7530. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7531. try:
  7532. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7533. directory=self.get_last_folder(), filter=_filter_)
  7534. except TypeError:
  7535. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7536. # The Qt methods above will return a QString which can cause problems later.
  7537. # So far json.dump() will fail to serialize it.
  7538. # TODO: Improve the serialization methods and remove this fix.
  7539. filename = str(filename)
  7540. if filename == "":
  7541. if silent is False:
  7542. self.inform.emit('[WARNING_NOTCL] %s' %
  7543. _("Open TCL script cancelled."))
  7544. else:
  7545. self.on_filenewscript()
  7546. try:
  7547. with open(filename, "r") as opened_script:
  7548. try:
  7549. for line in opened_script:
  7550. proc_line = str(line).strip('\n')
  7551. self.ui.code_editor.append(proc_line)
  7552. except Exception as e:
  7553. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7554. if silent is False:
  7555. self.inform.emit('[ERROR] %s %s' %
  7556. (_('App.on_fileopenscript() -->'), str(e)))
  7557. return
  7558. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7559. self.handleTextChanged()
  7560. if silent is False:
  7561. self.inform.emit('[success] %s' %
  7562. _("TCL script file opened in Code Editor."))
  7563. # self.ui.show()
  7564. except Exception as e:
  7565. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7566. def on_filerunscript(self, name=None, silent=False):
  7567. """
  7568. File menu callback for loading and running a TCL script.
  7569. :param silent: if True will not display status messages
  7570. :param name: name of a Tcl script file to be run by FlatCAM
  7571. :return: None
  7572. """
  7573. self.report_usage("on_filerunscript")
  7574. App.log.debug("on_file_runscript()")
  7575. if name:
  7576. filename = name
  7577. if self.cmd_line_headless != 1:
  7578. self.splash.showMessage('%s: %ssec\n%s' %
  7579. (_("Canvas initialization started.\n"
  7580. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7581. _("Executing FlatCAMScript file.")
  7582. ),
  7583. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7584. color=QtGui.QColor("gray"))
  7585. else:
  7586. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7587. try:
  7588. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7589. directory=self.get_last_folder(), filter=_filter_)
  7590. except TypeError:
  7591. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7592. # The Qt methods above will return a QString which can cause problems later.
  7593. # So far json.dump() will fail to serialize it.
  7594. # TODO: Improve the serialization methods and remove this fix.
  7595. filename = str(filename)
  7596. if filename == "":
  7597. if silent is False:
  7598. self.inform.emit('[WARNING_NOTCL] %s' %
  7599. _("Run TCL script cancelled."))
  7600. else:
  7601. if self.cmd_line_headless != 1:
  7602. if self.ui.shell_dock.isHidden():
  7603. self.ui.shell_dock.show()
  7604. try:
  7605. with open(filename, "r") as tcl_script:
  7606. cmd_line_shellfile_content = tcl_script.read()
  7607. if self.cmd_line_headless != 1:
  7608. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7609. else:
  7610. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7611. if silent is False:
  7612. self.inform.emit('[success] %s' %
  7613. _("TCL script file opened in Code Editor and executed."))
  7614. except Exception as e:
  7615. log.debug("App.on_filerunscript() -> %s" % str(e))
  7616. sys.exit(2)
  7617. def on_file_saveproject(self, silent=False):
  7618. """
  7619. Callback for menu item File->Save Project. Saves the project to
  7620. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7621. if set to None. The project is saved by calling ``self.save_project()``.
  7622. :param silent: if True will not display status messages
  7623. :return: None
  7624. """
  7625. self.report_usage("on_file_saveproject")
  7626. if self.project_filename is None:
  7627. self.on_file_saveprojectas()
  7628. else:
  7629. self.worker_task.emit({'fcn': self.save_project,
  7630. 'params': [self.project_filename, silent]})
  7631. if self.defaults["global_open_style"] is False:
  7632. self.file_opened.emit("project", self.project_filename)
  7633. self.file_saved.emit("project", self.project_filename)
  7634. self.set_ui_title(name=self.project_filename)
  7635. self.should_we_save = False
  7636. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7637. """
  7638. Callback for menu item File->Save Project As... Opens a file
  7639. chooser and saves the project to the given file via
  7640. ``self.save_project()``.
  7641. :param make_copy if to be create a copy of the project; boolean
  7642. :param use_thread: if to be run in a separate thread; boolean
  7643. :param quit_action: if to be followed by quiting the application; boolean
  7644. :return: None
  7645. """
  7646. self.report_usage("on_file_saveprojectas")
  7647. self.date = str(datetime.today()).rpartition('.')[0]
  7648. self.date = ''.join(c for c in self.date if c not in ':-')
  7649. self.date = self.date.replace(' ', '_')
  7650. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7651. try:
  7652. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7653. caption=_("Save Project As ..."),
  7654. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7655. filter=filter_)
  7656. except TypeError:
  7657. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7658. filename = str(filename)
  7659. if filename == '':
  7660. self.inform.emit('[WARNING_NOTCL] %s' %
  7661. _("Save Project cancelled."))
  7662. return
  7663. try:
  7664. f = open(filename, 'r')
  7665. f.close()
  7666. except IOError:
  7667. pass
  7668. if use_thread is True:
  7669. self.worker_task.emit({'fcn': self.save_project,
  7670. 'params': [filename, quit_action]})
  7671. else:
  7672. self.save_project(filename, quit_action)
  7673. # self.save_project(filename)
  7674. if self.defaults["global_open_style"] is False:
  7675. self.file_opened.emit("project", filename)
  7676. self.file_saved.emit("project", filename)
  7677. if not make_copy:
  7678. self.project_filename = filename
  7679. self.set_ui_title(name=self.project_filename)
  7680. self.should_we_save = False
  7681. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7682. """
  7683. Exports a Geometry Object to an SVG file.
  7684. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7685. :param filename: Path to the SVG file to save to.
  7686. :param scale_factor: factor by which to change/scale the thickness of the features
  7687. :return:
  7688. """
  7689. self.report_usage("export_svg()")
  7690. if filename is None:
  7691. filename = self.defaults["global_last_save_folder"]
  7692. self.log.debug("export_svg()")
  7693. try:
  7694. obj = self.collection.get_by_name(str(obj_name))
  7695. except:
  7696. # TODO: The return behavior has not been established... should raise exception?
  7697. return "Could not retrieve object: %s" % obj_name
  7698. with self.proc_container.new(_("Exporting SVG")) as proc:
  7699. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7700. # Determine bounding area for svg export
  7701. bounds = obj.bounds()
  7702. size = obj.size()
  7703. # Convert everything to strings for use in the xml doc
  7704. svgwidth = str(size[0])
  7705. svgheight = str(size[1])
  7706. minx = str(bounds[0])
  7707. miny = str(bounds[1] - size[1])
  7708. uom = obj.units.lower()
  7709. # Add a SVG Header and footer to the svg output from shapely
  7710. # The transform flips the Y Axis so that everything renders
  7711. # properly within svg apps such as inkscape
  7712. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7713. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7714. svg_header += 'width="' + svgwidth + uom + '" '
  7715. svg_header += 'height="' + svgheight + uom + '" '
  7716. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7717. svg_header += '<g transform="scale(1,-1)">'
  7718. svg_footer = '</g> </svg>'
  7719. svg_elem = svg_header + exported_svg + svg_footer
  7720. # Parse the xml through a xml parser just to add line feeds
  7721. # and to make it look more pretty for the output
  7722. svgcode = parse_xml_string(svg_elem)
  7723. try:
  7724. with open(filename, 'w') as fp:
  7725. fp.write(svgcode.toprettyxml())
  7726. except PermissionError:
  7727. self.inform.emit('[WARNING] %s' %
  7728. _("Permission denied, saving not possible.\n"
  7729. "Most likely another app is holding the file open and not accessible."))
  7730. return 'fail'
  7731. if self.defaults["global_open_style"] is False:
  7732. self.file_opened.emit("SVG", filename)
  7733. self.file_saved.emit("SVG", filename)
  7734. self.inform.emit('[success] %s: %s' %
  7735. (_("SVG file exported to"), filename))
  7736. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7737. """
  7738. Exports a Geometry Object to an SVG file in negative.
  7739. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7740. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7741. :param filename: Path to the SVG file to save to.
  7742. :param boundary: thickness of a black border to surround all the features
  7743. :param scale_factor: factor by which to change/scale the thickness of the features
  7744. :param use_thread: if to be run in a separate thread; boolean
  7745. :return:
  7746. """
  7747. self.report_usage("export_negative()")
  7748. if filename is None:
  7749. filename = self.defaults["global_last_save_folder"]
  7750. self.log.debug("export_svg() negative")
  7751. try:
  7752. obj = self.collection.get_by_name(str(obj_name))
  7753. except:
  7754. # TODO: The return behavior has not been established... should raise exception?
  7755. return "Could not retrieve object: %s" % obj_name
  7756. try:
  7757. box = self.collection.get_by_name(str(box_name))
  7758. except:
  7759. # TODO: The return behavior has not been established... should raise exception?
  7760. return "Could not retrieve object: %s" % box_name
  7761. if box is None:
  7762. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7763. (_("No object Box. Using instead"), obj))
  7764. box = obj
  7765. def make_negative_film():
  7766. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7767. # Determine bounding area for svg export
  7768. bounds = box.bounds()
  7769. size = box.size()
  7770. uom = obj.units.lower()
  7771. # Convert everything to strings for use in the xml doc
  7772. svgwidth = str(size[0] + (2 * boundary))
  7773. svgheight = str(size[1] + (2 * boundary))
  7774. minx = str(bounds[0] - boundary)
  7775. miny = str(bounds[1] + boundary + size[1])
  7776. miny_rect = str(bounds[1] - boundary)
  7777. # Add a SVG Header and footer to the svg output from shapely
  7778. # The transform flips the Y Axis so that everything renders
  7779. # properly within svg apps such as inkscape
  7780. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7781. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7782. svg_header += 'width="' + svgwidth + uom + '" '
  7783. svg_header += 'height="' + svgheight + uom + '" '
  7784. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7785. svg_header += '>'
  7786. svg_header += '<g transform="scale(1,-1)">'
  7787. svg_footer = '</g> </svg>'
  7788. # Change the attributes of the exported SVG
  7789. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7790. # We set opacity to maximum
  7791. # We set the color to WHITE
  7792. root = ET.fromstring(exported_svg)
  7793. for child in root:
  7794. child.set('fill', '#FFFFFF')
  7795. child.set('opacity', '1.0')
  7796. child.set('stroke', '#FFFFFF')
  7797. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7798. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7799. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7800. first_svg_elem_tag = 'rect'
  7801. first_svg_elem_attribs = {
  7802. 'x': minx,
  7803. 'y': miny_rect,
  7804. 'width': svgwidth,
  7805. 'height': svgheight,
  7806. 'id': 'neg_rect',
  7807. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7808. }
  7809. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7810. exported_svg = ET.tostring(root)
  7811. svg_elem = svg_header + str(exported_svg) + svg_footer
  7812. # Parse the xml through a xml parser just to add line feeds
  7813. # and to make it look more pretty for the output
  7814. doc = parse_xml_string(svg_elem)
  7815. try:
  7816. with open(filename, 'w') as fp:
  7817. fp.write(doc.toprettyxml())
  7818. except PermissionError:
  7819. self.inform.emit('[WARNING] %s' %
  7820. _("Permission denied, saving not possible.\n"
  7821. "Most likely another app is holding the file open and not accessible."))
  7822. return 'fail'
  7823. if self.defaults["global_open_style"] is False:
  7824. self.file_opened.emit("SVG", filename)
  7825. self.file_saved.emit("SVG", filename)
  7826. self.inform.emit('[success] %s: %s' %
  7827. (_("SVG file exported to"), filename))
  7828. if use_thread is True:
  7829. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7830. def job_thread_film(app_obj):
  7831. try:
  7832. make_negative_film()
  7833. except Exception as e:
  7834. proc.done()
  7835. return
  7836. proc.done()
  7837. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7838. else:
  7839. make_negative_film()
  7840. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7841. """
  7842. Exports a Geometry Object to an SVG file in positive black.
  7843. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7844. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7845. :param filename: Path to the SVG file to save to.
  7846. :param scale_factor: factor by which to change/scale the thickness of the features
  7847. :param use_thread: if to be run in a separate thread; boolean
  7848. :return:
  7849. """
  7850. self.report_usage("export_svg_positive()")
  7851. if filename is None:
  7852. filename = self.defaults["global_last_save_folder"]
  7853. self.log.debug("export_svg() black")
  7854. try:
  7855. obj = self.collection.get_by_name(str(obj_name))
  7856. except:
  7857. # TODO: The return behavior has not been established... should raise exception?
  7858. return "Could not retrieve object: %s" % obj_name
  7859. try:
  7860. box = self.collection.get_by_name(str(box_name))
  7861. except:
  7862. # TODO: The return behavior has not been established... should raise exception?
  7863. return "Could not retrieve object: %s" % box_name
  7864. if box is None:
  7865. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7866. (_("No object Box. Using instead"), obj))
  7867. box = obj
  7868. def make_positive_film():
  7869. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7870. self.progress.emit(40)
  7871. # Change the attributes of the exported SVG
  7872. # We don't need stroke-width
  7873. # We set opacity to maximum
  7874. # We set the colour to WHITE
  7875. root = ET.fromstring(exported_svg)
  7876. for child in root:
  7877. child.set('fill', str(self.defaults['tools_film_color']))
  7878. child.set('opacity', '1.0')
  7879. child.set('stroke', str(self.defaults['tools_film_color']))
  7880. exported_svg = ET.tostring(root)
  7881. # Determine bounding area for svg export
  7882. bounds = box.bounds()
  7883. size = box.size()
  7884. # This contain the measure units
  7885. uom = obj.units.lower()
  7886. # Define a boundary around SVG of about 1.0mm (~39mils)
  7887. if uom in "mm":
  7888. boundary = 1.0
  7889. else:
  7890. boundary = 0.0393701
  7891. self.progress.emit(80)
  7892. # Convert everything to strings for use in the xml doc
  7893. svgwidth = str(size[0] + (2 * boundary))
  7894. svgheight = str(size[1] + (2 * boundary))
  7895. minx = str(bounds[0] - boundary)
  7896. miny = str(bounds[1] + boundary + size[1])
  7897. self.log.debug(minx)
  7898. self.log.debug(miny)
  7899. # Add a SVG Header and footer to the svg output from shapely
  7900. # The transform flips the Y Axis so that everything renders
  7901. # properly within svg apps such as inkscape
  7902. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7903. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7904. svg_header += 'width="' + svgwidth + uom + '" '
  7905. svg_header += 'height="' + svgheight + uom + '" '
  7906. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7907. svg_header += '>'
  7908. svg_header += '<g transform="scale(1,-1)">'
  7909. svg_footer = '</g> </svg>'
  7910. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7911. self.progress.emit(90)
  7912. # Parse the xml through a xml parser just to add line feeds
  7913. # and to make it look more pretty for the output
  7914. doc = parse_xml_string(svg_elem)
  7915. try:
  7916. with open(filename, 'w') as fp:
  7917. fp.write(doc.toprettyxml())
  7918. except PermissionError:
  7919. self.inform.emit('[WARNING] %s' %
  7920. _("Permission denied, saving not possible.\n"
  7921. "Most likely another app is holding the file open and not accessible."))
  7922. return 'fail'
  7923. self.progress.emit(100)
  7924. if self.defaults["global_open_style"] is False:
  7925. self.file_opened.emit("SVG", filename)
  7926. self.file_saved.emit("SVG", filename)
  7927. self.inform.emit('[success] %s: %s' %
  7928. (_("SVG file exported to"), filename))
  7929. if use_thread is True:
  7930. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7931. def job_thread_film(app_obj):
  7932. try:
  7933. make_positive_film()
  7934. except Exception as e:
  7935. proc.done()
  7936. return
  7937. proc.done()
  7938. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7939. else:
  7940. make_positive_film()
  7941. def save_source_file(self, obj_name, filename, use_thread=True):
  7942. """
  7943. Exports a FlatCAM Object to an Gerber/Excellon file.
  7944. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7945. :param filename: Path to the Gerber file to save to.
  7946. :param use_thread: if to be run in a separate thread
  7947. :return:
  7948. """
  7949. self.report_usage("save source file()")
  7950. if filename is None:
  7951. filename = self.defaults["global_last_save_folder"]
  7952. self.log.debug("save source file()")
  7953. obj = self.collection.get_by_name(obj_name)
  7954. file_string = StringIO(obj.source_file)
  7955. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7956. try:
  7957. with open(filename, 'w') as file:
  7958. file.writelines('G04*\n')
  7959. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7960. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7961. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7962. file.writelines('G04 Created on : %s*\n' % time_string)
  7963. for line in file_string:
  7964. file.writelines(line)
  7965. except PermissionError:
  7966. self.inform.emit('[WARNING] %s' %
  7967. _("Permission denied, saving not possible.\n"
  7968. "Most likely another app is holding the file open and not accessible."))
  7969. return 'fail'
  7970. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7971. """
  7972. Exports a Excellon Object to an Excellon file.
  7973. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7974. :param filename: Path to the Excellon file to save to.
  7975. :param use_thread: if to be run in a separate thread
  7976. :return:
  7977. """
  7978. self.report_usage("export_excellon()")
  7979. if filename is None:
  7980. filename = self.defaults["global_last_save_folder"]
  7981. self.log.debug("export_excellon()")
  7982. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7983. self.defaults["excellon_exp_decimals"]
  7984. )
  7985. units = ''
  7986. if local_use is None:
  7987. try:
  7988. obj = self.collection.get_by_name(str(obj_name))
  7989. except:
  7990. # TODO: The return behavior has not been established... should raise exception?
  7991. return "Could not retrieve object: %s" % obj_name
  7992. else:
  7993. obj = local_use
  7994. # updated units
  7995. eunits = self.defaults["excellon_exp_units"]
  7996. ewhole = self.defaults["excellon_exp_integer"]
  7997. efract = self.defaults["excellon_exp_decimals"]
  7998. ezeros = self.defaults["excellon_exp_zeros"]
  7999. eformat = self.defaults["excellon_exp_format"]
  8000. slot_type = self.defaults["excellon_exp_slot_type"]
  8001. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8002. if fc_units == 'MM':
  8003. factor = 1 if eunits == 'METRIC' else 0.03937
  8004. else:
  8005. factor = 25.4 if eunits == 'METRIC' else 1
  8006. def make_excellon():
  8007. try:
  8008. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8009. header = 'M48\n'
  8010. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8011. (str(self.version), str(self.version_date))
  8012. header += ';Filename: %s' % str(obj_name) + '\n'
  8013. header += ';Created on : %s' % time_str + '\n'
  8014. if eformat == 'dec':
  8015. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8016. header += eunits + '\n'
  8017. for tool in obj.tools:
  8018. if eunits == 'METRIC':
  8019. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8020. tool=str(tool),
  8021. dec=2)
  8022. else:
  8023. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8024. tool=str(tool),
  8025. dec=4)
  8026. else:
  8027. if ezeros == 'LZ':
  8028. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8029. form='ndec', e_zeros='LZ', factor=factor,
  8030. slot_type=slot_type)
  8031. header += '%s,%s\n' % (eunits, 'LZ')
  8032. header += format_exc
  8033. for tool in obj.tools:
  8034. if eunits == 'METRIC':
  8035. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8036. tool=str(tool),
  8037. dec=2)
  8038. else:
  8039. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8040. tool=str(tool),
  8041. dec=4)
  8042. else:
  8043. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8044. form='ndec', e_zeros='TZ', factor=factor,
  8045. slot_type=slot_type)
  8046. header += '%s,%s\n' % (eunits, 'TZ')
  8047. header += format_exc
  8048. for tool in obj.tools:
  8049. if eunits == 'METRIC':
  8050. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8051. tool=str(tool),
  8052. dec=2)
  8053. else:
  8054. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8055. tool=str(tool),
  8056. dec=4)
  8057. header += '%\n'
  8058. footer = 'M30\n'
  8059. exported_excellon = header
  8060. exported_excellon += excellon_code
  8061. exported_excellon += footer
  8062. if local_use is None:
  8063. try:
  8064. with open(filename, 'w') as fp:
  8065. fp.write(exported_excellon)
  8066. except PermissionError:
  8067. self.inform.emit('[WARNING] %s' %
  8068. _("Permission denied, saving not possible.\n"
  8069. "Most likely another app is holding the file open and not accessible."))
  8070. return 'fail'
  8071. if self.defaults["global_open_style"] is False:
  8072. self.file_opened.emit("Excellon", filename)
  8073. self.file_saved.emit("Excellon", filename)
  8074. self.inform.emit('[success] %s: %s' %
  8075. (_("Excellon file exported to"), filename))
  8076. else:
  8077. return exported_excellon
  8078. except Exception as e:
  8079. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8080. return 'fail'
  8081. if use_thread is True:
  8082. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8083. def job_thread_exc(app_obj):
  8084. ret = make_excellon()
  8085. if ret == 'fail':
  8086. self.inform.emit('[ERROR_NOTCL] %s' %
  8087. _('Could not export Excellon file.'))
  8088. return
  8089. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8090. else:
  8091. ret = make_excellon()
  8092. if ret == 'fail':
  8093. self.inform.emit('[ERROR_NOTCL] %s' %
  8094. _('Could not export Excellon file.'))
  8095. return 'fail'
  8096. if local_use is not None:
  8097. return ret
  8098. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8099. """
  8100. Exports a Gerber Object to an Gerber file.
  8101. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8102. :param filename: Path to the Gerber file to save to.
  8103. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8104. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8105. :param use_thread: if to be run in a separate thread
  8106. :return:
  8107. """
  8108. self.report_usage("export_gerber()")
  8109. if filename is None:
  8110. filename = self.defaults["global_last_save_folder"]
  8111. self.log.debug("export_gerber()")
  8112. if local_use is None:
  8113. try:
  8114. obj = self.collection.get_by_name(str(obj_name))
  8115. except:
  8116. # TODO: The return behavior has not been established... should raise exception?
  8117. return "Could not retrieve object: %s" % obj_name
  8118. else:
  8119. obj = local_use
  8120. # updated units
  8121. gunits = self.defaults["gerber_exp_units"]
  8122. gwhole = self.defaults["gerber_exp_integer"]
  8123. gfract = self.defaults["gerber_exp_decimals"]
  8124. gzeros = self.defaults["gerber_exp_zeros"]
  8125. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8126. if fc_units == 'MM':
  8127. factor = 1 if gunits == 'MM' else 0.03937
  8128. else:
  8129. factor = 25.4 if gunits == 'MM' else 1
  8130. def make_gerber():
  8131. try:
  8132. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8133. header = 'G04*\n'
  8134. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8135. (str(self.version), str(self.version_date))
  8136. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8137. header += 'G04 Created on : %s*' % time_str + '\n'
  8138. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8139. header += "%MO{units}*%\n".format(units=gunits)
  8140. for apid in obj.apertures:
  8141. if obj.apertures[apid]['type'] == 'C':
  8142. header += "%ADD{apid}{type},{size}*%\n".format(
  8143. apid=str(apid),
  8144. type='C',
  8145. size=(factor * obj.apertures[apid]['size'])
  8146. )
  8147. elif obj.apertures[apid]['type'] == 'R':
  8148. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8149. apid=str(apid),
  8150. type='R',
  8151. width=(factor * obj.apertures[apid]['width']),
  8152. height=(factor * obj.apertures[apid]['height'])
  8153. )
  8154. elif obj.apertures[apid]['type'] == 'O':
  8155. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8156. apid=str(apid),
  8157. type='O',
  8158. width=(factor * obj.apertures[apid]['width']),
  8159. height=(factor * obj.apertures[apid]['height'])
  8160. )
  8161. header += '\n'
  8162. # obsolete units but some software may need it
  8163. if gunits == 'IN':
  8164. header += 'G70*\n'
  8165. else:
  8166. header += 'G71*\n'
  8167. # Absolute Mode
  8168. header += 'G90*\n'
  8169. header += 'G01*\n'
  8170. # positive polarity
  8171. header += '%LPD*%\n'
  8172. footer = 'M02*\n'
  8173. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8174. exported_gerber = header
  8175. exported_gerber += gerber_code
  8176. exported_gerber += footer
  8177. if local_use is None:
  8178. try:
  8179. with open(filename, 'w') as fp:
  8180. fp.write(exported_gerber)
  8181. except PermissionError:
  8182. self.inform.emit('[WARNING] %s' %
  8183. _("Permission denied, saving not possible.\n"
  8184. "Most likely another app is holding the file open and not accessible."))
  8185. return 'fail'
  8186. if self.defaults["global_open_style"] is False:
  8187. self.file_opened.emit("Gerber", filename)
  8188. self.file_saved.emit("Gerber", filename)
  8189. self.inform.emit('[success] %s: %s' %
  8190. (_("Gerber file exported to"), filename))
  8191. else:
  8192. return exported_gerber
  8193. except Exception as e:
  8194. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8195. return 'fail'
  8196. if use_thread is True:
  8197. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8198. def job_thread_grb(app_obj):
  8199. ret = make_gerber()
  8200. if ret == 'fail':
  8201. self.inform.emit('[ERROR_NOTCL] %s' %
  8202. _('Could not export Gerber file.'))
  8203. return
  8204. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8205. else:
  8206. ret = make_gerber()
  8207. if ret == 'fail':
  8208. self.inform.emit('[ERROR_NOTCL] %s' %
  8209. _('Could not export Gerber file.'))
  8210. return 'fail'
  8211. if local_use is not None:
  8212. return ret
  8213. def export_dxf(self, obj_name, filename, use_thread=True):
  8214. """
  8215. Exports a Geometry Object to an DXF file.
  8216. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8217. :param filename: Path to the DXF file to save to.
  8218. :param use_thread: if to be run in a separate thread
  8219. :return:
  8220. """
  8221. self.report_usage("export_dxf()")
  8222. if filename is None:
  8223. filename = self.defaults["global_last_save_folder"]
  8224. self.log.debug("export_dxf()")
  8225. format_exc = ''
  8226. units = ''
  8227. try:
  8228. obj = self.collection.get_by_name(str(obj_name))
  8229. except:
  8230. # TODO: The return behavior has not been established... should raise exception?
  8231. return "Could not retrieve object: %s" % obj_name
  8232. # updated units
  8233. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8234. if units == 'IN' or units == 'INCH':
  8235. units = 'INCH'
  8236. elif units == 'MM' or units == 'METIRC':
  8237. units ='METRIC'
  8238. def make_dxf():
  8239. try:
  8240. dxf_code = obj.export_dxf()
  8241. dxf_code.saveas(filename)
  8242. if self.defaults["global_open_style"] is False:
  8243. self.file_opened.emit("DXF", filename)
  8244. self.file_saved.emit("DXF", filename)
  8245. self.inform.emit('[success] %s: %s' %
  8246. (_("DXF file exported to"), filename))
  8247. except:
  8248. return 'fail'
  8249. if use_thread is True:
  8250. with self.proc_container.new(_("Exporting DXF")) as proc:
  8251. def job_thread_exc(app_obj):
  8252. ret = make_dxf()
  8253. if ret == 'fail':
  8254. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8255. _('Could not export DXF file.'))
  8256. return
  8257. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8258. else:
  8259. ret = make_dxf()
  8260. if ret == 'fail':
  8261. self.inform.emit('[WARNING_NOTCL] %s' %
  8262. _('Could not export DXF file.'))
  8263. return
  8264. def import_svg(self, filename, geo_type='geometry', outname=None):
  8265. """
  8266. Adds a new Geometry Object to the projects and populates
  8267. it with shapes extracted from the SVG file.
  8268. :param filename: Path to the SVG file.
  8269. :param outname:
  8270. :return:
  8271. """
  8272. self.report_usage("import_svg()")
  8273. obj_type = ""
  8274. if geo_type is None or geo_type == "geometry":
  8275. obj_type = "geometry"
  8276. elif geo_type == "gerber":
  8277. obj_type = geo_type
  8278. else:
  8279. self.inform.emit('[ERROR_NOTCL] %s' %
  8280. _("Not supported type is picked as parameter. "
  8281. "Only Geometry and Gerber are supported"))
  8282. return
  8283. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8284. def obj_init(geo_obj, app_obj):
  8285. geo_obj.import_svg(filename, obj_type, units=units)
  8286. geo_obj.multigeo = False
  8287. with self.proc_container.new(_("Importing SVG")) as proc:
  8288. # Object name
  8289. name = outname or filename.split('/')[-1].split('\\')[-1]
  8290. self.new_object(obj_type, name, obj_init, autoselected=False)
  8291. self.progress.emit(20)
  8292. # Register recent file
  8293. self.file_opened.emit("svg", filename)
  8294. # GUI feedback
  8295. self.inform.emit('[success] %s: %s' %
  8296. (_("Opened"), filename))
  8297. self.progress.emit(100)
  8298. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8299. """
  8300. Adds a new Geometry Object to the projects and populates
  8301. it with shapes extracted from the DXF file.
  8302. :param filename: Path to the DXF file.
  8303. :param outname:
  8304. :type putname: str
  8305. :return:
  8306. """
  8307. self.report_usage("import_dxf()")
  8308. obj_type = ""
  8309. if geo_type is None or geo_type == "geometry":
  8310. obj_type = "geometry"
  8311. elif geo_type == "gerber":
  8312. obj_type = geo_type
  8313. else:
  8314. self.inform.emit('[ERROR_NOTCL] %s' %
  8315. _("Not supported type is picked as parameter. "
  8316. "Only Geometry and Gerber are supported"))
  8317. return
  8318. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8319. def obj_init(geo_obj, app_obj):
  8320. geo_obj.import_dxf(filename, obj_type, units=units)
  8321. geo_obj.multigeo = False
  8322. with self.proc_container.new(_("Importing DXF")) as proc:
  8323. # Object name
  8324. name = outname or filename.split('/')[-1].split('\\')[-1]
  8325. self.new_object(obj_type, name, obj_init, autoselected=False)
  8326. self.progress.emit(20)
  8327. # Register recent file
  8328. self.file_opened.emit("dxf", filename)
  8329. # GUI feedback
  8330. self.inform.emit('[success] %s: %s' %
  8331. (_("Opened"), filename))
  8332. self.progress.emit(100)
  8333. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8334. """
  8335. Adds a new Geometry Object to the projects and populates
  8336. it with shapes extracted from the SVG file.
  8337. :param filename: Path to the SVG file.
  8338. :param o_type: type of FlatCAM objeect
  8339. :param dpi: dot per inch
  8340. :param mode: black or color
  8341. :param mask: dictate the level of detail
  8342. :param outname: name for the resulting file
  8343. :return:
  8344. """
  8345. self.report_usage("import_image()")
  8346. if o_type is None or o_type == "geometry":
  8347. obj_type = "geometry"
  8348. elif o_type == "gerber":
  8349. obj_type = o_type
  8350. else:
  8351. self.inform.emit('[ERROR_NOTCL] %s' %
  8352. _("Not supported type is picked as parameter. "
  8353. "Only Geometry and Gerber are supported"))
  8354. return
  8355. def obj_init(geo_obj, app_obj):
  8356. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8357. geo_obj.multigeo = False
  8358. with self.proc_container.new(_("Importing Image")) as proc:
  8359. # Object name
  8360. name = outname or filename.split('/')[-1].split('\\')[-1]
  8361. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8362. self.new_object(obj_type, name, obj_init)
  8363. self.progress.emit(20)
  8364. # Register recent file
  8365. self.file_opened.emit("image", filename)
  8366. # GUI feedback
  8367. self.inform.emit('[success] %s: %s' %
  8368. (_("Opened"), filename))
  8369. self.progress.emit(100)
  8370. def open_gerber(self, filename, outname=None):
  8371. """
  8372. Opens a Gerber file, parses it and creates a new object for
  8373. it in the program. Thread-safe.
  8374. :param outname: Name of the resulting object. None causes the
  8375. name to be that of the file.
  8376. :param filename: Gerber file filename
  8377. :type filename: str
  8378. :param follow: If true, the parser will not create polygons, just lines
  8379. following the gerber path.
  8380. :type follow: bool
  8381. :return: None
  8382. """
  8383. # How the object should be initialized
  8384. def obj_init(gerber_obj, app_obj):
  8385. assert isinstance(gerber_obj, FlatCAMGerber), \
  8386. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8387. # Opening the file happens here
  8388. self.progress.emit(30)
  8389. try:
  8390. gerber_obj.parse_file(filename)
  8391. except IOError:
  8392. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8393. (_("Failed to open file"), filename))
  8394. app_obj.progress.emit(0)
  8395. return "fail"
  8396. except ParseError as err:
  8397. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8398. (_("Failed to parse file"), filename, str(err)))
  8399. app_obj.progress.emit(0)
  8400. self.log.error(str(err))
  8401. return "fail"
  8402. except Exception as e:
  8403. log.debug("App.open_gerber() --> %s" % str(e))
  8404. msg = '[ERROR] %s' % \
  8405. _("An internal error has occurred. See shell.\n")
  8406. msg += traceback.format_exc()
  8407. app_obj.inform.emit(msg)
  8408. return "fail"
  8409. if gerber_obj.is_empty():
  8410. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8411. # self.collection.set_active(gerber_obj.options["name"])
  8412. # self.collection.delete_active()
  8413. self.inform.emit('[ERROR_NOTCL] %s' %
  8414. _("Object is not Gerber file or empty. Aborting object creation."))
  8415. return "fail"
  8416. # Further parsing
  8417. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8418. App.log.debug("open_gerber()")
  8419. with self.proc_container.new(_("Opening Gerber")) as proc:
  8420. self.progress.emit(10)
  8421. # Object name
  8422. name = outname or filename.split('/')[-1].split('\\')[-1]
  8423. # # ## Object creation # ##
  8424. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8425. if ret == 'fail':
  8426. self.inform.emit('[ERROR_NOTCL]%s' %
  8427. _(' Open Gerber failed. Probable not a Gerber file.'))
  8428. return
  8429. # Register recent file
  8430. self.file_opened.emit("gerber", filename)
  8431. self.progress.emit(100)
  8432. # GUI feedback
  8433. self.inform.emit('[success] %s: %s' %
  8434. (_("Opened"), filename))
  8435. def open_excellon(self, filename, outname=None, plot=True):
  8436. """
  8437. Opens an Excellon file, parses it and creates a new object for
  8438. it in the program. Thread-safe.
  8439. :param outname: Name of the resulting object. None causes the
  8440. name to be that of the file.
  8441. :param filename: Excellon file filename
  8442. :type filename: str
  8443. :return: None
  8444. """
  8445. App.log.debug("open_excellon()")
  8446. # How the object should be initialized
  8447. def obj_init(excellon_obj, app_obj):
  8448. # self.progress.emit(20)
  8449. try:
  8450. ret = excellon_obj.parse_file(filename=filename)
  8451. if ret == "fail":
  8452. log.debug("Excellon parsing failed.")
  8453. self.inform.emit('[ERROR_NOTCL] %s' %
  8454. _("This is not Excellon file."))
  8455. return "fail"
  8456. except IOError:
  8457. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8458. (_("Cannot open file"), filename))
  8459. log.debug("Could not open Excellon object.")
  8460. self.progress.emit(0) # TODO: self and app_bjj mixed
  8461. return "fail"
  8462. except:
  8463. msg = '[ERROR_NOTCL] %s' % \
  8464. _("An internal error has occurred. See shell.\n")
  8465. msg += traceback.format_exc()
  8466. app_obj.inform.emit(msg)
  8467. return "fail"
  8468. ret = excellon_obj.create_geometry()
  8469. if ret == 'fail':
  8470. log.debug("Could not create geometry for Excellon object.")
  8471. return "fail"
  8472. for tool in excellon_obj.tools:
  8473. if excellon_obj.tools[tool]['solid_geometry']:
  8474. return
  8475. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8476. (_("No geometry found in file"), filename))
  8477. return "fail"
  8478. with self.proc_container.new(_("Opening Excellon.")):
  8479. # Object name
  8480. name = outname or filename.split('/')[-1].split('\\')[-1]
  8481. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8482. if ret_val == 'fail':
  8483. self.inform.emit('[ERROR_NOTCL] %s' %
  8484. _('Open Excellon file failed. Probable not an Excellon file.'))
  8485. return
  8486. # Register recent file
  8487. self.file_opened.emit("excellon", filename)
  8488. # GUI feedback
  8489. self.inform.emit('[success] %s: %s' %
  8490. (_("Opened"), filename))
  8491. def open_gcode(self, filename, outname=None, plot=True):
  8492. """
  8493. Opens a G-gcode file, parses it and creates a new object for
  8494. it in the program. Thread-safe.
  8495. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8496. :param filename: G-code file filename
  8497. :type filename: str
  8498. :return: None
  8499. """
  8500. App.log.debug("open_gcode()")
  8501. # How the object should be initialized
  8502. def obj_init(job_obj, app_obj_):
  8503. """
  8504. :param job_obj: the resulting object
  8505. :type app_obj_: App
  8506. """
  8507. assert isinstance(app_obj_, App), \
  8508. "Initializer expected App, got %s" % type(app_obj_)
  8509. self.progress.emit(10)
  8510. try:
  8511. f = open(filename)
  8512. gcode = f.read()
  8513. f.close()
  8514. except IOError:
  8515. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8516. (_("Failed to open"), filename))
  8517. self.progress.emit(0)
  8518. return "fail"
  8519. job_obj.gcode = gcode
  8520. self.progress.emit(20)
  8521. ret = job_obj.gcode_parse()
  8522. if ret == "fail":
  8523. self.inform.emit('[ERROR_NOTCL] %s' %
  8524. _("This is not GCODE"))
  8525. return "fail"
  8526. self.progress.emit(60)
  8527. job_obj.create_geometry()
  8528. with self.proc_container.new(_("Opening G-Code.")):
  8529. # Object name
  8530. name = outname or filename.split('/')[-1].split('\\')[-1]
  8531. # New object creation and file processing
  8532. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8533. if ret == 'fail':
  8534. self.inform.emit('[ERROR_NOTCL] %s' %
  8535. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8536. "Attempting to create a FlatCAM CNCJob Object from "
  8537. "G-Code file failed during processing"))
  8538. return "fail"
  8539. # Register recent file
  8540. self.file_opened.emit("cncjob", filename)
  8541. # GUI feedback
  8542. self.inform.emit('[success] %s: %s' %
  8543. (_("Opened"), filename))
  8544. self.progress.emit(100)
  8545. def open_config_file(self, filename, run_from_arg=None):
  8546. """
  8547. Loads a config file from the specified file.
  8548. :param filename: Name of the file from which to load.
  8549. :type filename: str
  8550. :return: None
  8551. """
  8552. App.log.debug("Opening config file: " + filename)
  8553. if run_from_arg:
  8554. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8555. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8556. _("Opening FlatCAM Config file.")),
  8557. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8558. color=QtGui.QColor("gray"))
  8559. # add the tab if it was closed
  8560. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8561. # first clear previous text in text editor (if any)
  8562. self.ui.code_editor.clear()
  8563. # Switch plot_area to CNCJob tab
  8564. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8565. try:
  8566. if filename:
  8567. f = QtCore.QFile(filename)
  8568. if f.open(QtCore.QIODevice.ReadOnly):
  8569. stream = QtCore.QTextStream(f)
  8570. gcode_edited = stream.readAll()
  8571. self.ui.code_editor.setPlainText(gcode_edited)
  8572. f.close()
  8573. except IOError:
  8574. App.log.error("Failed to open config file: %s" % filename)
  8575. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8576. (_("Failed to open config file"), filename))
  8577. return
  8578. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8579. """
  8580. Loads a project from the specified file.
  8581. 1) Loads and parses file
  8582. 2) Registers the file as recently opened.
  8583. 3) Calls on_file_new()
  8584. 4) Updates options
  8585. 5) Calls new_object() with the object's from_dict() as init method.
  8586. 6) Calls plot_all() if plot=True
  8587. :param filename: Name of the file from which to load.
  8588. :type filename: str
  8589. :param run_from_arg: True if run for arguments
  8590. :param plot: If True plot all objects in the project
  8591. :param cli: run from command line
  8592. :return: None
  8593. """
  8594. App.log.debug("Opening project: " + filename)
  8595. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8596. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8597. if cli is None:
  8598. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8599. if run_from_arg:
  8600. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8601. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8602. _("Opening FlatCAM Project file.")),
  8603. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8604. color=QtGui.QColor("gray"))
  8605. # Open and parse an uncompressed Project file
  8606. try:
  8607. f = open(filename, 'r')
  8608. except IOError:
  8609. App.log.error("Failed to open project file: %s" % filename)
  8610. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8611. (_("Failed to open project file"), filename))
  8612. return
  8613. try:
  8614. d = json.load(f, object_hook=dict2obj)
  8615. except Exception as e:
  8616. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8617. (filename, str(e)))
  8618. f.close()
  8619. # Open and parse a compressed Project file
  8620. try:
  8621. with lzma.open(filename) as f:
  8622. file_content = f.read().decode('utf-8')
  8623. d = json.loads(file_content, object_hook=dict2obj)
  8624. except Exception as e:
  8625. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8626. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8627. (_("Failed to open project file"), filename))
  8628. return
  8629. # Clear the current project
  8630. # # NOT THREAD SAFE # ##
  8631. if run_from_arg is True:
  8632. pass
  8633. elif cli is True:
  8634. self.delete_selection_shape()
  8635. else:
  8636. self.on_file_new()
  8637. # Project options
  8638. self.options.update(d['options'])
  8639. self.project_filename = filename
  8640. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8641. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8642. if cli is None:
  8643. self.set_screen_units(self.options["units"])
  8644. # Re create objects
  8645. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8646. for obj in d['objs']:
  8647. def obj_init(obj_inst, app_inst):
  8648. obj_inst.from_dict(obj)
  8649. App.log.debug("Recreating from opened project an %s object: %s" %
  8650. (obj['kind'].capitalize(), obj['options']['name']))
  8651. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8652. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8653. if cli is None:
  8654. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8655. obj['kind'].upper(),
  8656. obj['options']['name']
  8657. )
  8658. )
  8659. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8660. self.inform.emit('[success] %s: %s' %
  8661. (_("Project loaded from"), filename))
  8662. self.should_we_save = False
  8663. self.file_opened.emit("project", filename)
  8664. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8665. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8666. if cli is None:
  8667. self.set_ui_title(name=self.project_filename)
  8668. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8669. def propagate_defaults(self, silent=False):
  8670. """
  8671. This method is used to set default values in classes. It's
  8672. an alternative to project options but allows the use
  8673. of values invisible to the user.
  8674. :return: None
  8675. """
  8676. if silent is False:
  8677. self.log.debug("propagate_defaults()")
  8678. # Which objects to update the given parameters.
  8679. routes = {
  8680. "global_zdownrate": CNCjob,
  8681. "excellon_zeros": Excellon,
  8682. "excellon_format_upper_in": Excellon,
  8683. "excellon_format_lower_in": Excellon,
  8684. "excellon_format_upper_mm": Excellon,
  8685. "excellon_format_lower_mm": Excellon,
  8686. "excellon_units": Excellon,
  8687. "gerber_use_buffer_for_union": Gerber,
  8688. "geometry_multidepth": Geometry
  8689. }
  8690. for param in routes:
  8691. if param in routes[param].defaults:
  8692. try:
  8693. routes[param].defaults[param] = self.defaults[param]
  8694. if silent is False:
  8695. self.log.debug(" " + param + " OK")
  8696. except KeyError:
  8697. if silent is False:
  8698. self.log.debug(" ERROR: " + param + " not in defaults.")
  8699. else:
  8700. # Try extracting the name:
  8701. # classname_param here is param in the object
  8702. if param.find(routes[param].__name__.lower() + "_") == 0:
  8703. p = param[len(routes[param].__name__) + 1:]
  8704. if p in routes[param].defaults:
  8705. routes[param].defaults[p] = self.defaults[param]
  8706. if silent is False:
  8707. self.log.debug(" " + param + " OK!")
  8708. def restore_main_win_geom(self):
  8709. try:
  8710. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8711. self.defaults["global_def_win_y"],
  8712. self.defaults["global_def_win_w"],
  8713. self.defaults["global_def_win_h"])
  8714. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8715. except KeyError as e:
  8716. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8717. def plot_all(self, zoom=True):
  8718. """
  8719. Re-generates all plots from all objects.
  8720. :return: None
  8721. """
  8722. self.log.debug("Plot_all()")
  8723. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8724. for obj in self.collection.get_list():
  8725. def worker_task(obj):
  8726. with self.proc_container.new("Plotting"):
  8727. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8728. if zoom:
  8729. self.object_plotted.emit(obj)
  8730. # Send to worker
  8731. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8732. def register_folder(self, filename):
  8733. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8734. def register_save_folder(self, filename):
  8735. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8736. def set_progress_bar(self, percentage, text=""):
  8737. self.ui.progress_bar.setValue(int(percentage))
  8738. def setup_shell(self):
  8739. """
  8740. Creates shell functions. Runs once at startup.
  8741. :return: None
  8742. """
  8743. self.log.debug("setup_shell()")
  8744. def shelp(p=None):
  8745. if not p:
  8746. return _("Available commands:\n") + \
  8747. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8748. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8749. if p not in commands:
  8750. return "Unknown command: %s" % p
  8751. return commands[p]["help"]
  8752. # --- Migrated to new architecture ---
  8753. # def options(name):
  8754. # ops = self.collection.get_by_name(str(name)).options
  8755. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8756. def h(*args):
  8757. """
  8758. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8759. and standalone parameters into list.
  8760. """
  8761. kwa = {}
  8762. a = []
  8763. n = len(args)
  8764. name = None
  8765. for i in range(n):
  8766. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8767. if match:
  8768. assert name is None
  8769. name = match.group(1)
  8770. continue
  8771. if name is None:
  8772. a.append(args[i])
  8773. else:
  8774. kwa[name] = args[i]
  8775. name = None
  8776. return a, kwa
  8777. @contextmanager
  8778. def wait_signal(signal, timeout=10000):
  8779. """
  8780. Block loop until signal emitted, timeout (ms) elapses
  8781. or unhandled exception happens in a thread.
  8782. :param timeout: time after which the loop is exited
  8783. :param signal: Signal to wait for.
  8784. """
  8785. loop = QtCore.QEventLoop()
  8786. # Normal termination
  8787. signal.connect(loop.quit)
  8788. # Termination by exception in thread
  8789. self.thread_exception.connect(loop.quit)
  8790. status = {'timed_out': False}
  8791. def report_quit():
  8792. status['timed_out'] = True
  8793. loop.quit()
  8794. yield
  8795. # Temporarily change how exceptions are managed.
  8796. oeh = sys.excepthook
  8797. ex = []
  8798. def except_hook(type_, value, traceback_):
  8799. ex.append(value)
  8800. oeh(type_, value, traceback_)
  8801. sys.excepthook = except_hook
  8802. # Terminate on timeout
  8803. if timeout is not None:
  8804. QtCore.QTimer.singleShot(timeout, report_quit)
  8805. # # ## Block ## ##
  8806. loop.exec_()
  8807. # Restore exception management
  8808. sys.excepthook = oeh
  8809. if ex:
  8810. self.raiseTclError(str(ex[0]))
  8811. if status['timed_out']:
  8812. raise Exception('Timed out!')
  8813. def make_docs():
  8814. output = ''
  8815. import collections
  8816. od = collections.OrderedDict(sorted(commands.items()))
  8817. for cmd_, val in od.items():
  8818. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8819. t = val['help']
  8820. usage_i = t.find('>')
  8821. if usage_i < 0:
  8822. expl = t
  8823. output += expl + '\n\n'
  8824. continue
  8825. expl = t[:usage_i - 1]
  8826. output += expl + '\n\n'
  8827. end_usage_i = t[usage_i:].find('\n')
  8828. if end_usage_i < 0:
  8829. end_usage_i = len(t[usage_i:])
  8830. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8831. else:
  8832. extras = t[usage_i+end_usage_i+1:]
  8833. parts = [s.strip() for s in extras.split('\n')]
  8834. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8835. for p in parts:
  8836. output += ' ' + p + '\n\n'
  8837. return output
  8838. '''
  8839. Howto implement TCL shell commands:
  8840. All parameters passed to command should be possible to set as None and test it afterwards.
  8841. This is because we need to see error caused in tcl,
  8842. if None value as default parameter is not allowed TCL will return empty error.
  8843. Use:
  8844. def mycommand(name=None,...):
  8845. Test it like this:
  8846. if name is None:
  8847. self.raise_tcl_error('Argument name is missing.')
  8848. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8849. otherwise we will miss it and processing will silently continue.
  8850. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8851. which is catched in exec_command and displayed in TCL shell console with red background.
  8852. Error in console is displayed with TCL trace.
  8853. This behavior works only within main thread,
  8854. errors with promissed tasks can be catched and detected only with log.
  8855. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8856. TCL shell.
  8857. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8858. '''
  8859. commands = {
  8860. 'help': {
  8861. 'fcn': shelp,
  8862. 'help': _("Shows list of commands.")
  8863. },
  8864. }
  8865. # Import/overwrite tcl commands as objects of TclCommand descendants
  8866. # This modifies the variable 'commands'.
  8867. tclCommands.register_all_commands(self, commands)
  8868. # Add commands to the tcl interpreter
  8869. for cmd in commands:
  8870. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8871. # Make the tcl puts function return instead of print to stdout
  8872. self.tcl.eval('''
  8873. rename puts original_puts
  8874. proc puts {args} {
  8875. if {[llength $args] == 1} {
  8876. return "[lindex $args 0]"
  8877. } else {
  8878. eval original_puts $args
  8879. }
  8880. }
  8881. ''')
  8882. def setup_recent_items(self):
  8883. # TODO: Move this to constructor
  8884. icons = {
  8885. "gerber": "share/flatcam_icon16.png",
  8886. "excellon": "share/drill16.png",
  8887. 'geometry': "share/geometry16.png",
  8888. "cncjob": "share/cnc16.png",
  8889. "project": "share/project16.png",
  8890. "svg": "share/geometry16.png",
  8891. "dxf": "share/dxf16.png",
  8892. "pdf": "share/pdf32.png",
  8893. "image": "share/image16.png"
  8894. }
  8895. openers = {
  8896. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8897. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8898. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8899. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8900. 'project': self.open_project,
  8901. 'svg': self.import_svg,
  8902. 'dxf': self.import_dxf,
  8903. 'image': self.import_image,
  8904. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8905. }
  8906. # Open recent file for files
  8907. try:
  8908. f = open(self.data_path + '/recent.json')
  8909. except IOError:
  8910. App.log.error("Failed to load recent item list.")
  8911. self.inform.emit('[ERROR_NOTCL] %s' %
  8912. _("Failed to load recent item list."))
  8913. return
  8914. try:
  8915. self.recent = json.load(f)
  8916. except json.scanner.JSONDecodeError:
  8917. App.log.error("Failed to parse recent item list.")
  8918. self.inform.emit('[ERROR_NOTCL] %s' %
  8919. _("Failed to parse recent item list."))
  8920. f.close()
  8921. return
  8922. f.close()
  8923. # Open recent file for projects
  8924. try:
  8925. fp = open(self.data_path + '/recent_projects.json')
  8926. except IOError:
  8927. App.log.error("Failed to load recent project item list.")
  8928. self.inform.emit('[ERROR_NOTCL] %s' %
  8929. _("Failed to load recent projects item list."))
  8930. return
  8931. try:
  8932. self.recent_projects = json.load(fp)
  8933. except json.scanner.JSONDecodeError:
  8934. App.log.error("Failed to parse recent project item list.")
  8935. self.inform.emit('[ERROR_NOTCL] %s' %
  8936. _("Failed to parse recent project item list."))
  8937. fp.close()
  8938. return
  8939. fp.close()
  8940. # Closure needed to create callbacks in a loop.
  8941. # Otherwise late binding occurs.
  8942. def make_callback(func, fname):
  8943. def opener():
  8944. func(fname)
  8945. return opener
  8946. def reset_recent_files():
  8947. # Reset menu
  8948. self.ui.recent.clear()
  8949. self.recent = []
  8950. try:
  8951. f = open(self.data_path + '/recent.json', 'w')
  8952. except IOError:
  8953. App.log.error("Failed to open recent items file for writing.")
  8954. return
  8955. json.dump(self.recent, f)
  8956. def reset_recent_projects():
  8957. # Reset menu
  8958. self.ui.recent_projects.clear()
  8959. self.recent_projects = []
  8960. try:
  8961. fp = open(self.data_path + '/recent_projects.json', 'w')
  8962. except IOError:
  8963. App.log.error("Failed to open recent projects items file for writing.")
  8964. return
  8965. json.dump(self.recent, fp)
  8966. # Reset menu
  8967. self.ui.recent.clear()
  8968. self.ui.recent_projects.clear()
  8969. # Create menu items for projects
  8970. for recent in self.recent_projects:
  8971. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8972. if recent['kind'] == 'project':
  8973. try:
  8974. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8975. # Attach callback
  8976. o = make_callback(openers[recent["kind"]], recent['filename'])
  8977. action.triggered.connect(o)
  8978. self.ui.recent_projects.addAction(action)
  8979. except KeyError:
  8980. App.log.error("Unsupported file type: %s" % recent["kind"])
  8981. # Last action in Recent Files menu is one that Clear the content
  8982. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8983. clear_action_proj.triggered.connect(reset_recent_projects)
  8984. self.ui.recent_projects.addSeparator()
  8985. self.ui.recent_projects.addAction(clear_action_proj)
  8986. # Create menu items for files
  8987. for recent in self.recent:
  8988. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8989. if recent['kind'] != 'project':
  8990. try:
  8991. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8992. # Attach callback
  8993. o = make_callback(openers[recent["kind"]], recent['filename'])
  8994. action.triggered.connect(o)
  8995. self.ui.recent.addAction(action)
  8996. except KeyError:
  8997. App.log.error("Unsupported file type: %s" % recent["kind"])
  8998. # Last action in Recent Files menu is one that Clear the content
  8999. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9000. clear_action.triggered.connect(reset_recent_files)
  9001. self.ui.recent.addSeparator()
  9002. self.ui.recent.addAction(clear_action)
  9003. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9004. # self.ui.menufilerecent.set_submenu(recent_menu)
  9005. # recent_menu.show_all()
  9006. # self.ui.recent.show()
  9007. self.log.debug("Recent items list has been populated.")
  9008. def setup_component_editor(self):
  9009. # label = QtWidgets.QLabel("Choose an item from Project")
  9010. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9011. sel_title = QtWidgets.QTextEdit(
  9012. _('<b>Shortcut Key List</b>'))
  9013. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9014. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9015. settings = QSettings("Open Source", "FlatCAM")
  9016. if settings.contains("notebook_font_size"):
  9017. fsize = settings.value('notebook_font_size', type=int)
  9018. else:
  9019. fsize = 12
  9020. tsize = fsize + int(fsize / 2)
  9021. # selected_text = (_('''
  9022. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9023. #
  9024. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9025. # The normal flow when working in FlatCAM is the following:</span></p>
  9026. #
  9027. # <ol>
  9028. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9029. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9030. # even dragging and dropping the files on the GUI.<br />
  9031. # <br />
  9032. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9033. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9034. # &nbsp;</li>
  9035. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9036. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9037. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9038. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9039. # <br />
  9040. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9041. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9042. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9043. # it even if it was out of focus.<br />
  9044. # <br />
  9045. # You can change the parameters in this screen and the flow direction is like this:<br />
  9046. # <br />
  9047. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9048. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9049. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9050. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9051. # </ol>
  9052. #
  9053. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9054. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9055. # <strong>F3</strong>.</span></p>
  9056. #
  9057. # ''').format(fsize=fsize, tsize=tsize))
  9058. selected_text = '''
  9059. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  9060. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  9061. %s:</span></p>
  9062. <ol>
  9063. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  9064. <br />
  9065. %s &amp; %s.</span><br />
  9066. &nbsp;</li>
  9067. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  9068. <br />
  9069. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  9070. <br />
  9071. %s:<br />
  9072. <br />
  9073. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  9074. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  9075. </ol>
  9076. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  9077. <strong>F3</strong>.</span></p>
  9078. ''' % (
  9079. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  9080. _("The normal flow when working in FlatCAM is the following"),
  9081. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  9082. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  9083. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  9084. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  9085. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  9086. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  9087. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  9088. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  9089. _("If the selection of the object is done on the canvas by single click instead, and the"),
  9090. _("SELECTED TAB"),
  9091. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  9092. "double clicking on the object on the canvas will bring the"),
  9093. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  9094. _("You can change the parameters in this screen and the flow direction is like this"),
  9095. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  9096. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  9097. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  9098. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  9099. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  9100. )
  9101. sel_title.setText(selected_text)
  9102. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9103. self.ui.selected_scroll_area.setWidget(sel_title)
  9104. def setup_obj_classes(self):
  9105. """
  9106. Sets up application specifics on the FlatCAMObj class.
  9107. :return: None
  9108. """
  9109. FlatCAMObj.app = self
  9110. ObjectCollection.app = self
  9111. Gerber.app = self
  9112. Excellon.app = self
  9113. Geometry.app = self
  9114. CNCjob.app = self
  9115. FCProcess.app = self
  9116. FCProcessContainer.app = self
  9117. def version_check(self):
  9118. """
  9119. Checks for the latest version of the program. Alerts the
  9120. user if theirs is outdated. This method is meant to be run
  9121. in a separate thread.
  9122. :return: None
  9123. """
  9124. self.log.debug("version_check()")
  9125. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9126. full_url = App.version_url + \
  9127. "?s=" + str(self.defaults['global_serial']) + \
  9128. "&v=" + str(self.version) + \
  9129. "&os=" + str(self.os) + \
  9130. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9131. else:
  9132. # no_stats dict; just so it won't break things on website
  9133. no_ststs_dict = {}
  9134. no_ststs_dict["global_ststs"] = {}
  9135. full_url = App.version_url + \
  9136. "?s=" + str(self.defaults['global_serial']) + \
  9137. "&v=" + str(self.version) + \
  9138. "&os=" + str(self.os) + \
  9139. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9140. App.log.debug("Checking for updates @ %s" % full_url)
  9141. # ## Get the data
  9142. try:
  9143. f = urllib.request.urlopen(full_url)
  9144. except:
  9145. # App.log.warning("Failed checking for latest version. Could not connect.")
  9146. self.log.warning("Failed checking for latest version. Could not connect.")
  9147. self.inform.emit('[WARNING_NOTCL] %s' %
  9148. _("Failed checking for latest version. Could not connect."))
  9149. return
  9150. try:
  9151. data = json.load(f)
  9152. except Exception as e:
  9153. App.log.error("Could not parse information about latest version.")
  9154. self.inform.emit('[ERROR_NOTCL] %s' %
  9155. _("Could not parse information about latest version."))
  9156. App.log.debug("json.load(): %s" % str(e))
  9157. f.close()
  9158. return
  9159. f.close()
  9160. # ## Latest version?
  9161. if self.version >= data["version"]:
  9162. App.log.debug("FlatCAM is up to date!")
  9163. self.inform.emit('[success] %s' %
  9164. _("FlatCAM is up to date!"))
  9165. return
  9166. App.log.debug("Newer version available.")
  9167. self.message.emit(
  9168. _("Newer Version Available"),
  9169. _("There is a newer version of FlatCAM available for download:\n\n") +
  9170. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9171. _("info")
  9172. )
  9173. def on_plotcanvas_setup(self, container=None):
  9174. """
  9175. This is doing the setup for the plot area (VisPy canvas)
  9176. :param container: widget where to install the canvas
  9177. :return: None
  9178. """
  9179. if container:
  9180. plot_container = container
  9181. else:
  9182. plot_container = self.ui.right_layout
  9183. if self.is_legacy is False:
  9184. self.plotcanvas = PlotCanvas(plot_container, self)
  9185. else:
  9186. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9187. # So it can receive key presses
  9188. self.plotcanvas.native.setFocus()
  9189. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9190. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9191. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9192. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9193. # Keys over plot enabled
  9194. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9195. self.app_cursor = self.plotcanvas.new_cursor()
  9196. if self.ui.grid_snap_btn.isChecked():
  9197. self.app_cursor.enabled = True
  9198. else:
  9199. self.app_cursor.enabled = False
  9200. if self.is_legacy is False:
  9201. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9202. else:
  9203. # will use the default Matplotlib axes
  9204. self.hover_shapes = ShapeCollectionLegacy()
  9205. def on_zoom_fit(self, event):
  9206. """
  9207. Callback for zoom-out request. This can be either from the corresponding
  9208. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9209. with axes limits from the geometry bounds of all objects.
  9210. :param event: Ignored.
  9211. :return: None
  9212. """
  9213. if self.is_legacy is False:
  9214. self.plotcanvas.fit_view()
  9215. else:
  9216. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9217. width = xmax - xmin
  9218. height = ymax - ymin
  9219. xmin -= 0.05 * width
  9220. xmax += 0.05 * width
  9221. ymin -= 0.05 * height
  9222. ymax += 0.05 * height
  9223. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9224. def on_zoom_in(self):
  9225. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9226. def on_zoom_out(self):
  9227. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9228. def disable_all_plots(self):
  9229. self.report_usage("disable_all_plots()")
  9230. self.disable_plots(self.collection.get_list())
  9231. self.inform.emit('[success] %s' %
  9232. _("All plots disabled."))
  9233. def disable_other_plots(self):
  9234. self.report_usage("disable_other_plots()")
  9235. self.disable_plots(self.collection.get_non_selected())
  9236. self.inform.emit('[success] %s' %
  9237. _("All non selected plots disabled."))
  9238. def enable_all_plots(self):
  9239. self.report_usage("enable_all_plots()")
  9240. self.enable_plots(self.collection.get_list())
  9241. self.inform.emit('[success] %s' %
  9242. _("All plots enabled."))
  9243. def on_enable_sel_plots(self):
  9244. log.debug("App.on_enable_sel_plot()")
  9245. object_list = self.collection.get_selected()
  9246. self.enable_plots(objects=object_list)
  9247. self.inform.emit('[success] %s' %
  9248. _("Selected plots enabled..."))
  9249. def on_disable_sel_plots(self):
  9250. log.debug("App.on_disable_sel_plot()")
  9251. # self.inform.emit(_("Disabling plots ..."))
  9252. object_list = self.collection.get_selected()
  9253. self.disable_plots(objects=object_list)
  9254. self.inform.emit('[success] %s' %
  9255. _("Selected plots disabled..."))
  9256. def enable_plots(self, objects):
  9257. """
  9258. Disables plots
  9259. :param objects: list of Objects to be enabled
  9260. :return:
  9261. """
  9262. log.debug("Enabling plots ...")
  9263. # self.inform.emit(_("Working ..."))
  9264. for obj in objects:
  9265. if obj.options['plot'] is False:
  9266. obj.options.set_change_callback(lambda x: None)
  9267. obj.options['plot'] = True
  9268. obj.options.set_change_callback(obj.on_options_change)
  9269. def worker_task(objects):
  9270. with self.proc_container.new(_("Enabling plots ...")):
  9271. for obj in objects:
  9272. # obj.options['plot'] = True
  9273. if isinstance(obj, FlatCAMCNCjob):
  9274. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9275. else:
  9276. obj.plot(visible=True)
  9277. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9278. # self.plots_updated.emit()
  9279. def disable_plots(self, objects):
  9280. """
  9281. Disables plots
  9282. :param objects: list of Objects to be disabled
  9283. :return:
  9284. """
  9285. # if no objects selected then do nothing
  9286. if not self.collection.get_selected():
  9287. return
  9288. log.debug("Disabling plots ...")
  9289. # self.inform.emit(_("Working ..."))
  9290. for obj in objects:
  9291. if obj.options['plot'] is True:
  9292. obj.options.set_change_callback(lambda x: None)
  9293. obj.options['plot'] = False
  9294. obj.options.set_change_callback(obj.on_options_change)
  9295. try:
  9296. self.delete_selection_shape()
  9297. except Exception as e:
  9298. log.debug("App.disable_plots() --> %s" % str(e))
  9299. # self.plots_updated.emit()
  9300. def worker_task(objects):
  9301. with self.proc_container.new(_("Disabling plots ...")):
  9302. for obj in objects:
  9303. # obj.options['plot'] = True
  9304. if isinstance(obj, FlatCAMCNCjob):
  9305. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9306. else:
  9307. obj.plot(visible=False)
  9308. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9309. def toggle_plots(self, objects):
  9310. """
  9311. Toggle plots visibility
  9312. :param objects: list of Objects for which to be toggled the visibility
  9313. :return:
  9314. """
  9315. # if no objects selected then do nothing
  9316. if not self.collection.get_selected():
  9317. return
  9318. log.debug("Toggling plots ...")
  9319. self.inform.emit(_("Working ..."))
  9320. for obj in objects:
  9321. if obj.options['plot'] is False:
  9322. obj.options['plot'] = True
  9323. else:
  9324. obj.options['plot'] = False
  9325. self.plots_updated.emit()
  9326. def clear_plots(self):
  9327. objects = self.collection.get_list()
  9328. for obj in objects:
  9329. obj.clear(obj == objects[-1])
  9330. # Clear pool to free memory
  9331. self.clear_pool()
  9332. def generate_cnc_job(self, objects):
  9333. self.report_usage("generate_cnc_job()")
  9334. # for obj in objects:
  9335. # obj.generatecncjob()
  9336. for obj in objects:
  9337. obj.on_generatecnc_button_click()
  9338. def save_project(self, filename, quit_action=False, silent=False):
  9339. """
  9340. Saves the current project to the specified file.
  9341. :param filename: Name of the file in which to save.
  9342. :type filename: str
  9343. :param quit_action: if the project saving will be followed by an app quit; boolean
  9344. :param silent: if True will not display status messages
  9345. :return: None
  9346. """
  9347. self.log.debug("save_project()")
  9348. self.save_in_progress = True
  9349. with self.proc_container.new(_("Saving FlatCAM Project")):
  9350. # Capture the latest changes
  9351. # Current object
  9352. try:
  9353. self.collection.get_active().read_form()
  9354. except:
  9355. self.log.debug("There was no active object")
  9356. pass
  9357. # Project options
  9358. self.options_read_form()
  9359. # Serialize the whole project
  9360. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9361. "options": self.options,
  9362. "version": self.version}
  9363. if self.defaults["global_save_compressed"] is True:
  9364. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9365. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9366. # # Write
  9367. f.write(g)
  9368. self.inform.emit('[success] %s: %s' %
  9369. (_("Project saved to"), filename))
  9370. else:
  9371. # Open file
  9372. try:
  9373. f = open(filename, 'w')
  9374. except IOError:
  9375. App.log.error("Failed to open file for saving: %s", filename)
  9376. return
  9377. # Write
  9378. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9379. f.close()
  9380. # verification of the saved project
  9381. # Open and parse
  9382. try:
  9383. saved_f = open(filename, 'r')
  9384. except IOError:
  9385. if silent is False:
  9386. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9387. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9388. )
  9389. return
  9390. try:
  9391. saved_d = json.load(saved_f, object_hook=dict2obj)
  9392. except:
  9393. if silent is False:
  9394. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9395. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9396. )
  9397. f.close()
  9398. return
  9399. saved_f.close()
  9400. if silent is False:
  9401. if 'version' in saved_d:
  9402. self.inform.emit('[success] %s: %s' %
  9403. (_("Project saved to"), filename))
  9404. else:
  9405. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9406. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9407. )
  9408. settings = QSettings("Open Source", "FlatCAM")
  9409. lock_state = self.ui.lock_action.isChecked()
  9410. settings.setValue('toolbar_lock', lock_state)
  9411. # This will write the setting to the platform specific storage.
  9412. del settings
  9413. # if quit:
  9414. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9415. # t.start()
  9416. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9417. def start_delayed_quit(self, delay, filename, should_quit=None):
  9418. """
  9419. :param delay: period of checking if project file size is more than zero; in seconds
  9420. :param filename: the name of the project file to be checked periodically for size more than zero
  9421. :param should_quit: if the task finished will be followed by an app quit; boolean
  9422. :return:
  9423. """
  9424. to_quit = should_quit
  9425. self.save_timer = QtCore.QTimer()
  9426. self.save_timer.setInterval(delay)
  9427. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9428. self.save_timer.start()
  9429. def check_project_file_size(self, filename, should_quit=None):
  9430. """
  9431. :param filename: the name of the project file to be checked periodically for size more than zero
  9432. :param should_quit: will quit the app if True; boolean
  9433. :return:
  9434. """
  9435. try:
  9436. if os.stat(filename).st_size > 0:
  9437. self.save_in_progress = False
  9438. self.save_timer.stop()
  9439. if should_quit:
  9440. self.app_quit.emit()
  9441. except Exception as e:
  9442. traceback.print_exc()
  9443. def on_options_app2project(self):
  9444. """
  9445. Callback for Options->Transfer Options->App=>Project. Copies options
  9446. from application defaults to project defaults.
  9447. :return: None
  9448. """
  9449. self.report_usage("on_options_app2project")
  9450. self.defaults_read_form()
  9451. self.options.update(self.defaults)
  9452. self.options_write_form()
  9453. def on_options_project2app(self):
  9454. """
  9455. Callback for Options->Transfer Options->Project=>App. Copies options
  9456. from project defaults to application defaults.
  9457. :return: None
  9458. """
  9459. self.report_usage("on_options_project2app")
  9460. self.options_read_form()
  9461. self.defaults.update(self.options)
  9462. self.defaults_write_form()
  9463. def on_options_project2object(self):
  9464. """
  9465. Callback for Options->Transfer Options->Project=>Object. Copies options
  9466. from project defaults to the currently selected object.
  9467. :return: None
  9468. """
  9469. self.report_usage("on_options_project2object")
  9470. self.options_read_form()
  9471. obj = self.collection.get_active()
  9472. if obj is None:
  9473. self.inform.emit('[WARNING_NOTCL] %s' %
  9474. _("No object selected."))
  9475. return
  9476. for option in self.options:
  9477. if option.find(obj.kind + "_") == 0:
  9478. oname = option[len(obj.kind) + 1:]
  9479. obj.options[oname] = self.options[option]
  9480. obj.to_form() # Update UI
  9481. def on_options_object2project(self):
  9482. """
  9483. Callback for Options->Transfer Options->Object=>Project. Copies options
  9484. from the currently selected object to project defaults.
  9485. :return: None
  9486. """
  9487. self.report_usage("on_options_object2project")
  9488. obj = self.collection.get_active()
  9489. if obj is None:
  9490. self.inform.emit('[WARNING_NOTCL] %s' %
  9491. _("No object selected."))
  9492. return
  9493. obj.read_form()
  9494. for option in obj.options:
  9495. if option in ['name']: # TODO: Handle this better...
  9496. continue
  9497. self.options[obj.kind + "_" + option] = obj.options[option]
  9498. self.options_write_form()
  9499. def on_options_object2app(self):
  9500. """
  9501. Callback for Options->Transfer Options->Object=>App. Copies options
  9502. from the currently selected object to application defaults.
  9503. :return: None
  9504. """
  9505. self.report_usage("on_options_object2app")
  9506. obj = self.collection.get_active()
  9507. if obj is None:
  9508. self.inform.emit('[WARNING_NOTCL] %s' %
  9509. _("No object selected."))
  9510. return
  9511. obj.read_form()
  9512. for option in obj.options:
  9513. if option in ['name']: # TODO: Handle this better...
  9514. continue
  9515. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9516. self.defaults_write_form()
  9517. def on_options_app2object(self):
  9518. """
  9519. Callback for Options->Transfer Options->App=>Object. Copies options
  9520. from application defaults to the currently selected object.
  9521. :return: None
  9522. """
  9523. self.report_usage("on_options_app2object")
  9524. self.defaults_read_form()
  9525. obj = self.collection.get_active()
  9526. if obj is None:
  9527. self.inform.emit('[WARNING_NOTCL] %s' %
  9528. _("No object selected."))
  9529. return
  9530. for option in self.defaults:
  9531. if option.find(obj.kind + "_") == 0:
  9532. oname = option[len(obj.kind) + 1:]
  9533. obj.options[oname] = self.defaults[option]
  9534. obj.to_form() # Update UI
  9535. class ArgsThread(QtCore.QObject):
  9536. open_signal = pyqtSignal(list)
  9537. start = pyqtSignal()
  9538. if sys.platform == 'win32':
  9539. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9540. else:
  9541. address = ('/tmp/testipc', 'AF_UNIX')
  9542. def __init__(self):
  9543. super(ArgsThread, self).__init__()
  9544. self.start.connect(self.run)
  9545. def my_loop(self, address):
  9546. try:
  9547. listener = Listener(*address)
  9548. while True:
  9549. conn = listener.accept()
  9550. self.serve(conn)
  9551. except socket.error as e:
  9552. conn = Client(*address)
  9553. conn.send(sys.argv)
  9554. conn.send('close')
  9555. # close the current instance only if there are args
  9556. if len(sys.argv) > 1:
  9557. sys.exit()
  9558. def serve(self, conn):
  9559. while True:
  9560. msg = conn.recv()
  9561. if msg == 'close':
  9562. break
  9563. self.open_signal.emit(msg)
  9564. conn.close()
  9565. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9566. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9567. @pyqtSlot()
  9568. def run(self):
  9569. self.my_loop(self.address)
  9570. class GracefulException(Exception):
  9571. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9572. def __init__(self):
  9573. super().__init__()
  9574. def __str__(self):
  9575. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9576. # end of file