FlatCAMApp.py 546 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045
  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 webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. import stat
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import subprocess
  21. import ctypes
  22. import tkinter as tk
  23. from PyQt5 import QtPrintSupport
  24. from contextlib import contextmanager
  25. import gc
  26. from xml.dom.minidom import parseString as parse_xml_string
  27. from multiprocessing.connection import Listener, Client
  28. from multiprocessing import Pool, cpu_count
  29. import socket
  30. from array import array
  31. import vispy.scene as scene
  32. # #######################################
  33. # # Imports part of FlatCAM ##
  34. # #######################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from camlib import to_dict, dict2obj, ET, ParseError
  38. from flatcamGUI.PlotCanvas import *
  39. from flatcamGUI.PlotCanvasLegacy import *
  40. from flatcamGUI.FlatCAMGUI import *
  41. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB
  42. from FlatCAMPostProc import load_postprocessors
  43. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  44. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  45. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  46. from flatcamEditors.FlatCAMTextEditor import TextEditor
  47. from FlatCAMProcess import *
  48. from FlatCAMWorkerStack import WorkerStack
  49. # from flatcamGUI.VisPyVisuals import Color
  50. from vispy.gloo.util import _screenshot
  51. from vispy.io import write_png
  52. from flatcamTools import *
  53. import tclCommands
  54. import gettext
  55. import FlatCAMTranslation as fcTranslate
  56. import builtins
  57. if sys.platform == 'win32':
  58. import winreg
  59. fcTranslate.apply_language('strings')
  60. if '_' not in builtins.__dict__:
  61. _ = gettext.gettext
  62. class App(QtCore.QObject):
  63. # ########################################
  64. # # App ###
  65. # ########################################
  66. """
  67. The main application class. The constructor starts the GUI.
  68. """
  69. # Get Cmd Line Options
  70. cmd_line_shellfile = ''
  71. cmd_line_shellvar = ''
  72. cmd_line_headless = None
  73. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  74. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  75. "FlatCam.py --headless=1"
  76. try:
  77. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  78. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  79. "shellvar=",
  80. "headless=",
  81. "multiprocessing-fork="])
  82. except getopt.GetoptError:
  83. print(cmd_line_help)
  84. sys.exit(2)
  85. for opt, arg in cmd_line_options:
  86. if opt == '-h':
  87. print(cmd_line_help)
  88. sys.exit()
  89. elif opt == '--shellfile':
  90. cmd_line_shellfile = arg
  91. elif opt == '--shellvar':
  92. cmd_line_shellvar = arg
  93. elif opt == '--headless':
  94. try:
  95. cmd_line_headless = eval(arg)
  96. except NameError:
  97. pass
  98. # ## Logging ###
  99. log = logging.getLogger('base')
  100. log.setLevel(logging.DEBUG)
  101. # log.setLevel(logging.WARNING)
  102. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  103. handler = logging.StreamHandler()
  104. handler.setFormatter(formatter)
  105. log.addHandler(handler)
  106. # ##########################################################################
  107. # ################## Version and VERSION DATE ##############################
  108. # ##########################################################################
  109. version = 8.99
  110. version_date = "2019/12/7"
  111. beta = True
  112. engine = '3D'
  113. # current date now
  114. date = str(datetime.today()).rpartition('.')[0]
  115. date = ''.join(c for c in date if c not in ':-')
  116. date = date.replace(' ', '_')
  117. # URL for update checks and statistics
  118. version_url = "http://flatcam.org/version"
  119. # App URL
  120. app_url = "http://flatcam.org"
  121. # Manual URL
  122. manual_url = "http://flatcam.org/manual/index.html"
  123. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  124. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  125. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  126. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  127. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  128. # this variable will hold the project status
  129. # if True it will mean that the project was modified and not saved
  130. should_we_save = False
  131. # flag is True if saving action has been triggered
  132. save_in_progress = False
  133. # ###########################################################################
  134. # ############################# Signals ################################
  135. # ###########################################################################
  136. # Inform the user
  137. # Handled by:
  138. # * App.info() --> Print on the status bar
  139. inform = QtCore.pyqtSignal(str)
  140. app_quit = QtCore.pyqtSignal()
  141. # General purpose background task
  142. worker_task = QtCore.pyqtSignal(dict)
  143. # File opened
  144. # Handled by:
  145. # * register_folder()
  146. # * register_recent()
  147. # Note: Setting the parameters to unicode does not seem
  148. # to have an effect. Then are received as Qstring
  149. # anyway.
  150. # File type and filename
  151. file_opened = QtCore.pyqtSignal(str, str)
  152. # File type and filename
  153. file_saved = QtCore.pyqtSignal(str, str)
  154. # Percentage of progress
  155. progress = QtCore.pyqtSignal(int)
  156. plots_updated = QtCore.pyqtSignal()
  157. # Emitted by new_object() and passes the new object as argument, plot flag.
  158. # on_object_created() adds the object to the collection, plots on appropriate flag
  159. # and emits new_object_available.
  160. object_created = QtCore.pyqtSignal(object, bool, bool)
  161. # Emitted when a object has been changed (like scaled, mirrored)
  162. object_changed = QtCore.pyqtSignal(object)
  163. # Emitted after object has been plotted.
  164. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  165. object_plotted = QtCore.pyqtSignal(object)
  166. # Emitted when a new object has been added or deleted from/to the collection
  167. object_status_changed = QtCore.pyqtSignal(object, str, str)
  168. message = QtCore.pyqtSignal(str, str, str)
  169. # Emmited when shell command is finished(one command only)
  170. shell_command_finished = QtCore.pyqtSignal(object)
  171. # Emitted when multiprocess pool has been recreated
  172. pool_recreated = QtCore.pyqtSignal(object)
  173. # Emitted when an unhandled exception happens
  174. # in the worker task.
  175. thread_exception = QtCore.pyqtSignal(object)
  176. # used to signal that there are arguments for the app
  177. args_at_startup = QtCore.pyqtSignal(list)
  178. # a reusable signal to replot a list of objects
  179. # should be disconnected after use so it can be reused
  180. replot_signal = pyqtSignal(list)
  181. def __init__(self, user_defaults=True):
  182. """
  183. Starts the application.
  184. :return: app
  185. :rtype: App
  186. """
  187. App.log.info("FlatCAM Starting...")
  188. self.main_thread = QtWidgets.QApplication.instance().thread()
  189. # ############################################################################
  190. # # ################# OS-specific ############################################
  191. # ############################################################################
  192. portable = False
  193. # Folder for user settings.
  194. if sys.platform == 'win32':
  195. # #########################################################################
  196. # Setup the listening thread for another instance launching with args #####
  197. # #########################################################################
  198. # make sure the thread is stored by using a self. otherwise it's garbage collected
  199. self.th = QtCore.QThread()
  200. self.th.start(priority=QtCore.QThread.LowestPriority)
  201. self.new_launch = ArgsThread()
  202. self.new_launch.open_signal[list].connect(self.on_startup_args)
  203. self.new_launch.moveToThread(self.th)
  204. self.new_launch.start.emit()
  205. from win32com.shell import shell, shellcon
  206. if platform.architecture()[0] == '32bit':
  207. App.log.debug("Win32!")
  208. else:
  209. App.log.debug("Win64!")
  210. # #########################################################################
  211. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  212. # #########################################################################
  213. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  214. try:
  215. with open(config_file, 'r'):
  216. pass
  217. except FileNotFoundError:
  218. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  219. try:
  220. with open(config_file, 'r') as f:
  221. try:
  222. for line in f:
  223. param = str(line).replace('\n', '').rpartition('=')
  224. if param[0] == 'portable':
  225. try:
  226. portable = eval(param[2])
  227. except NameError:
  228. portable = False
  229. if param[0] == 'headless':
  230. if param[2].lower() == 'true':
  231. self.cmd_line_headless = 1
  232. else:
  233. self.cmd_line_headless = None
  234. except Exception as e:
  235. log.debug('App.__init__() -->%s' % str(e))
  236. return
  237. except FileNotFoundError as e:
  238. log.debug(str(e))
  239. pass
  240. if portable is False:
  241. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  242. else:
  243. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  244. self.os = 'windows'
  245. else: # Linux/Unix/MacOS
  246. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  247. self.os = 'unix'
  248. # ##########################################################################
  249. # ################## Setup folders and files ###############################
  250. # ##########################################################################
  251. if not os.path.exists(self.data_path):
  252. os.makedirs(self.data_path)
  253. App.log.debug('Created data folder: ' + self.data_path)
  254. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  255. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  256. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  257. if not os.path.exists(self.postprocessorpaths):
  258. os.makedirs(self.postprocessorpaths)
  259. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  260. # create tools_db.FlatConfig file if there is none
  261. try:
  262. f = open(self.data_path + '/tools_db.FlatConfig')
  263. f.close()
  264. except IOError:
  265. App.log.debug('Creating empty tool_db.FlatConfig')
  266. f = open(self.data_path + '/tools_db.FlatConfig', 'w')
  267. json.dump({}, f)
  268. f.close()
  269. # create current_defaults.FlatConfig file if there is none
  270. try:
  271. f = open(self.data_path + '/current_defaults.FlatConfig')
  272. f.close()
  273. except IOError:
  274. App.log.debug('Creating empty current_defaults.FlatConfig')
  275. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  276. json.dump({}, f)
  277. f.close()
  278. # create factory_defaults.FlatConfig file if there is none
  279. try:
  280. f = open(self.data_path + '/factory_defaults.FlatConfig')
  281. f.close()
  282. except IOError:
  283. App.log.debug('Creating empty factory_defaults.FlatConfig')
  284. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  285. json.dump({}, f)
  286. f.close()
  287. # create a recent files json file if there is none
  288. try:
  289. f = open(self.data_path + '/recent.json')
  290. f.close()
  291. except IOError:
  292. App.log.debug('Creating empty recent.json')
  293. f = open(self.data_path + '/recent.json', 'w')
  294. json.dump([], f)
  295. f.close()
  296. # create a recent projects json file if there is none
  297. try:
  298. fp = open(self.data_path + '/recent_projects.json')
  299. fp.close()
  300. except IOError:
  301. App.log.debug('Creating empty recent_projects.json')
  302. fp = open(self.data_path + '/recent_projects.json', 'w')
  303. json.dump([], fp)
  304. fp.close()
  305. # Application directory. CHDIR to it. Otherwise, trying to load
  306. # GUI icons will fail as their path is relative.
  307. # This will fail under cx_freeze ...
  308. self.app_home = os.path.dirname(os.path.realpath(__file__))
  309. App.log.debug("Application path is " + self.app_home)
  310. App.log.debug("Started in " + os.getcwd())
  311. # cx_freeze workaround
  312. if os.path.isfile(self.app_home):
  313. self.app_home = os.path.dirname(self.app_home)
  314. os.chdir(self.app_home)
  315. # #################################################################################
  316. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  317. # #################################################################################
  318. self.defaults = LoudDict()
  319. self.defaults.update({
  320. # Global APP Preferences
  321. "decimals_inch": 4,
  322. "decimals_metric": 4,
  323. "version": self.version,
  324. "first_run": True,
  325. "units": "MM",
  326. "global_serial": 0,
  327. "global_stats": dict(),
  328. "global_tabs_detachable": True,
  329. "global_graphic_engine": '3D',
  330. "global_app_level": 'b',
  331. "global_portable": False,
  332. "global_language": 'English',
  333. "global_version_check": True,
  334. "global_send_stats": True,
  335. "global_pan_button": '2',
  336. "global_mselect_key": 'Control',
  337. "global_project_at_startup": False,
  338. "global_systray_icon": True,
  339. "global_project_autohide": True,
  340. "global_toggle_tooltips": True,
  341. "global_worker_number": 2,
  342. "global_tolerance": 0.005,
  343. "global_open_style": True,
  344. "global_delete_confirmation": True,
  345. "global_compression_level": 3,
  346. "global_save_compressed": True,
  347. "global_machinist_setting": False,
  348. # Global GUI Preferences
  349. "global_gridx": 1.0,
  350. "global_gridy": 1.0,
  351. "global_snap_max": 0.05,
  352. "global_workspace": False,
  353. "global_workspaceT": "A4",
  354. "global_workspace_orientation": 'p',
  355. "global_grid_context_menu": {
  356. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  357. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  358. },
  359. "global_plot_fill": '#BBF268BF',
  360. "global_plot_line": '#006E20BF',
  361. "global_sel_fill": '#a5a5ffbf',
  362. "global_sel_line": '#0000ffbf',
  363. "global_alt_sel_fill": '#BBF268BF',
  364. "global_alt_sel_line": '#006E20BF',
  365. "global_draw_color": '#FF0000',
  366. "global_sel_draw_color": '#0000FF',
  367. "global_proj_item_color": '#000000',
  368. "global_proj_item_dis_color": '#b7b7cb',
  369. "global_activity_icon": 'Ball green',
  370. "global_toolbar_view": 511,
  371. "global_background_timeout": 300000, # Default value is 5 minutes
  372. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  373. # (python trace only for unknown errors),
  374. # 1 = show trace(show trace always),
  375. # 2 = (For the future).
  376. # Persistence
  377. "global_last_folder": None,
  378. "global_last_save_folder": None,
  379. # Default window geometry
  380. "global_def_win_x": 100,
  381. "global_def_win_y": 100,
  382. "global_def_win_w": 1024,
  383. "global_def_win_h": 650,
  384. "global_def_notebook_width": 1,
  385. # Constants...
  386. "global_defaults_save_period_ms": 20000, # Time between default saves.
  387. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  388. "global_shell_at_startup": False, # Show the shell at startup.
  389. "global_recent_limit": 10, # Max. items in recent list.
  390. "global_bookmarks": dict(),
  391. "global_bookmarks_limit": 10,
  392. "fit_key": 'V',
  393. "zoom_out_key": '-',
  394. "zoom_in_key": '=',
  395. "grid_toggle_key": 'G',
  396. "global_zoom_ratio": 1.5,
  397. "global_point_clipboard_format": "(%.4f, %.4f)",
  398. "global_zdownrate": None,
  399. # General GUI Settings
  400. "global_theme": 'white',
  401. "global_hover": False,
  402. "global_selection_shape": True,
  403. "global_layout": "compact",
  404. "global_cursor_type": "small",
  405. "global_cursor_size": 20,
  406. # Gerber General
  407. "gerber_plot": True,
  408. "gerber_solid": True,
  409. "gerber_multicolored": False,
  410. "gerber_circle_steps": 64,
  411. "gerber_use_buffer_for_union": True,
  412. "gerber_def_units": 'IN',
  413. "gerber_def_zeros": 'L',
  414. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  415. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  416. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  417. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  418. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  419. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  420. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  421. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  422. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  423. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  424. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  425. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  426. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  427. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  428. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  429. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  430. "Gerber File (*.tsm);;Gerber File (*.art)"
  431. "All Files (*.*)",
  432. # Gerber Options
  433. "gerber_isotooldia": 0.1,
  434. "gerber_isopasses": 1,
  435. "gerber_isooverlap": 10,
  436. "gerber_milling_type": "cl",
  437. "gerber_combine_passes": False,
  438. "gerber_iso_scope": 'all',
  439. "gerber_noncoppermargin": 0.1,
  440. "gerber_noncopperrounded": False,
  441. "gerber_bboxmargin": 0.1,
  442. "gerber_bboxrounded": False,
  443. # Gerber Advanced Options
  444. "gerber_aperture_display": False,
  445. "gerber_aperture_scale_factor": 1.0,
  446. "gerber_aperture_buffer_factor": 0.0,
  447. "gerber_follow": False,
  448. "gerber_tool_type": 'circular',
  449. "gerber_vtipdia": 0.1,
  450. "gerber_vtipangle": 30,
  451. "gerber_vcutz": -0.05,
  452. "gerber_iso_type": "full",
  453. "gerber_buffering": "full",
  454. "gerber_simplification": False,
  455. "gerber_simp_tolerance": 0.0005,
  456. # Gerber Export
  457. "gerber_exp_units": 'IN',
  458. "gerber_exp_integer": 2,
  459. "gerber_exp_decimals": 4,
  460. "gerber_exp_zeros": 'L',
  461. # Gerber Editor
  462. "gerber_editor_sel_limit": 30,
  463. "gerber_editor_newcode": 10,
  464. "gerber_editor_newsize": 0.8,
  465. "gerber_editor_newtype": 'C',
  466. "gerber_editor_newdim": "0.5, 0.5",
  467. "gerber_editor_array_size": 5,
  468. "gerber_editor_lin_axis": 'X',
  469. "gerber_editor_lin_pitch": 0.1,
  470. "gerber_editor_lin_angle": 0.0,
  471. "gerber_editor_circ_dir": 'CW',
  472. "gerber_editor_circ_angle": 0.0,
  473. "gerber_editor_scale_f": 1.0,
  474. "gerber_editor_buff_f": 0.1,
  475. "gerber_editor_ma_low": 0.0,
  476. "gerber_editor_ma_high": 1.0,
  477. # Excellon General
  478. "excellon_plot": True,
  479. "excellon_solid": True,
  480. "excellon_format_upper_in": 2,
  481. "excellon_format_lower_in": 4,
  482. "excellon_format_upper_mm": 3,
  483. "excellon_format_lower_mm": 3,
  484. "excellon_zeros": "L",
  485. "excellon_units": "INCH",
  486. "excellon_update": True,
  487. "excellon_optimization_type": 'B',
  488. "excellon_search_time": 3,
  489. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  490. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  491. "Excellon File (*.xln);;All Files (*.*)",
  492. # Excellon Options
  493. "excellon_drillz": -1.7,
  494. "excellon_travelz": 2,
  495. "excellon_endz": 0.5,
  496. "excellon_feedrate": 300,
  497. "excellon_spindlespeed": None,
  498. "excellon_dwell": False,
  499. "excellon_dwelltime": 1,
  500. "excellon_toolchange": False,
  501. "excellon_toolchangez": 15,
  502. "excellon_ppname_e": 'default',
  503. "excellon_tooldia": 0.8,
  504. "excellon_slot_tooldia": 1.8,
  505. "excellon_gcode_type": "drills",
  506. # Excellon Advanced Options
  507. "excellon_offset": 0.0,
  508. "excellon_toolchangexy": "0.0, 0.0",
  509. "excellon_startz": None,
  510. "excellon_feedrate_rapid": 1500,
  511. "excellon_z_pdepth": -0.02,
  512. "excellon_feedrate_probe": 75,
  513. "excellon_spindledir": 'CW',
  514. "excellon_f_plunge": False,
  515. "excellon_f_retract": False,
  516. # Excellon Export
  517. "excellon_exp_units": 'INCH',
  518. "excellon_exp_format": 'ndec',
  519. "excellon_exp_integer": 2,
  520. "excellon_exp_decimals": 4,
  521. "excellon_exp_zeros": 'LZ',
  522. "excellon_exp_slot_type": 'routing',
  523. # Excellon Editor
  524. "excellon_editor_sel_limit": 30,
  525. "excellon_editor_newdia": 1.0,
  526. "excellon_editor_array_size": 5,
  527. "excellon_editor_lin_dir": 'X',
  528. "excellon_editor_lin_pitch": 2.54,
  529. "excellon_editor_lin_angle": 0.0,
  530. "excellon_editor_circ_dir": 'CW',
  531. "excellon_editor_circ_angle": 12,
  532. # Excellon Slots
  533. "excellon_editor_slot_direction": 'X',
  534. "excellon_editor_slot_angle": 0.0,
  535. "excellon_editor_slot_length": 5.0,
  536. # Excellon Slot Array
  537. "excellon_editor_slot_array_size": 5,
  538. "excellon_editor_slot_lin_dir": 'X',
  539. "excellon_editor_slot_lin_pitch": 2.54,
  540. "excellon_editor_slot_lin_angle": 0.0,
  541. "excellon_editor_slot_circ_dir": 'CW',
  542. "excellon_editor_slot_circ_angle": 0.0,
  543. # Geometry General
  544. "geometry_plot": True,
  545. "geometry_circle_steps": 64,
  546. "geometry_cnctooldia": "2.4",
  547. # Geometry Options
  548. "geometry_cutz": -2.4,
  549. "geometry_vtipdia": 0.1,
  550. "geometry_vtipangle": 30,
  551. "geometry_multidepth": False,
  552. "geometry_depthperpass": 0.8,
  553. "geometry_travelz": 2,
  554. "geometry_toolchange": False,
  555. "geometry_toolchangez": 15.0,
  556. "geometry_endz": 15.0,
  557. "geometry_feedrate": 120,
  558. "geometry_feedrate_z": 60,
  559. "geometry_spindlespeed": None,
  560. "geometry_dwell": False,
  561. "geometry_dwelltime": 1,
  562. "geometry_ppname_g": 'default',
  563. # Geometry Advanced Options
  564. "geometry_toolchangexy": "0.0, 0.0",
  565. "geometry_startz": None,
  566. "geometry_feedrate_rapid": 1500,
  567. "geometry_extracut": False,
  568. "geometry_z_pdepth": -0.02,
  569. "geometry_f_plunge": False,
  570. "geometry_spindledir": 'CW',
  571. "geometry_feedrate_probe": 75,
  572. "geometry_segx": 0.0,
  573. "geometry_segy": 0.0,
  574. # Geometry Editor
  575. "geometry_editor_sel_limit": 30,
  576. "geometry_editor_milling_type": "cl",
  577. # CNC Job General
  578. "cncjob_plot": True,
  579. "cncjob_plot_kind": 'all',
  580. "cncjob_annotation": True,
  581. "cncjob_tooldia": 1.0,
  582. "cncjob_coords_type": "G90",
  583. "cncjob_coords_decimals": 4,
  584. "cncjob_fr_decimals": 2,
  585. "cncjob_steps_per_circle": 64,
  586. "cncjob_footer": False,
  587. "cncjob_line_ending": False,
  588. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  589. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  590. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  591. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  592. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  593. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  594. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  595. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  596. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  597. "All Files (*.*)",
  598. # CNC Job Options
  599. "cncjob_prepend": "",
  600. "cncjob_append": "",
  601. # CNC Job Advanced Options
  602. "cncjob_toolchange_macro": "",
  603. "cncjob_toolchange_macro_enable": False,
  604. "cncjob_annotation_fontsize": 9,
  605. "cncjob_annotation_fontcolor": '#990000',
  606. # NCC Tool
  607. "tools_ncctools": "1.0, 0.5",
  608. "tools_nccorder": 'rev',
  609. "tools_nccoverlap": 40,
  610. "tools_nccmargin": 1.0,
  611. "tools_nccmethod": "seed",
  612. "tools_nccconnect": True,
  613. "tools_ncccontour": True,
  614. "tools_nccrest": False,
  615. "tools_ncc_offset_choice": False,
  616. "tools_ncc_offset_value": 0.0000,
  617. "tools_nccref": 'itself',
  618. "tools_ncc_plotting": 'normal',
  619. "tools_nccmilling_type": 'cl',
  620. "tools_ncctool_type": 'V',
  621. "tools_ncccutz": -0.05,
  622. "tools_ncctipdia": 0.1,
  623. "tools_ncctipangle": 30,
  624. "tools_nccnewdia": 1.0,
  625. # Cutout Tool
  626. "tools_cutouttooldia": 2.4,
  627. "tools_cutoutkind": "single",
  628. "tools_cutoutmargin": 0.1,
  629. "tools_cutout_z": -1.8,
  630. "tools_cutout_depthperpass": 0.6,
  631. "tools_cutout_mdepth": True,
  632. "tools_cutoutgapsize": 4,
  633. "tools_gaps_ff": "4",
  634. "tools_cutout_convexshape": False,
  635. # Paint Tool
  636. "tools_painttooldia": 0.3,
  637. "tools_paintorder": 'rev',
  638. "tools_paintoverlap": 20,
  639. "tools_paintmargin": 0.0,
  640. "tools_paintmethod": "seed",
  641. "tools_selectmethod": "all",
  642. "tools_pathconnect": True,
  643. "tools_paintcontour": True,
  644. "tools_paint_plotting": 'normal',
  645. # 2-Sided Tool
  646. "tools_2sided_mirror_axis": "X",
  647. "tools_2sided_axis_loc": "point",
  648. "tools_2sided_drilldia": 3.125,
  649. # Film Tool
  650. "tools_film_type": 'neg',
  651. "tools_film_boundary": 1.0,
  652. "tools_film_scale_stroke": 0,
  653. "tools_film_color": '#000000',
  654. "tools_film_scale_cb": False,
  655. "tools_film_scale_x_entry": 1.0,
  656. "tools_film_scale_y_entry": 1.0,
  657. "tools_film_skew_cb": False,
  658. "tools_film_skew_x_entry": 0.0,
  659. "tools_film_skew_y_entry": 0.0,
  660. "tools_film_skew_ref_radio": 'bottomleft',
  661. "tools_film_mirror_cb": False,
  662. "tools_film_mirror_axis_radio": 'none',
  663. "tools_film_file_type_radio": 'svg',
  664. "tools_film_orientation": 'p',
  665. "tools_film_pagesize": 'A4',
  666. # Panel Tool
  667. "tools_panelize_spacing_columns": 0,
  668. "tools_panelize_spacing_rows": 0,
  669. "tools_panelize_columns": 1,
  670. "tools_panelize_rows": 1,
  671. "tools_panelize_constrain": False,
  672. "tools_panelize_constrainx": 200.0,
  673. "tools_panelize_constrainy": 290.0,
  674. "tools_panelize_panel_type": 'gerber',
  675. # Calculators Tool
  676. "tools_calc_vshape_tip_dia": 0.2,
  677. "tools_calc_vshape_tip_angle": 30,
  678. "tools_calc_vshape_cut_z": 0.05,
  679. "tools_calc_electro_length": 10.0,
  680. "tools_calc_electro_width": 10.0,
  681. "tools_calc_electro_cdensity": 13.0,
  682. "tools_calc_electro_growth": 10.0,
  683. # Transform Tool
  684. "tools_transform_rotate": 90,
  685. "tools_transform_skew_x": 0.0,
  686. "tools_transform_skew_y": 0.0,
  687. "tools_transform_scale_x": 1.0,
  688. "tools_transform_scale_y": 1.0,
  689. "tools_transform_scale_link": True,
  690. "tools_transform_scale_reference": True,
  691. "tools_transform_offset_x": 0.0,
  692. "tools_transform_offset_y": 0.0,
  693. "tools_transform_mirror_reference": False,
  694. "tools_transform_mirror_point": (0, 0),
  695. # SolderPaste Tool
  696. "tools_solderpaste_tools": "1.0, 0.3",
  697. "tools_solderpaste_new": 0.3,
  698. "tools_solderpaste_z_start": 0.05,
  699. "tools_solderpaste_z_dispense": 0.1,
  700. "tools_solderpaste_z_stop": 0.05,
  701. "tools_solderpaste_z_travel": 0.1,
  702. "tools_solderpaste_z_toolchange": 1.0,
  703. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  704. "tools_solderpaste_frxy": 150,
  705. "tools_solderpaste_frz": 150,
  706. "tools_solderpaste_frz_dispense": 1.0,
  707. "tools_solderpaste_speedfwd": 300,
  708. "tools_solderpaste_dwellfwd": 1,
  709. "tools_solderpaste_speedrev": 200,
  710. "tools_solderpaste_dwellrev": 1,
  711. "tools_solderpaste_pp": 'Paste_1',
  712. # Subtract Tool
  713. "tools_sub_close_paths": True,
  714. # ###################################################################################
  715. # ################################ TOOLS 2 ##########################################
  716. # ###################################################################################
  717. # Optimal Tool
  718. "tools_opt_precision": 4,
  719. # Check Rules Tool
  720. "tools_cr_trace_size": True,
  721. "tools_cr_trace_size_val": 0.25,
  722. "tools_cr_c2c": True,
  723. "tools_cr_c2c_val": 0.25,
  724. "tools_cr_c2o": True,
  725. "tools_cr_c2o_val": 1.0,
  726. "tools_cr_s2s": True,
  727. "tools_cr_s2s_val": 0.25,
  728. "tools_cr_s2sm": True,
  729. "tools_cr_s2sm_val": 0.25,
  730. "tools_cr_s2o": True,
  731. "tools_cr_s2o_val": 1.0,
  732. "tools_cr_sm2sm": True,
  733. "tools_cr_sm2sm_val": 0.25,
  734. "tools_cr_ri": True,
  735. "tools_cr_ri_val": 0.3,
  736. "tools_cr_h2h": True,
  737. "tools_cr_h2h_val": 0.3,
  738. "tools_cr_dh": True,
  739. "tools_cr_dh_val": 0.3,
  740. # QRCode Tool
  741. "tools_qrcode_version": 1,
  742. "tools_qrcode_error": 'L',
  743. "tools_qrcode_box_size": 3,
  744. "tools_qrcode_border_size": 4,
  745. "tools_qrcode_qrdata": '',
  746. "tools_qrcode_polarity": 'pos',
  747. "tools_qrcode_rounded": 's',
  748. "tools_qrcode_fill_color": '#000000',
  749. "tools_qrcode_back_color": '#FFFFFF',
  750. "tools_qrcode_sel_limit": 330,
  751. # Copper Thieving Tool
  752. "tools_copper_thieving_clearance": 0.25,
  753. "tools_copper_thieving_margin": 1.0,
  754. "tools_copper_thieving_reference": 'itself',
  755. "tools_copper_thieving_box_type": 'rect',
  756. "tools_copper_thieving_circle_steps": 64,
  757. "tools_copper_thieving_fill_type": 'solid',
  758. "tools_copper_thieving_dots_dia": 1.0,
  759. "tools_copper_thieving_dots_spacing": 2.0,
  760. "tools_copper_thieving_squares_size": 1.0,
  761. "tools_copper_thieving_squares_spacing": 2.0,
  762. "tools_copper_thieving_lines_size": 0.25,
  763. "tools_copper_thieving_lines_spacing": 2.0,
  764. "tools_copper_thieving_rb_margin": 1.0,
  765. "tools_copper_thieving_rb_thickness": 1.0,
  766. "tools_copper_thieving_mask_clearance": 0.0,
  767. # Fiducials Tool
  768. "tools_fiducials_dia": 1.0,
  769. "tools_fiducials_margin": 1.0,
  770. "tools_fiducials_mode": 'auto',
  771. "tools_fiducials_second_pos": 'up',
  772. "tools_fiducials_type": 'circular',
  773. "tools_fiducials_line_thickness": 0.25,
  774. # Utilities
  775. # file associations
  776. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  777. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  778. 'ncg, ncp, ngc, out, plt, ply, rol, sbp, tap, xpi',
  779. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  780. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  781. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  782. # Keyword list
  783. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  784. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  785. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  786. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  787. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  788. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  789. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  790. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  791. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  792. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  793. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  794. 'z_move',
  795. "script_autocompleter": True,
  796. "script_text": "",
  797. "script_plot": True,
  798. "script_source_file": "",
  799. "document_autocompleter": False,
  800. "document_text": "",
  801. "document_plot": True,
  802. "document_source_file": "",
  803. "document_font_color": '#000000',
  804. "document_sel_color": '#0055ff',
  805. "document_font_size": 6,
  806. "document_tab_size": 80,
  807. })
  808. # ############################################################
  809. # ############### Load defaults from file ####################
  810. # ############################################################
  811. self.old_defaults_found = False
  812. if user_defaults:
  813. self.load_defaults(filename='current_defaults')
  814. if self.defaults['units'] == 'MM':
  815. self.decimals = int(self.defaults['decimals_metric'])
  816. else:
  817. self.decimals = int(self.defaults['decimals_inch'])
  818. # #############################################################################
  819. # ##################### CREATE MULTIPROCESSING POOL ###########################
  820. # #############################################################################
  821. self.pool = Pool(processes=cpu_count())
  822. # ##########################################################################
  823. # ################## Setting the Splash Screen #############################
  824. # ##########################################################################
  825. splash_settings = QSettings("Open Source", "FlatCAM")
  826. if splash_settings.contains("splash_screen"):
  827. show_splash = splash_settings.value("splash_screen")
  828. else:
  829. splash_settings.setValue('splash_screen', 1)
  830. # This will write the setting to the platform specific storage.
  831. del splash_settings
  832. show_splash = 1
  833. if show_splash and self.cmd_line_headless != 1:
  834. splash_pix = QtGui.QPixmap('share/splash.png')
  835. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  836. # self.splash.setMask(splash_pix.mask())
  837. # move splashscreen to the current monitor
  838. desktop = QtWidgets.QApplication.desktop()
  839. screen = desktop.screenNumber(QtGui.QCursor.pos())
  840. current_screen_center = desktop.availableGeometry(screen).center()
  841. self.splash.move(current_screen_center - self.splash.rect().center())
  842. self.splash.show()
  843. self.splash.showMessage(_("FlatCAM is initializing ..."),
  844. alignment=Qt.AlignBottom | Qt.AlignLeft,
  845. color=QtGui.QColor("gray"))
  846. else:
  847. show_splash = 0
  848. # #############################################################################
  849. # ##################### Initialize GUI ########################################
  850. # #############################################################################
  851. # FlatCAM colors used in plotting
  852. self.FC_light_green = '#BBF268BF'
  853. self.FC_dark_green = '#006E20BF'
  854. self.FC_light_blue = '#a5a5ffbf'
  855. self.FC_dark_blue = '#0000ffbf'
  856. QtCore.QObject.__init__(self)
  857. self.ui = FlatCAMGUI(self)
  858. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  859. if theme_settings.contains("theme"):
  860. theme = theme_settings.value('theme', type=str)
  861. else:
  862. theme = 'white'
  863. if theme == 'white':
  864. self.cursor_color_3D = 'black'
  865. else:
  866. self.cursor_color_3D = 'gray'
  867. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  868. self.ui.final_save.connect(self.final_save)
  869. # restore the toolbar view
  870. self.restore_toolbar_view()
  871. # restore the GUI geometry
  872. self.restore_main_win_geom()
  873. # set FlatCAM units in the Status bar
  874. self.set_screen_units(self.defaults['units'])
  875. # #############################################################################
  876. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  877. # #############################################################################
  878. # when adding entries here read the comments in the method found bellow named:
  879. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  880. self.defaults_form_fields = {
  881. # General App
  882. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  883. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  884. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  885. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  886. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  887. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  888. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  889. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  890. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  891. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  892. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  893. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  894. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  895. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  896. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  897. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  898. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  899. "global_machinist_setting": self.ui.general_defaults_form.general_app_group.machinist_cb,
  900. # General GUI Preferences
  901. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  902. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  903. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  904. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  905. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  906. "global_workspace_orientation": self.ui.general_defaults_form.general_gui_group.wk_orientation_radio,
  907. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  908. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  909. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  910. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  911. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  912. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  913. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  914. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  915. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  916. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  917. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  918. # General GUI Settings
  919. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  920. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  921. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  922. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  923. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  924. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  925. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  926. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  927. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  928. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  929. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  930. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  931. # Gerber General
  932. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  933. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  934. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  935. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  936. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  937. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  938. # Gerber Options
  939. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  940. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  941. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  942. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  943. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  944. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  945. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  946. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  947. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  948. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  949. # Gerber Advanced Options
  950. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  951. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  952. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  953. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  954. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  955. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  956. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  957. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  958. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  959. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  960. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  961. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  962. # Gerber Export
  963. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  964. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  965. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  966. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  967. # Gerber Editor
  968. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  969. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  970. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  971. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  972. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  973. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  974. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  975. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  976. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  977. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  978. "gerber_editor_circ_angle":
  979. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  980. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  981. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  982. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  983. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  984. # Excellon General
  985. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  986. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  987. "excellon_format_upper_in":
  988. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  989. "excellon_format_lower_in":
  990. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  991. "excellon_format_upper_mm":
  992. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  993. "excellon_format_lower_mm":
  994. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  995. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  996. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  997. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  998. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  999. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1000. # Excellon Options
  1001. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1002. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1003. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  1004. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  1005. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1006. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1007. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1008. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1009. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1010. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1011. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1012. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1013. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1014. # Excellon Advanced Options
  1015. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1016. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1017. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1018. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1019. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1020. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1021. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1022. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1023. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1024. # Excellon Export
  1025. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1026. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1027. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1028. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1029. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1030. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1031. # Excellon Editor
  1032. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1033. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1034. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1035. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1036. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1037. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1038. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1039. "excellon_editor_circ_angle":
  1040. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1041. # Excellon Slots
  1042. "excellon_editor_slot_direction":
  1043. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1044. "excellon_editor_slot_angle":
  1045. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1046. "excellon_editor_slot_length":
  1047. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1048. # Excellon Slots
  1049. "excellon_editor_slot_array_size":
  1050. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1051. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1052. "excellon_editor_slot_lin_pitch":
  1053. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1054. "excellon_editor_slot_lin_angle":
  1055. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1056. "excellon_editor_slot_circ_dir":
  1057. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1058. "excellon_editor_slot_circ_angle":
  1059. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1060. # Geometry General
  1061. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1062. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1063. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1064. # Geometry Options
  1065. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1066. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1067. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1068. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1069. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1070. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1071. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1072. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1073. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1074. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1075. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1076. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1077. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1078. # Geometry Advanced Options
  1079. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1080. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1081. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1082. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1083. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1084. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1085. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1086. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1087. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1088. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1089. # Geometry Editor
  1090. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1091. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1092. # CNCJob General
  1093. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1094. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1095. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1096. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1097. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1098. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1099. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1100. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1101. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1102. # CNC Job Options
  1103. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1104. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1105. # CNC Job Advanced Options
  1106. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1107. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1108. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1109. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1110. # NCC Tool
  1111. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1112. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1113. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1114. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1115. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1116. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1117. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1118. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1119. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1120. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1121. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1122. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1123. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1124. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1125. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1126. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1127. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1128. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1129. # CutOut Tool
  1130. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1131. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1132. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1133. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1134. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1135. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1136. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1137. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1138. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1139. # Paint Area Tool
  1140. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1141. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1142. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1143. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1144. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1145. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1146. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1147. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1148. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1149. # 2-sided Tool
  1150. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1151. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1152. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1153. # Film Tool
  1154. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1155. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1156. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1157. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1158. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1159. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1160. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1161. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1162. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1163. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1164. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1165. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1166. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1167. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1168. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1169. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1170. # Panelize Tool
  1171. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1172. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1173. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1174. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1175. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1176. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1177. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1178. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1179. # Calculators Tool
  1180. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1181. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1182. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1183. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1184. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1185. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1186. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1187. # Transformations Tool
  1188. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1189. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1190. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1191. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1192. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1193. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1194. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1195. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1196. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1197. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1198. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1199. # SolderPaste Dispensing Tool
  1200. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1201. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1202. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1203. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1204. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1205. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1206. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1207. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1208. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1209. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1210. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1211. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1212. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1213. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1214. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1215. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1216. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1217. # ###################################################################################
  1218. # ################################ TOOLS 2 ##########################################
  1219. # ###################################################################################
  1220. # Optimal Tool
  1221. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1222. # Check Rules Tool
  1223. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1224. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1225. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1226. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1227. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1228. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1229. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1230. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1231. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1232. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1233. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1234. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1235. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1236. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1237. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1238. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1239. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1240. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1241. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1242. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1243. # QRCode Tool
  1244. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1245. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1246. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1247. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1248. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1249. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1250. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1251. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1252. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1253. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1254. # Copper Thieving Tool
  1255. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1256. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1257. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1258. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1259. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1260. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1261. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1262. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1263. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1264. "tools_copper_thieving_squares_spacing":
  1265. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1266. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1267. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1268. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1269. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1270. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1271. # Fiducials Tool
  1272. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1273. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1274. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1275. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1276. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1277. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1278. # Utilities
  1279. # File associations
  1280. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1281. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1282. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1283. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1284. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1285. }
  1286. # update the Preferences GUI elements with the values in the self.defaults
  1287. self.defaults_write_form()
  1288. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1289. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1290. # #############################################################################
  1291. # ############################## Data #########################################
  1292. # #############################################################################
  1293. self.recent = []
  1294. self.recent_projects = []
  1295. self.clipboard = QtWidgets.QApplication.clipboard()
  1296. self.project_filename = None
  1297. self.toggle_units_ignore = False
  1298. # #############################################################################
  1299. # ########################## LOAD POSTPROCESSORS ##############################
  1300. # #############################################################################
  1301. # a dictionary that have as keys the name of the postprocessor files and the value is the class from
  1302. # the postprocessor file
  1303. self.postprocessors = load_postprocessors(self)
  1304. # make sure that always the 'default' postprocessor is the first item in the dictionary
  1305. if 'default' in self.postprocessors.keys():
  1306. new_ppp_dict = dict()
  1307. # add the 'default' name first in the dict after removing from the postprocessor's dictionary
  1308. default_pp = self.postprocessors.pop('default')
  1309. new_ppp_dict['default'] = default_pp
  1310. # then add the rest of the keys
  1311. for name, val_class in self.postprocessors.items():
  1312. new_ppp_dict[name] = val_class
  1313. # and now put back the ordered dict with 'default' key first
  1314. self.postprocessors = new_ppp_dict
  1315. for name in list(self.postprocessors.keys()):
  1316. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  1317. if name.partition('_')[0] == 'Paste':
  1318. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1319. continue
  1320. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1321. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1322. if name == 'hpgl':
  1323. continue
  1324. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1325. # #############################################################################
  1326. # ########################## LOAD LANGUAGES ##################################
  1327. # #############################################################################
  1328. self.languages = fcTranslate.load_languages()
  1329. for name in sorted(self.languages.values()):
  1330. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1331. # #############################################################################
  1332. # ############################ APPLY APP LANGUAGE #############################
  1333. # #############################################################################
  1334. ret_val = fcTranslate.apply_language('strings')
  1335. if ret_val == "no language":
  1336. self.inform.emit('[ERROR] %s' %
  1337. _("Could not find the Language files. The App strings are missing."))
  1338. log.debug("Could not find the Language files. The App strings are missing.")
  1339. else:
  1340. # make the current language the current selection on the language combobox
  1341. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1342. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1343. # #############################################################################
  1344. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1345. # #############################################################################
  1346. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1347. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1348. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1349. self.save_defaults(silent=True, first_time=True)
  1350. self.propagate_defaults(silent=True)
  1351. # def auto_save_defaults():
  1352. # try:
  1353. # self.save_defaults(silent=True)
  1354. # self.propagate_defaults(silent=True)
  1355. # finally:
  1356. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1357. # the following lines activates automatic defaults save
  1358. # if user_defaults:
  1359. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1360. # #############################################################################
  1361. # ########################### UPDATE THE OPTIONS ##############################
  1362. # #############################################################################
  1363. self.options = LoudDict()
  1364. # ----------------------------------------------------------------------------------------------------
  1365. # Update the self.options from the self.defaults
  1366. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1367. # -----------------------------------------------------------------------------------------------------
  1368. # Copy app defaults to project options
  1369. for def_key, def_val in self.defaults.items():
  1370. self.options[def_key] = deepcopy(def_val)
  1371. # self.options.update(self.defaults)
  1372. self.gen_form = None
  1373. self.ger_form = None
  1374. self.exc_form = None
  1375. self.geo_form = None
  1376. self.cnc_form = None
  1377. self.tools_form = None
  1378. self.tools2_form = None
  1379. self.fa_form = None
  1380. # Will show the Preferences GUI
  1381. self.show_preferences_gui()
  1382. # Initialize the color box's color in Preferences -> Global -> Color
  1383. self.init_color_pickers_in_preferences_gui()
  1384. # ### End of Data ####
  1385. # #############################################################################
  1386. # ######################## SETUP OBJECT COLLECTION ############################
  1387. # #############################################################################
  1388. self.collection = ObjectCollection(self)
  1389. self.ui.project_tab_layout.addWidget(self.collection.view)
  1390. # ### Adjust tabs width ## ##
  1391. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1392. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1393. self.collection.view.setMinimumWidth(290)
  1394. self.log.debug("Finished creating Object Collection.")
  1395. # #############################################################################
  1396. # ############################## SETUP Plot Area ##############################
  1397. # #############################################################################
  1398. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1399. if self.defaults["global_graphic_engine"] == '3D':
  1400. self.is_legacy = False
  1401. else:
  1402. self.is_legacy = True
  1403. # Event signals disconnect id holders
  1404. self.mp = None
  1405. self.mm = None
  1406. self.mr = None
  1407. self.mdc = None
  1408. self.mp_zc = None
  1409. # Matplotlib axis
  1410. self.axes = None
  1411. if show_splash:
  1412. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1413. "Canvas initialization started."),
  1414. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1415. color=QtGui.QColor("gray"))
  1416. start_plot_time = time.time() # debug
  1417. self.plotcanvas = None
  1418. self.app_cursor = None
  1419. self.hover_shapes = None
  1420. # setup the PlotCanvas
  1421. self.on_plotcanvas_setup()
  1422. end_plot_time = time.time()
  1423. self.used_time = end_plot_time - start_plot_time
  1424. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1425. if show_splash:
  1426. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1427. "Canvas initialization started.\n"
  1428. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1429. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1430. color=QtGui.QColor("gray"))
  1431. self.ui.splitter.setStretchFactor(1, 2)
  1432. # #############################################################################
  1433. # ################################### SYS TRAY ################################
  1434. # #############################################################################
  1435. if self.defaults["global_systray_icon"]:
  1436. self.parent_w = QtWidgets.QWidget()
  1437. if self.cmd_line_headless == 1:
  1438. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1439. headless=True,
  1440. parent=self.parent_w)
  1441. else:
  1442. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1443. parent=self.parent_w)
  1444. # #############################################################################
  1445. # ################################## Worker SETUP #############################
  1446. # #############################################################################
  1447. if self.defaults["global_worker_number"]:
  1448. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1449. else:
  1450. self.workers = WorkerStack(workers_number=2)
  1451. self.worker_task.connect(self.workers.add_task)
  1452. self.log.debug("Finished creating Workers crew.")
  1453. # #############################################################################
  1454. # ################################# Activity Monitor ##########################
  1455. # #############################################################################
  1456. self.activity_view = FlatCAMActivityView(app=self)
  1457. self.ui.infobar.addWidget(self.activity_view)
  1458. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1459. # #############################################################################
  1460. # ################################## Signal handling ##########################
  1461. # #############################################################################
  1462. # ################################# Custom signals ###########################
  1463. # signal for displaying messages in status bar
  1464. self.inform.connect(self.info)
  1465. # signal to be called when the app is quiting
  1466. self.app_quit.connect(self.quit_application)
  1467. self.message.connect(self.message_dialog)
  1468. self.progress.connect(self.set_progress_bar)
  1469. # signals that are emitted when object state changes
  1470. self.object_created.connect(self.on_object_created)
  1471. self.object_changed.connect(self.on_object_changed)
  1472. self.object_plotted.connect(self.on_object_plotted)
  1473. self.plots_updated.connect(self.on_plots_updated)
  1474. # signals emitted when file state change
  1475. self.file_opened.connect(self.register_recent)
  1476. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1477. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1478. # ############# Standard signals ###################
  1479. # ### Menu
  1480. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1481. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1482. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1483. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1484. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1485. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1486. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1487. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1488. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1489. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1490. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1491. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1492. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1493. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1494. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1495. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1496. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1497. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1498. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1499. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1500. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1501. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1502. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1503. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1504. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1505. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1506. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1507. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1508. self.ui.menufile_exit.triggered.connect(self.final_save)
  1509. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1510. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1511. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1512. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1513. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1514. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1515. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1516. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1517. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1518. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1519. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1520. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1521. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1522. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1523. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1524. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1525. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1526. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1527. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1528. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1529. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1530. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1531. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1532. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1533. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1534. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1535. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1536. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1537. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1538. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1539. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1540. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1541. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1542. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1543. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1544. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1545. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1546. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1547. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1548. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1549. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1550. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1551. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1552. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1553. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1554. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1555. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1556. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1557. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1558. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1559. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1560. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1561. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1562. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1563. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1564. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1565. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1566. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1567. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1568. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1569. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1570. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1571. # ToolBar signals
  1572. self.connect_toolbar_signals()
  1573. # Notebook and Plot Tab Area signals
  1574. # make the right click on the notebook tab and plot tab area tab raise a menu
  1575. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1576. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1577. self.on_tab_setup_context_menu()
  1578. # activate initial state
  1579. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1580. # Context Menu
  1581. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1582. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1583. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1584. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1585. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1586. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1587. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1588. self.ui.clearplot.triggered.connect(self.clear_plots)
  1589. self.ui.replot.triggered.connect(self.plot_all)
  1590. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1591. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1592. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1593. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1594. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1595. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1596. # Preferences Plot Area TAB
  1597. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1598. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1599. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1600. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1601. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1602. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1603. # #############################################################################
  1604. # ######################### GUI PREFERENCES SIGNALS ###########################
  1605. # #############################################################################
  1606. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1607. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1608. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1609. )
  1610. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1611. lambda: self.on_toggle_units(no_pref=False))
  1612. # #############################################################################
  1613. # ############################# GUI COLORS SIGNALS ############################
  1614. # #############################################################################
  1615. # Setting plot colors signals
  1616. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1617. self.on_pf_color_entry)
  1618. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1619. self.on_pf_color_button)
  1620. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1621. self.on_pf_color_spinner)
  1622. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1623. self.on_pf_color_slider)
  1624. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1625. self.on_pl_color_entry)
  1626. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1627. self.on_pl_color_button)
  1628. # Setting selection (left - right) colors signals
  1629. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1630. self.on_sf_color_entry)
  1631. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1632. self.on_sf_color_button)
  1633. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1634. self.on_sf_color_spinner)
  1635. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1636. self.on_sf_color_slider)
  1637. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1638. self.on_sl_color_entry)
  1639. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1640. self.on_sl_color_button)
  1641. # Setting selection (right - left) colors signals
  1642. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1643. self.on_alt_sf_color_entry)
  1644. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1645. self.on_alt_sf_color_button)
  1646. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1647. self.on_alt_sf_color_spinner)
  1648. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1649. self.on_alt_sf_color_slider)
  1650. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1651. self.on_alt_sl_color_entry)
  1652. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1653. self.on_alt_sl_color_button)
  1654. # Setting Editor Draw colors signals
  1655. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1656. self.on_draw_color_entry)
  1657. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1658. self.on_draw_color_button)
  1659. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1660. self.on_sel_draw_color_entry)
  1661. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1662. self.on_sel_draw_color_button)
  1663. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1664. self.on_proj_color_entry)
  1665. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1666. self.on_proj_color_button)
  1667. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1668. self.on_proj_color_dis_entry)
  1669. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1670. self.on_proj_color_dis_button)
  1671. # ############################# workspace setting signals #####################
  1672. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1673. self.ui.general_defaults_form.general_gui_group.wk_orientation_radio.activated_custom.connect(
  1674. self.on_workspace_modified
  1675. )
  1676. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1677. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1678. # #############################################################################
  1679. # ############################# GUI SETTINGS SIGNALS ##########################
  1680. # #############################################################################
  1681. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1682. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1683. # ########## CNC Job related signals #############
  1684. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1685. self.on_cnc_custom_parameters)
  1686. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1687. self.on_annotation_fontcolor_entry)
  1688. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1689. self.on_annotation_fontcolor_button)
  1690. # ########## Tools related signals #############
  1691. # Film Tool
  1692. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1693. self.on_film_color_entry)
  1694. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1695. self.on_film_color_button)
  1696. # QRCode Tool
  1697. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1698. self.on_qrcode_fill_color_entry)
  1699. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1700. self.on_qrcode_fill_color_button)
  1701. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1702. self.on_qrcode_back_color_entry)
  1703. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1704. self.on_qrcode_back_color_button)
  1705. # portability changed signal
  1706. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1707. # Object list
  1708. self.collection.view.activated.connect(self.on_row_activated)
  1709. self.collection.item_selected.connect(self.on_row_selected)
  1710. self.object_status_changed.connect(self.on_collection_updated)
  1711. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1712. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1713. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1714. # Export Excellon parameters.
  1715. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1716. self.on_update_exc_export
  1717. )
  1718. # call it once to make sure it is updated at startup
  1719. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1720. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1721. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1722. self.on_excellon_defaults_button)
  1723. # when there are arguments at application startup this get launched
  1724. self.args_at_startup[list].connect(self.on_startup_args)
  1725. # #############################################################################
  1726. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1727. # #############################################################################
  1728. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1729. lambda: self.restore_extensions(ext_type='excellon'))
  1730. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1731. lambda: self.restore_extensions(ext_type='gcode'))
  1732. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1733. lambda: self.restore_extensions(ext_type='gerber'))
  1734. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1735. lambda: self.delete_all_extensions(ext_type='excellon'))
  1736. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1737. lambda: self.delete_all_extensions(ext_type='gcode'))
  1738. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1739. lambda: self.delete_all_extensions(ext_type='gerber'))
  1740. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1741. lambda: self.add_extension(ext_type='excellon'))
  1742. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1743. lambda: self.add_extension(ext_type='gcode'))
  1744. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1745. lambda: self.add_extension(ext_type='gerber'))
  1746. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1747. lambda: self.del_extension(ext_type='excellon'))
  1748. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1749. lambda: self.del_extension(ext_type='gcode'))
  1750. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1751. lambda: self.del_extension(ext_type='gerber'))
  1752. # connect the 'Apply' buttons from the Preferences/File Associations
  1753. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1754. lambda: self.on_register_files(obj_type='excellon'))
  1755. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1756. lambda: self.on_register_files(obj_type='gcode'))
  1757. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1758. lambda: self.on_register_files(obj_type='gerber'))
  1759. # #############################################################################
  1760. # ################################ KEYWORDS SIGNALS ###########################
  1761. # #############################################################################
  1762. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1763. lambda: self.restore_extensions(ext_type='keyword'))
  1764. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1765. lambda: self.delete_all_extensions(ext_type='keyword'))
  1766. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1767. lambda: self.add_extension(ext_type='keyword'))
  1768. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1769. lambda: self.del_extension(ext_type='keyword'))
  1770. # splash screen button signal
  1771. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1772. # connect the abort_all_tasks related slots to the related signals
  1773. self.proc_container.idle_flag.connect(self.app_is_idle)
  1774. # signal emitted when a tab is closed in the Plot Area
  1775. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1776. # #####################################################################################
  1777. # ########### FINISHED CONNECTING SIGNALS #############################################
  1778. # #####################################################################################
  1779. self.log.debug("Finished connecting Signals.")
  1780. # #####################################################################################
  1781. # ########################## Other setups #############################################
  1782. # #####################################################################################
  1783. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1784. # depending on from where those tools are called different actions can be done
  1785. self.call_source = 'app'
  1786. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1787. self.tool_tab_locked = False
  1788. # decide if to show or hide the Notebook side of the screen at startup
  1789. if self.defaults["global_project_at_startup"] is True:
  1790. self.ui.splitter.setSizes([1, 1])
  1791. else:
  1792. self.ui.splitter.setSizes([0, 1])
  1793. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1794. self.setup_obj_classes()
  1795. self.setup_component_editor()
  1796. # #####################################################################################
  1797. # ######################### Auto-complete KEYWORDS ####################################
  1798. # #####################################################################################
  1799. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1800. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1801. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1802. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1803. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1804. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1805. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1806. 'mirror', 'ncc',
  1807. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1808. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1809. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1810. 'save', 'save_project',
  1811. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1812. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1813. 'version', 'write_gcode'
  1814. ]
  1815. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1816. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1817. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1818. 'axisoffset',
  1819. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1820. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1821. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1822. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1823. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1824. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1825. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1826. 'spacing_columns',
  1827. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1828. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1829. ]
  1830. self.tcl_keywords = [
  1831. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1832. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1833. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1834. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1835. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1836. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1837. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1838. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1839. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1840. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1841. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1842. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1843. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1844. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1845. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1846. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1847. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1848. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1849. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1850. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1851. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1852. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1853. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1854. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1855. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1856. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1857. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1858. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1859. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1860. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1861. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1862. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1863. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1864. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1865. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1866. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1867. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1868. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1869. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1870. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1871. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1872. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1873. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1874. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1875. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1876. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1877. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1878. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1879. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1880. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1881. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1882. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1883. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1884. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1885. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1886. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1887. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1888. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1889. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1890. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1891. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1892. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1893. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1894. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1895. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1896. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1897. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1898. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1899. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1900. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1901. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1902. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1903. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1904. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1905. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1906. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1907. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1908. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1909. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1910. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1911. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1912. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1913. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1914. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1915. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1916. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1917. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1918. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1919. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1920. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1921. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1922. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1923. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1924. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1925. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1926. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1927. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1928. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1929. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1930. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1931. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1932. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1933. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1934. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1935. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1936. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1937. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1938. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1939. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1940. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1941. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1942. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1943. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1944. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1945. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1946. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1947. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1948. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1949. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1950. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1951. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1952. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1953. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1954. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1955. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1956. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1957. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1958. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1959. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1960. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1961. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1962. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1963. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1964. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1965. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1966. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1967. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1968. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1969. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1970. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1971. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1972. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1973. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1974. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1975. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1976. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1977. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1978. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1979. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1980. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1981. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1982. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1983. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1984. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1985. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1986. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1987. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1988. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1989. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1990. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1991. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1992. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1993. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1994. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1995. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1996. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1997. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1998. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1999. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2000. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2001. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2002. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2003. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2004. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2005. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2006. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2007. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2008. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2009. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2010. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2011. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2012. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2013. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2014. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2015. ]
  2016. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2017. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2018. # ####################################################################################
  2019. # ####################### Shell SETUP ################################################
  2020. # ####################################################################################
  2021. # this will hold the TCL instance
  2022. self.tcl = None
  2023. self.init_tcl()
  2024. self.shell = FCShell(self, version=self.version)
  2025. self.shell._edit.set_model_data(self.myKeywords)
  2026. self.shell.setWindowIcon(self.ui.app_icon)
  2027. self.shell.setWindowTitle("FlatCAM Shell")
  2028. self.shell.resize(*self.defaults["global_shell_shape"])
  2029. self.shell.append_output("FlatCAM %s - " % self.version)
  2030. self.shell.append_output(_("Type >help< to get started\n\n"))
  2031. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2032. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2033. self.ui.shell_dock.setWidget(self.shell)
  2034. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2035. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2036. QtWidgets.QDockWidget.DockWidgetFloatable |
  2037. QtWidgets.QDockWidget.DockWidgetClosable)
  2038. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2039. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2040. if self.defaults["global_shell_at_startup"]:
  2041. self.ui.shell_dock.show()
  2042. else:
  2043. self.ui.shell_dock.hide()
  2044. # ##################################################################################
  2045. # ###################### Tools and Plugins #########################################
  2046. # ##################################################################################
  2047. self.dblsidedtool = None
  2048. self.distance_tool = None
  2049. self.distance_min_tool = None
  2050. self.panelize_tool = None
  2051. self.film_tool = None
  2052. self.paste_tool = None
  2053. self.calculator_tool = None
  2054. self.rules_tool = None
  2055. self.sub_tool = None
  2056. self.move_tool = None
  2057. self.cutout_tool = None
  2058. self.ncclear_tool = None
  2059. self.optimal_tool = None
  2060. self.paint_tool = None
  2061. self.transform_tool = None
  2062. self.properties_tool = None
  2063. self.pdf_tool = None
  2064. self.image_tool = None
  2065. self.pcb_wizard_tool = None
  2066. self.cal_exc_tool = None
  2067. self.qrcode_tool = None
  2068. self.copper_thieving_tool = None
  2069. self.fiducial_tool = None
  2070. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2071. self.install_tools()
  2072. # ##################################################################################
  2073. # ########################### SETUP RECENT ITEMS ###################################
  2074. # ##################################################################################
  2075. self.setup_recent_items()
  2076. # ##################################################################################
  2077. # ########################### BookMarks Manager ####################################
  2078. # ##################################################################################
  2079. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2080. self.install_bookmarks()
  2081. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2082. # ##################################################################################
  2083. # ############################## Tools Database ####################################
  2084. # ##################################################################################
  2085. self.tools_db_tab = None
  2086. # ### System Font Parsing ###
  2087. # self.f_parse = ParseFont(self)
  2088. # self.parse_system_fonts()
  2089. # #####################################################################################
  2090. # ######################## Check for updates ##########################################
  2091. # #####################################################################################
  2092. # Separate thread (Not worker)
  2093. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2094. if (self.beta is False or self.beta is None) and \
  2095. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2096. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2097. self.thr2 = QtCore.QThread()
  2098. self.worker_task.emit({'fcn': self.version_check,
  2099. 'params': []})
  2100. self.thr2.start(QtCore.QThread.LowPriority)
  2101. # #####################################################################################
  2102. # ######################### Register files with FlatCAM; #############################
  2103. # ######################### It works only for Windows for now ########################
  2104. # #####################################################################################
  2105. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2106. self.on_register_files()
  2107. # #####################################################################################
  2108. # ###################### Variables for global usage ###################################
  2109. # #####################################################################################
  2110. # hold the App units
  2111. self.units = 'IN'
  2112. # coordinates for relative position display
  2113. self.rel_point1 = (0, 0)
  2114. self.rel_point2 = (0, 0)
  2115. # variable to store coordinates
  2116. self.pos = (0, 0)
  2117. self.pos_jump = (0, 0)
  2118. # variable to store mouse coordinates
  2119. self.mouse = [0, 0]
  2120. # decide if we have a double click or single click
  2121. self.doubleclick = False
  2122. # store here the is_dragging value
  2123. self.event_is_dragging = False
  2124. # variable to store if a command is active (then the var is not None) and which one it is
  2125. self.command_active = None
  2126. # variable to store the status of moving selection action
  2127. # None value means that it's not an selection action
  2128. # True value = a selection from left to right
  2129. # False value = a selection from right to left
  2130. self.selection_type = None
  2131. # List to store the objects that are currently loaded in FlatCAM
  2132. # This list is updated on each object creation or object delete
  2133. self.all_objects_list = list()
  2134. # List to store the objects that are selected
  2135. self.sel_objects_list = list()
  2136. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2137. self.key_modifiers = None
  2138. # Variable to hold the status of the axis
  2139. self.toggle_axis = True
  2140. # Variable to hold the status of the grid lines
  2141. self.toggle_grid_lines = True
  2142. # Variable to store the status of the fullscreen event
  2143. self.toggle_fscreen = False
  2144. # Variable to store the status of the code editor
  2145. self.toggle_codeeditor = False
  2146. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2147. self.click_noproject = False
  2148. self.cursor = None
  2149. # Variable to store the GCODE that was edited
  2150. self.gcode_edited = ""
  2151. self.text_editor_tab = None
  2152. # reference for the self.ui.code_editor
  2153. self.reference_code_editor = None
  2154. self.script_code = ''
  2155. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2156. self.preferences_changed_flag = False
  2157. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2158. self.tools_db_changed_flag = False
  2159. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2160. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2161. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2162. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2163. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2164. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2165. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'plt', 'ply', 'rol',
  2166. 'sbp', 'tap', 'xpi']
  2167. self.svg_list = ['svg']
  2168. self.dxf_list = ['dxf']
  2169. self.pdf_list = ['pdf']
  2170. self.prj_list = ['flatprj']
  2171. self.conf_list = ['flatconfig']
  2172. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2173. # flag for polygons not cleared
  2174. self.poly_not_cleared = False
  2175. # VisPy visuals
  2176. self.isHovering = False
  2177. self.notHovering = True
  2178. # Window geometry
  2179. self.x_pos = None
  2180. self.y_pos = None
  2181. self.width = None
  2182. self.height = None
  2183. # when True, the app has to return from any thread
  2184. self.abort_flag = False
  2185. # set the value used in the Windows Title
  2186. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2187. # this holds a widget that is installed in the Plot Area when View Source option is used
  2188. self.source_editor_tab = None
  2189. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2190. # VisPy visuals
  2191. if self.is_legacy is False:
  2192. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2193. else:
  2194. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2195. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2196. # ###############################################################################
  2197. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2198. # ############# It's done only once after install ###############
  2199. # ###############################################################################
  2200. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2201. fac_def_from_file = factory_file.read()
  2202. factory_defaults = json.loads(fac_def_from_file)
  2203. # if the file contain an empty dictionary then save the factory defaults into the file
  2204. if not factory_defaults:
  2205. self.save_factory_defaults(silent_message=False)
  2206. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2207. initial_lay = 'compact'
  2208. self.on_layout(lay=initial_lay)
  2209. # Set the combobox in Preferences to the current layout
  2210. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2211. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2212. factory_file.close()
  2213. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  2214. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2215. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2216. # after the first run, this object should be False
  2217. self.defaults["first_run"] = False
  2218. # ###############################################################################
  2219. # ################# ADDING FlatCAM EDITORS section ##############################
  2220. # ###############################################################################
  2221. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2222. # at the first launch of the App , the editors will not be functional.
  2223. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2224. self.exc_editor = FlatCAMExcEditor(self)
  2225. self.grb_editor = FlatCAMGrbEditor(self)
  2226. self.log.debug("Finished adding FlatCAM Editor's.")
  2227. self.set_ui_title(name=_("New Project - Not saved"))
  2228. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2229. current_platform = platform.architecture()[0]
  2230. if current_platform != '64bit':
  2231. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2232. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2233. # ###############################################################################
  2234. # ####################### Finished the CONSTRUCTOR ##############################
  2235. # ###############################################################################
  2236. App.log.debug("END of constructor. Releasing control.")
  2237. # #####################################################################################
  2238. # ########################## SHOW GUI #################################################
  2239. # #####################################################################################
  2240. # if the app is not started as headless, show it
  2241. if self.cmd_line_headless != 1:
  2242. if show_splash:
  2243. # finish the splash
  2244. self.splash.finish(self.ui)
  2245. mgui_settings = QSettings("Open Source", "FlatCAM")
  2246. if mgui_settings.contains("maximized_gui"):
  2247. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2248. if maximized_ui is True:
  2249. self.ui.showMaximized()
  2250. else:
  2251. self.ui.show()
  2252. else:
  2253. self.ui.show()
  2254. if self.defaults["global_systray_icon"]:
  2255. self.trayIcon.show()
  2256. else:
  2257. log.warning("******************* RUNNING HEADLESS *******************")
  2258. # #####################################################################################
  2259. # ########################## START-UP ARGUMENTS #######################################
  2260. # #####################################################################################
  2261. # test if the program was started with a script as parameter
  2262. if self.cmd_line_shellvar:
  2263. try:
  2264. cnt = 0
  2265. command_tcl = 0
  2266. for i in self.cmd_line_shellvar.split(','):
  2267. if i is not None:
  2268. # noinspection PyBroadException
  2269. try:
  2270. command_tcl = eval(i)
  2271. except Exception:
  2272. command_tcl = i
  2273. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2274. cnt += 1
  2275. # if there are Windows paths then replace the path separator with a Unix like one
  2276. if sys.platform == 'win32':
  2277. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2278. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2279. except Exception as ext:
  2280. print("ERROR: ", ext)
  2281. sys.exit(2)
  2282. if self.cmd_line_shellfile:
  2283. try:
  2284. if self.ui.shell_dock.isHidden():
  2285. self.ui.shell_dock.show()
  2286. with open(self.cmd_line_shellfile, "r") as myfile:
  2287. if show_splash:
  2288. self.splash.showMessage('%s: %ssec\n%s' % (
  2289. _("Canvas initialization started.\n"
  2290. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2291. _("Executing Tcl Script ...")),
  2292. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2293. color=QtGui.QColor("gray"))
  2294. cmd_line_shellfile_text = myfile.read()
  2295. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2296. except Exception as ext:
  2297. print("ERROR: ", ext)
  2298. sys.exit(2)
  2299. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2300. # the path/file_name must be enclosed in quotes if it contain spaces
  2301. if App.args:
  2302. self.args_at_startup.emit(App.args)
  2303. if self.old_defaults_found is True:
  2304. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2305. "Please reboot the application to update."))
  2306. self.old_defaults_found = False
  2307. @staticmethod
  2308. def copy_and_overwrite(from_path, to_path):
  2309. """
  2310. From here:
  2311. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2312. :param from_path: source path
  2313. :param to_path: destination path
  2314. :return: None
  2315. """
  2316. if os.path.exists(to_path):
  2317. shutil.rmtree(to_path)
  2318. try:
  2319. shutil.copytree(from_path, to_path)
  2320. except FileNotFoundError:
  2321. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2322. shutil.copytree(from_new_path, to_path)
  2323. def on_startup_args(self, args, silent=False):
  2324. """
  2325. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2326. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2327. :param args: a list containing the application args at startup
  2328. :return: None
  2329. """
  2330. if args is not None:
  2331. args_to_process = args
  2332. else:
  2333. args_to_process = App.args
  2334. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2335. for argument in args_to_process:
  2336. if '.FlatPrj'.lower() in argument.lower():
  2337. try:
  2338. project_name = str(argument)
  2339. if project_name == "":
  2340. if silent is False:
  2341. self.inform.emit(_("Open cancelled."))
  2342. else:
  2343. # self.open_project(project_name)
  2344. run_from_arg = True
  2345. # self.worker_task.emit({'fcn': self.open_project,
  2346. # 'params': [project_name, run_from_arg]})
  2347. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2348. except Exception as e:
  2349. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2350. elif '.FlatConfig'.lower() in argument.lower():
  2351. try:
  2352. file_name = str(argument)
  2353. if file_name == "":
  2354. if silent is False:
  2355. self.inform.emit(_("Open Config file failed."))
  2356. else:
  2357. run_from_arg = True
  2358. # self.worker_task.emit({'fcn': self.open_config_file,
  2359. # 'params': [file_name, run_from_arg]})
  2360. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2361. except Exception as e:
  2362. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2363. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2364. try:
  2365. file_name = str(argument)
  2366. if file_name == "":
  2367. if silent is False:
  2368. self.inform.emit(_("Open Script file failed."))
  2369. else:
  2370. if silent is False:
  2371. self.on_fileopenscript(name=file_name)
  2372. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2373. self.on_filerunscript(name=file_name)
  2374. except Exception as e:
  2375. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2376. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2377. log.debug("App.on_startup_args() --> Quit event.")
  2378. sys.exit()
  2379. elif 'save'.lower() in argument.lower():
  2380. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2381. self.save_defaults()
  2382. else:
  2383. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2384. proc_arg = argument.lower()
  2385. for ext in exc_list:
  2386. proc_ext = ext.replace(' ', '')
  2387. proc_ext = '.%s' % proc_ext
  2388. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2389. file_name = str(argument)
  2390. if file_name == "":
  2391. if silent is False:
  2392. self.inform.emit(_("Open Excellon file failed."))
  2393. else:
  2394. self.on_fileopenexcellon(name=file_name)
  2395. return
  2396. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2397. for ext in gco_list:
  2398. proc_ext = ext.replace(' ', '')
  2399. proc_ext = '.%s' % proc_ext
  2400. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2401. file_name = str(argument)
  2402. if file_name == "":
  2403. if silent is False:
  2404. self.inform.emit(_("Open GCode file failed."))
  2405. else:
  2406. self.on_fileopengcode(name=file_name)
  2407. return
  2408. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2409. for ext in grb_list:
  2410. proc_ext = ext.replace(' ', '')
  2411. proc_ext = '.%s' % proc_ext
  2412. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2413. file_name = str(argument)
  2414. if file_name == "":
  2415. if silent is False:
  2416. self.inform.emit(_("Open Gerber file failed."))
  2417. else:
  2418. self.on_fileopengerber(name=file_name)
  2419. return
  2420. # if it reached here without already returning then the app was registered with a file that it does not
  2421. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2422. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2423. # for arg in args_to_process:
  2424. # if 'FlatCAM.exe' in arg:
  2425. # continue
  2426. # else:
  2427. # sys.exit(2)
  2428. def set_ui_title(self, name):
  2429. """
  2430. Sets the title of the main window.
  2431. :param name: String that store the project path and project name
  2432. :return: None
  2433. """
  2434. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2435. (self.version,
  2436. ('BETA' if self.beta else ''),
  2437. platform.architecture()[0],
  2438. self.engine,
  2439. name)
  2440. )
  2441. def on_theme_change(self, val):
  2442. t_settings = QSettings("Open Source", "FlatCAM")
  2443. t_settings.setValue('theme', val)
  2444. # This will write the setting to the platform specific storage.
  2445. del t_settings
  2446. self.on_app_restart()
  2447. def on_app_restart(self):
  2448. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2449. # be left in the SySTray
  2450. try:
  2451. self.trayIcon.hide()
  2452. except Exception:
  2453. pass
  2454. fcTranslate.restart_program(app=self)
  2455. def defaults_read_form(self):
  2456. """
  2457. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2458. :return: None
  2459. """
  2460. for option in self.defaults_form_fields:
  2461. try:
  2462. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2463. except Exception as e:
  2464. log.debug("App.defaults_read_form() --> %s" % str(e))
  2465. def defaults_write_form(self, factor=None, fl_units=None):
  2466. """
  2467. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2468. self.defaults dictionary.
  2469. :param factor: will apply a factor to the values that written in the GUI elements
  2470. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2471. :return: None
  2472. """
  2473. for option in self.defaults:
  2474. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2475. # try:
  2476. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2477. # except KeyError:
  2478. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2479. # # TODO: Rethink this?
  2480. # pass
  2481. def defaults_write_form_field(self, field, factor=None, units=None):
  2482. """
  2483. Basically it is the worker in the self.defaults_write_form()
  2484. :param field: the GUI element in Preferences GUI to be updated
  2485. :param factor: factor to be applied to the field parameter
  2486. :param units: current FLatCAM measuring units
  2487. :return: None, it updates GUI elements
  2488. """
  2489. try:
  2490. if factor is None:
  2491. if units is None:
  2492. self.defaults_form_fields[field].set_value(self.defaults[field])
  2493. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2494. self.defaults_form_fields[field].set_value(self.defaults[field])
  2495. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2496. self.defaults_form_fields[field].set_value(self.defaults[field])
  2497. else:
  2498. if units is None:
  2499. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2500. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2501. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2502. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2503. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2504. except KeyError:
  2505. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2506. # TODO: Rethink this?
  2507. pass
  2508. except AttributeError:
  2509. log.debug(field)
  2510. def clear_pool(self):
  2511. """
  2512. Clear the multiprocessing pool and calls garbage collector.
  2513. :return: None
  2514. """
  2515. self.pool.close()
  2516. self.pool = Pool()
  2517. self.pool_recreated.emit(self.pool)
  2518. gc.collect()
  2519. def install_tools(self):
  2520. """
  2521. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2522. Instantiation of the Tools classes.
  2523. The order that the tools are installed is important as they can depend on each other install position.
  2524. :return: None
  2525. """
  2526. self.dblsidedtool = DblSidedTool(self)
  2527. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2528. self.cal_exc_tool = ToolCalibrateExcellon(self)
  2529. self.cal_exc_tool.install(icon=QtGui.QIcon('share/drill16.png'), pos=self.ui.menutool,
  2530. before=self.dblsidedtool.menuAction,
  2531. separator=False)
  2532. self.distance_tool = Distance(self)
  2533. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2534. before=self.ui.menueditorigin,
  2535. separator=False)
  2536. self.distance_min_tool = DistanceMin(self)
  2537. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2538. before=self.ui.menueditorigin,
  2539. separator=True)
  2540. self.panelize_tool = Panelize(self)
  2541. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2542. self.film_tool = Film(self)
  2543. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2544. self.paste_tool = SolderPaste(self)
  2545. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2546. self.calculator_tool = ToolCalculator(self)
  2547. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2548. self.sub_tool = ToolSub(self)
  2549. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2550. self.rules_tool = RulesCheck(self)
  2551. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2552. self.optimal_tool = ToolOptimal(self)
  2553. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2554. self.move_tool = ToolMove(self)
  2555. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2556. before=self.ui.menueditorigin, separator=True)
  2557. self.cutout_tool = CutOut(self)
  2558. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2559. before=self.sub_tool.menuAction)
  2560. self.ncclear_tool = NonCopperClear(self)
  2561. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2562. before=self.sub_tool.menuAction, separator=True)
  2563. self.paint_tool = ToolPaint(self)
  2564. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2565. before=self.sub_tool.menuAction, separator=True)
  2566. self.copper_thieving_tool = ToolCopperThieving(self)
  2567. self.copper_thieving_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2568. self.fiducial_tool = ToolFiducials(self)
  2569. self.fiducial_tool.install(icon=QtGui.QIcon('share/fiducials_32.png'), pos=self.ui.menutool)
  2570. self.qrcode_tool = QRCode(self)
  2571. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2572. self.transform_tool = ToolTransform(self)
  2573. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2574. self.properties_tool = Properties(self)
  2575. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2576. self.pdf_tool = ToolPDF(self)
  2577. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2578. separator=True)
  2579. self.image_tool = ToolImage(self)
  2580. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2581. separator=True)
  2582. self.pcb_wizard_tool = PcbWizard(self)
  2583. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2584. self.log.debug("Tools are installed.")
  2585. def remove_tools(self):
  2586. """
  2587. Will remove all the actions in the Tool menu.
  2588. :return: None
  2589. """
  2590. for act in self.ui.menutool.actions():
  2591. self.ui.menutool.removeAction(act)
  2592. def init_tools(self):
  2593. """
  2594. Initialize the Tool tab in the notebook side of the central widget.
  2595. Remove the actions in the Tools menu.
  2596. Instantiate again the FlatCAM tools (plugins).
  2597. All this is required when changing the layout: standard, compact etc.
  2598. :return: None
  2599. """
  2600. log.debug("init_tools()")
  2601. # delete the data currently in the Tools Tab and the Tab itself
  2602. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2603. if widget is not None:
  2604. widget.deleteLater()
  2605. self.ui.notebook.removeTab(2)
  2606. # rebuild the Tools Tab
  2607. self.ui.tool_tab = QtWidgets.QWidget()
  2608. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2609. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2610. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2611. self.ui.tool_scroll_area = VerticalScrollArea()
  2612. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2613. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2614. # first remove all of them
  2615. self.remove_tools()
  2616. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2617. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2618. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2619. # third install all of them
  2620. self.install_tools()
  2621. self.log.debug("Tools are initialized.")
  2622. # def parse_system_fonts(self):
  2623. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2624. # 'params': []})
  2625. def connect_toolbar_signals(self):
  2626. """
  2627. Reconnect the signals to the actions in the toolbar.
  2628. This has to be done each time after the FlatCAM tools are removed/installed.
  2629. :return: None
  2630. """
  2631. # Toolbar
  2632. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2633. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2634. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2635. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2636. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2637. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2638. self.ui.replot_btn.triggered.connect(self.plot_all)
  2639. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2640. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2641. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2642. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2643. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2644. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2645. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2646. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2647. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2648. self.ui.delete_btn.triggered.connect(self.on_delete)
  2649. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2650. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2651. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2652. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2653. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2654. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2655. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2656. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2657. # Tools Toolbar Signals
  2658. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2659. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2660. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2661. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2662. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2663. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2664. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2665. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2666. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2667. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2668. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2669. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2670. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2671. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2672. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2673. def object2editor(self):
  2674. """
  2675. Send the current Geometry or Excellon object (if any) into the it's editor.
  2676. :return: None
  2677. """
  2678. self.report_usage("object2editor()")
  2679. # disable the objects menu as it may interfere with the Editors
  2680. self.ui.menuobjects.setDisabled(True)
  2681. edited_object = self.collection.get_active()
  2682. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2683. isinstance(edited_object, FlatCAMExcellon):
  2684. pass
  2685. else:
  2686. self.inform.emit('[WARNING_NOTCL] %s' %
  2687. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2688. return
  2689. if isinstance(edited_object, FlatCAMGeometry):
  2690. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2691. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2692. # we set the notebook to hidden
  2693. self.ui.splitter.setSizes([0, 1])
  2694. if edited_object.multigeo is True:
  2695. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2696. if len(sel_rows) > 1:
  2697. self.inform.emit('[WARNING_NOTCL] %s' %
  2698. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2699. "is not possible.\n"
  2700. "Edit only one geometry at a time."))
  2701. # determine the tool dia of the selected tool
  2702. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2703. # now find the key in the edited_object.tools that has this tooldia
  2704. multi_tool = 1
  2705. for tool in edited_object.tools:
  2706. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2707. multi_tool = tool
  2708. break
  2709. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2710. else:
  2711. self.geo_editor.edit_fcgeometry(edited_object)
  2712. # set call source to the Editor we go into
  2713. self.call_source = 'geo_editor'
  2714. elif isinstance(edited_object, FlatCAMExcellon):
  2715. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2716. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2717. if self.ui.splitter.sizes()[0] == 0:
  2718. self.ui.splitter.setSizes([1, 1])
  2719. self.exc_editor.edit_fcexcellon(edited_object)
  2720. # set call source to the Editor we go into
  2721. self.call_source = 'exc_editor'
  2722. elif isinstance(edited_object, FlatCAMGerber):
  2723. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2724. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2725. if self.ui.splitter.sizes()[0] == 0:
  2726. self.ui.splitter.setSizes([1, 1])
  2727. self.grb_editor.edit_fcgerber(edited_object)
  2728. # set call source to the Editor we go into
  2729. self.call_source = 'grb_editor'
  2730. # make sure that we can't select another object while in Editor Mode:
  2731. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2732. self.ui.project_frame.setDisabled(True)
  2733. # delete any selection shape that might be active as they are not relevant in Editor
  2734. self.delete_selection_shape()
  2735. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2736. self.ui.plot_tab_area.protectTab(0)
  2737. self.inform.emit('[WARNING_NOTCL] %s' %
  2738. _("Editor is activated ..."))
  2739. self.should_we_save = True
  2740. def editor2object(self, cleanup=None):
  2741. """
  2742. Transfers the Geometry or Excellon from it's editor to the current object.
  2743. :return: None
  2744. """
  2745. self.report_usage("editor2object()")
  2746. # re-enable the objects menu that was disabled on entry in Editor mode
  2747. self.ui.menuobjects.setDisabled(False)
  2748. # do not update a geometry or excellon object unless it comes out of an editor
  2749. if self.call_source != 'app':
  2750. edited_obj = self.collection.get_active()
  2751. if cleanup is None:
  2752. msgbox = QtWidgets.QMessageBox()
  2753. msgbox.setText(_("Do you want to save the edited object?"))
  2754. msgbox.setWindowTitle(_("Close Editor"))
  2755. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2756. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2757. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2758. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2759. msgbox.setDefaultButton(bt_yes)
  2760. msgbox.exec_()
  2761. response = msgbox.clickedButton()
  2762. if response == bt_yes:
  2763. # clean the Tools Tab
  2764. self.ui.tool_scroll_area.takeWidget()
  2765. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2766. self.ui.notebook.setTabText(2, "Tool")
  2767. if isinstance(edited_obj, FlatCAMGeometry):
  2768. obj_type = "Geometry"
  2769. if cleanup is None:
  2770. self.geo_editor.update_fcgeometry(edited_obj)
  2771. self.geo_editor.update_options(edited_obj)
  2772. self.geo_editor.deactivate()
  2773. # update the geo object options so it is including the bounding box values
  2774. try:
  2775. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2776. edited_obj.options['xmin'] = xmin
  2777. edited_obj.options['ymin'] = ymin
  2778. edited_obj.options['xmax'] = xmax
  2779. edited_obj.options['ymax'] = ymax
  2780. except AttributeError as e:
  2781. self.inform.emit('[WARNING] %s' %
  2782. _("Object empty after edit."))
  2783. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2784. elif isinstance(edited_obj, FlatCAMGerber):
  2785. obj_type = "Gerber"
  2786. if cleanup is None:
  2787. self.grb_editor.update_fcgerber()
  2788. self.grb_editor.update_options(edited_obj)
  2789. self.grb_editor.deactivate_grb_editor()
  2790. # delete the old object (the source object) if it was an empty one
  2791. try:
  2792. if len(edited_obj.solid_geometry) == 0:
  2793. old_name = edited_obj.options['name']
  2794. self.collection.set_active(old_name)
  2795. self.collection.delete_active()
  2796. except TypeError:
  2797. # if the solid_geometry is a single Polygon the len() will not work
  2798. # in any case, falling here means that we have something in the solid_geometry, even if only
  2799. # a single Polygon, therefore we pass this
  2800. pass
  2801. # restore GUI to the Selected TAB
  2802. # Remove anything else in the GUI
  2803. self.ui.selected_scroll_area.takeWidget()
  2804. # Switch notebook to Selected page
  2805. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2806. elif isinstance(edited_obj, FlatCAMExcellon):
  2807. obj_type = "Excellon"
  2808. if cleanup is None:
  2809. self.exc_editor.update_fcexcellon(edited_obj)
  2810. self.exc_editor.update_options(edited_obj)
  2811. self.exc_editor.deactivate()
  2812. # delete the old object (the source object) if it was an empty one
  2813. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2814. old_name = edited_obj.options['name']
  2815. self.collection.set_active(old_name)
  2816. self.collection.delete_active()
  2817. # restore GUI to the Selected TAB
  2818. # Remove anything else in the GUI
  2819. self.ui.tool_scroll_area.takeWidget()
  2820. # Switch notebook to Selected page
  2821. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2822. else:
  2823. self.inform.emit('[WARNING_NOTCL] %s' %
  2824. _("Select a Gerber, Geometry or Excellon Object to update."))
  2825. return
  2826. self.inform.emit('[selected] %s %s' %
  2827. (obj_type, _("is updated, returning to App...")))
  2828. elif response == bt_no:
  2829. # clean the Tools Tab
  2830. self.ui.tool_scroll_area.takeWidget()
  2831. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2832. self.ui.notebook.setTabText(2, "Tool")
  2833. if isinstance(edited_obj, FlatCAMGeometry):
  2834. self.geo_editor.deactivate()
  2835. elif isinstance(edited_obj, FlatCAMGerber):
  2836. self.grb_editor.deactivate_grb_editor()
  2837. elif isinstance(edited_obj, FlatCAMExcellon):
  2838. self.exc_editor.deactivate()
  2839. # set focus on the project tab
  2840. else:
  2841. self.inform.emit('[WARNING_NOTCL] %s' %
  2842. _("Select a Gerber, Geometry or Excellon Object to update."))
  2843. return
  2844. edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2845. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2846. elif response == bt_cancel:
  2847. return
  2848. else:
  2849. if isinstance(edited_obj, FlatCAMGeometry):
  2850. self.geo_editor.deactivate()
  2851. elif isinstance(edited_obj, FlatCAMGerber):
  2852. self.grb_editor.deactivate_grb_editor()
  2853. elif isinstance(edited_obj, FlatCAMExcellon):
  2854. self.exc_editor.deactivate()
  2855. else:
  2856. self.inform.emit('[WARNING_NOTCL] %s' %
  2857. _("Select a Gerber, Geometry or Excellon Object to update."))
  2858. return
  2859. # if notebook is hidden we show it
  2860. if self.ui.splitter.sizes()[0] == 0:
  2861. self.ui.splitter.setSizes([1, 1])
  2862. # restore the call_source to app
  2863. self.call_source = 'app'
  2864. edited_obj.plot()
  2865. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2866. self.ui.plot_tab_area.protectTab(0)
  2867. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2868. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2869. self.ui.project_frame.setDisabled(False)
  2870. def get_last_folder(self):
  2871. """
  2872. Get the folder path from where the last file was opened.
  2873. :return: String, last opened folder path
  2874. """
  2875. return self.defaults["global_last_folder"]
  2876. def get_last_save_folder(self):
  2877. """
  2878. Get the folder path from where the last file was saved.
  2879. :return: String, last saved folder path
  2880. """
  2881. loc = self.defaults["global_last_save_folder"]
  2882. if loc is None:
  2883. loc = self.defaults["global_last_folder"]
  2884. if loc is None:
  2885. loc = os.path.dirname(__file__)
  2886. return loc
  2887. def report_usage(self, resource):
  2888. """
  2889. Increments usage counter for the given resource
  2890. in self.defaults['global_stats'].
  2891. :param resource: Name of the resource.
  2892. :return: None
  2893. """
  2894. if resource in self.defaults['global_stats']:
  2895. self.defaults['global_stats'][resource] += 1
  2896. else:
  2897. self.defaults['global_stats'][resource] = 1
  2898. def init_tcl(self):
  2899. """
  2900. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2901. :return: None
  2902. """
  2903. if hasattr(self, 'tcl') and self.tcl is not None:
  2904. # self.tcl = None
  2905. # TODO we need to clean non default variables and procedures here
  2906. # new object cannot be used here as it will not remember values created for next passes,
  2907. # because tcl was execudted in old instance of TCL
  2908. pass
  2909. else:
  2910. self.tcl = tk.Tcl()
  2911. self.setup_shell()
  2912. self.log.debug("TCL Shell has been initialized.")
  2913. # TODO: This shouldn't be here.
  2914. class TclErrorException(Exception):
  2915. """
  2916. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2917. """
  2918. pass
  2919. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2920. """
  2921. Shows a message on the FlatCAM Shell
  2922. :param msg: Message to display.
  2923. :param show: Opens the shell.
  2924. :param error: Shows the message as an error.
  2925. :param warning: Shows the message as an warning.
  2926. :param success: Shows the message as an success.
  2927. :param selected: Indicate that something was selected on canvas
  2928. :return: None
  2929. """
  2930. if show:
  2931. self.ui.shell_dock.show()
  2932. try:
  2933. if error:
  2934. self.shell.append_error(msg + "\n")
  2935. elif warning:
  2936. self.shell.append_warning(msg + "\n")
  2937. elif success:
  2938. self.shell.append_success(msg + "\n")
  2939. elif selected:
  2940. self.shell.append_selected(msg + "\n")
  2941. else:
  2942. self.shell.append_output(msg + "\n")
  2943. except AttributeError:
  2944. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2945. def raise_tcl_unknown_error(self, unknownException):
  2946. """
  2947. Raise exception if is different type than TclErrorException
  2948. this is here mainly to show unknown errors inside TCL shell console.
  2949. :param unknownException:
  2950. :return:
  2951. """
  2952. if not isinstance(unknownException, self.TclErrorException):
  2953. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2954. else:
  2955. raise unknownException
  2956. def display_tcl_error(self, error, error_info=None):
  2957. """
  2958. Escape bracket [ with '\' otherwise there is error
  2959. "ERROR: missing close-bracket" instead of real error
  2960. :param error: it may be text or exception
  2961. :param error_info: Some informations about the error
  2962. :return: None
  2963. """
  2964. if isinstance(error, Exception):
  2965. exc_type, exc_value, exc_traceback = error_info
  2966. if not isinstance(error, self.TclErrorException):
  2967. show_trace = 1
  2968. else:
  2969. show_trace = int(self.defaults['global_verbose_error_level'])
  2970. if show_trace > 0:
  2971. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2972. trc_formated = []
  2973. for a in reversed(trc):
  2974. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2975. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2976. else:
  2977. text = "%s" % error
  2978. else:
  2979. text = error
  2980. text = text.replace('[', '\\[').replace('"', '\\"')
  2981. self.tcl.eval('return -code error "%s"' % text)
  2982. def raise_tcl_error(self, text):
  2983. """
  2984. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2985. :param text: text of error
  2986. :return: raise exception
  2987. """
  2988. self.display_tcl_error(text)
  2989. raise self.TclErrorException(text)
  2990. def exec_command(self, text, no_echo=False):
  2991. """
  2992. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2993. Also handles execution in separated threads
  2994. :param text: FlatCAM TclCommand with parameters
  2995. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2996. will create crashes of the _Expandable_Edit widget
  2997. :return: output if there was any
  2998. """
  2999. self.report_usage('exec_command')
  3000. result = self.exec_command_test(text, False, no_echo=no_echo)
  3001. # MS: added this method call so the geometry is updated once the TCL command is executed
  3002. # if no_plot is None:
  3003. # self.plot_all()
  3004. return result
  3005. def exec_command_test(self, text, reraise=True, no_echo=False):
  3006. """
  3007. Same as exec_command(...) with additional control over exceptions.
  3008. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3009. :param text: Input command
  3010. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  3011. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3012. will create crashes of the _Expandable_Edit widget
  3013. :return: Output from the command
  3014. """
  3015. tcl_command_string = str(text)
  3016. try:
  3017. if no_echo is False:
  3018. self.shell.open_proccessing() # Disables input box.
  3019. result = self.tcl.eval(str(tcl_command_string))
  3020. if result != 'None' and no_echo is False:
  3021. self.shell.append_output(result + '\n')
  3022. except tk.TclError as e:
  3023. # This will display more precise answer if something in TCL shell fails
  3024. result = self.tcl.eval("set errorInfo")
  3025. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3026. if no_echo is False:
  3027. self.shell.append_error('ERROR: ' + result + '\n')
  3028. # Show error in console and just return or in test raise exception
  3029. if reraise:
  3030. raise e
  3031. finally:
  3032. if no_echo is False:
  3033. self.shell.close_proccessing()
  3034. pass
  3035. return result
  3036. # """
  3037. # Code below is unsused. Saved for later.
  3038. # """
  3039. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3040. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3041. # self.log.debug(parts)
  3042. # try:
  3043. # if parts[0] not in commands:
  3044. # self.shell.append_error("Unknown command\n")
  3045. # return
  3046. #
  3047. # #import inspect
  3048. # #inspect.getargspec(someMethod)
  3049. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3050. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3051. # self.shell.append_error(
  3052. # "Command %s takes %d arguments. %d given.\n" %
  3053. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3054. # )
  3055. # return
  3056. #
  3057. # cmdfcn = commands[parts[0]]["fcn"]
  3058. # cmdconv = commands[parts[0]]["converters"]
  3059. # if len(parts) - 1 > 0:
  3060. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3061. # else:
  3062. # retval = cmdfcn()
  3063. # retfcn = commands[parts[0]]["retfcn"]
  3064. # if retval and retfcn(retval):
  3065. # self.shell.append_output(retfcn(retval) + "\n")
  3066. #
  3067. # except Exception as e:
  3068. # #self.shell.append_error(''.join(traceback.format_exc()))
  3069. # #self.shell.append_error("?\n")
  3070. # self.shell.append_error(str(e) + "\n")
  3071. def info(self, msg):
  3072. """
  3073. Informs the user. Normally on the status bar, optionally
  3074. also on the shell.
  3075. :param msg: Text to write.
  3076. :return: None
  3077. """
  3078. # Type of message in brackets at the beginning of the message.
  3079. match = re.search("\[([^\]]+)\](.*)", msg)
  3080. if match:
  3081. level = match.group(1)
  3082. msg_ = match.group(2)
  3083. self.ui.fcinfo.set_status(str(msg_), level=level)
  3084. if level.lower() == "error":
  3085. self.shell_message(msg, error=True, show=True)
  3086. elif level.lower() == "warning":
  3087. self.shell_message(msg, warning=True, show=True)
  3088. elif level.lower() == "error_notcl":
  3089. self.shell_message(msg, error=True, show=False)
  3090. elif level.lower() == "warning_notcl":
  3091. self.shell_message(msg, warning=True, show=False)
  3092. elif level.lower() == "success":
  3093. self.shell_message(msg, success=True, show=False)
  3094. elif level.lower() == "selected":
  3095. self.shell_message(msg, selected=True, show=False)
  3096. else:
  3097. self.shell_message(msg, show=False)
  3098. else:
  3099. self.ui.fcinfo.set_status(str(msg), level="info")
  3100. # make sure that if the message is to clear the infobar with a space
  3101. # is not printed over and over on the shell
  3102. if msg != '':
  3103. self.shell_message(msg)
  3104. def restore_toolbar_view(self):
  3105. """
  3106. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3107. was saved in the defaults dictionary.
  3108. :return: None
  3109. """
  3110. tb = self.defaults["global_toolbar_view"]
  3111. if tb & 1:
  3112. self.ui.toolbarfile.setVisible(True)
  3113. else:
  3114. self.ui.toolbarfile.setVisible(False)
  3115. if tb & 2:
  3116. self.ui.toolbargeo.setVisible(True)
  3117. else:
  3118. self.ui.toolbargeo.setVisible(False)
  3119. if tb & 4:
  3120. self.ui.toolbarview.setVisible(True)
  3121. else:
  3122. self.ui.toolbarview.setVisible(False)
  3123. if tb & 8:
  3124. self.ui.toolbartools.setVisible(True)
  3125. else:
  3126. self.ui.toolbartools.setVisible(False)
  3127. if tb & 16:
  3128. self.ui.exc_edit_toolbar.setVisible(True)
  3129. else:
  3130. self.ui.exc_edit_toolbar.setVisible(False)
  3131. if tb & 32:
  3132. self.ui.geo_edit_toolbar.setVisible(True)
  3133. else:
  3134. self.ui.geo_edit_toolbar.setVisible(False)
  3135. if tb & 64:
  3136. self.ui.grb_edit_toolbar.setVisible(True)
  3137. else:
  3138. self.ui.grb_edit_toolbar.setVisible(False)
  3139. if tb & 128:
  3140. self.ui.snap_toolbar.setVisible(True)
  3141. else:
  3142. self.ui.snap_toolbar.setVisible(False)
  3143. if tb & 256:
  3144. self.ui.toolbarshell.setVisible(True)
  3145. else:
  3146. self.ui.toolbarshell.setVisible(False)
  3147. def load_defaults(self, filename):
  3148. """
  3149. Loads the aplication's default settings from current_defaults.FlatConfig into
  3150. ``self.defaults``.
  3151. :return: None
  3152. """
  3153. try:
  3154. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3155. options = f.read()
  3156. f.close()
  3157. except IOError:
  3158. self.log.error("Could not load defaults file.")
  3159. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3160. # in case the defaults file can't be loaded, show all toolbars
  3161. self.defaults["global_toolbar_view"] = 511
  3162. return
  3163. try:
  3164. defaults = json.loads(options)
  3165. except Exception:
  3166. # in case the defaults file can't be loaded, show all toolbars
  3167. self.defaults["global_toolbar_view"] = 511
  3168. e = sys.exc_info()[0]
  3169. App.log.error(str(e))
  3170. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3171. return
  3172. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3173. for k, v in defaults.items():
  3174. if k in self.defaults:
  3175. self.defaults[k] = v
  3176. # delete old factory defaults
  3177. try:
  3178. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3179. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3180. os.remove(fact_def_file_path)
  3181. # recreate a new factory defaults file and save the factory defaults data into it
  3182. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3183. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3184. f_f_def_s.close()
  3185. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  3186. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3187. except Exception as e:
  3188. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3189. self.old_defaults_found = True
  3190. else:
  3191. self.defaults.update(defaults)
  3192. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3193. def on_import_preferences(self):
  3194. """
  3195. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3196. ``self.defaults``.
  3197. :return: None
  3198. """
  3199. self.report_usage("on_import_preferences")
  3200. App.log.debug("on_import_preferences()")
  3201. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3202. try:
  3203. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3204. directory=self.data_path,
  3205. filter=filter_)
  3206. except TypeError:
  3207. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3208. filter=filter_)
  3209. filename = str(filename)
  3210. if filename == "":
  3211. self.inform.emit('[WARNING_NOTCL] %s' %
  3212. _("FlatCAM preferences import cancelled."))
  3213. else:
  3214. try:
  3215. f = open(filename)
  3216. options = f.read()
  3217. f.close()
  3218. except IOError:
  3219. self.log.error("Could not load defaults file.")
  3220. self.inform.emit('[ERROR_NOTCL] %s' %
  3221. _("Could not load defaults file."))
  3222. return
  3223. try:
  3224. defaults_from_file = json.loads(options)
  3225. except Exception:
  3226. e = sys.exc_info()[0]
  3227. App.log.error(str(e))
  3228. self.inform.emit('[ERROR_NOTCL] %s' %
  3229. _("Failed to parse defaults file."))
  3230. return
  3231. self.defaults.update(defaults_from_file)
  3232. self.on_preferences_edited()
  3233. self.inform.emit('[success] %s: %s' %
  3234. (_("Imported Defaults from"), filename))
  3235. def on_export_preferences(self):
  3236. """
  3237. Save the defaults dictionary to a file.
  3238. :return: None
  3239. """
  3240. self.report_usage("on_export_preferences")
  3241. App.log.debug("on_export_preferences()")
  3242. defaults_file_content = None
  3243. self.date = str(datetime.today()).rpartition('.')[0]
  3244. self.date = ''.join(c for c in self.date if c not in ':-')
  3245. self.date = self.date.replace(' ', '_')
  3246. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3247. try:
  3248. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3249. caption=_("Export FlatCAM Preferences"),
  3250. directory=self.data_path + '/preferences_' + self.date,
  3251. filter=filter__
  3252. )
  3253. except TypeError:
  3254. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3255. filter=filter__)
  3256. filename = str(filename)
  3257. defaults_from_file = {}
  3258. if filename == "":
  3259. self.inform.emit('[WARNING_NOTCL] %s' %
  3260. _("FlatCAM preferences export cancelled."))
  3261. return
  3262. else:
  3263. try:
  3264. f = open(filename, 'w')
  3265. defaults_file_content = f.read()
  3266. f.close()
  3267. except PermissionError:
  3268. self.inform.emit('[WARNING] %s' %
  3269. _("Permission denied, saving not possible.\n"
  3270. "Most likely another app is holding the file open and not accessible."))
  3271. return
  3272. except IOError:
  3273. App.log.debug('Creating a new preferences file ...')
  3274. f = open(filename, 'w')
  3275. json.dump({}, f)
  3276. f.close()
  3277. except Exception:
  3278. e = sys.exc_info()[0]
  3279. App.log.error("Could not load defaults file.")
  3280. App.log.error(str(e))
  3281. self.inform.emit('[ERROR_NOTCL] %s' %
  3282. _("Could not load preferences file."))
  3283. return
  3284. try:
  3285. defaults_from_file = json.loads(defaults_file_content)
  3286. except Exception:
  3287. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3288. # Update options
  3289. self.defaults_read_form()
  3290. defaults_from_file.update(self.defaults)
  3291. self.propagate_defaults(silent=True)
  3292. # Save update options
  3293. try:
  3294. f = open(filename, "w")
  3295. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3296. f.close()
  3297. except Exception:
  3298. self.inform.emit('[ERROR_NOTCL] %s' %
  3299. _("Failed to write defaults to file."))
  3300. return
  3301. if self.defaults["global_open_style"] is False:
  3302. self.file_opened.emit("preferences", filename)
  3303. self.file_saved.emit("preferences", filename)
  3304. self.inform.emit('[success] %s: %s' %
  3305. (_("Exported preferences to"), filename))
  3306. def on_preferences_open_folder(self):
  3307. """
  3308. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3309. :return: None
  3310. """
  3311. self.report_usage("on_preferences_open_folder()")
  3312. if sys.platform == 'win32':
  3313. subprocess.Popen('explorer %s' % self.data_path)
  3314. elif sys.platform == 'darwin':
  3315. os.system('open "%s"' % self.data_path)
  3316. else:
  3317. subprocess.Popen(['xdg-open', self.data_path])
  3318. self.inform.emit('[success] %s' %
  3319. _("FlatCAM Preferences Folder opened."))
  3320. def save_geometry(self, x, y, width, height, notebook_width):
  3321. """
  3322. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3323. launch of the application.
  3324. :param x: X position of the main window
  3325. :param y: Y position of the main window
  3326. :param width: width of the main window
  3327. :param height: height of the main window
  3328. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3329. :return: None
  3330. """
  3331. self.defaults["global_def_win_x"] = x
  3332. self.defaults["global_def_win_y"] = y
  3333. self.defaults["global_def_win_w"] = width
  3334. self.defaults["global_def_win_h"] = height
  3335. self.defaults["global_def_notebook_width"] = notebook_width
  3336. self.save_defaults()
  3337. def restore_main_win_geom(self):
  3338. try:
  3339. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3340. self.defaults["global_def_win_y"],
  3341. self.defaults["global_def_win_w"],
  3342. self.defaults["global_def_win_h"])
  3343. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3344. except KeyError as e:
  3345. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3346. def message_dialog(self, title, message, kind="info"):
  3347. """
  3348. Builds and show a custom QMessageBox to be used in FlatCAM.
  3349. :param title: title of the QMessageBox
  3350. :param message: message to be displayed
  3351. :param kind: type of QMessageBox; will display a specific icon.
  3352. :return:
  3353. """
  3354. icon = {"info": QtWidgets.QMessageBox.Information,
  3355. "warning": QtWidgets.QMessageBox.Warning,
  3356. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3357. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3358. dlg.setText(message)
  3359. dlg.exec_()
  3360. def register_recent(self, kind, filename):
  3361. """
  3362. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3363. dictionary.
  3364. :param kind: type of file that was opened
  3365. :param filename: the path and file name for the file that was opened
  3366. :return:
  3367. """
  3368. self.log.debug("register_recent()")
  3369. self.log.debug(" %s" % kind)
  3370. self.log.debug(" %s" % filename)
  3371. record = {'kind': str(kind), 'filename': str(filename)}
  3372. if record in self.recent:
  3373. return
  3374. if record in self.recent_projects:
  3375. return
  3376. if record['kind'] == 'project':
  3377. self.recent_projects.insert(0, record)
  3378. else:
  3379. self.recent.insert(0, record)
  3380. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3381. self.recent.pop()
  3382. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3383. self.recent_projects.pop()
  3384. try:
  3385. f = open(self.data_path + '/recent.json', 'w')
  3386. except IOError:
  3387. App.log.error("Failed to open recent items file for writing.")
  3388. self.inform.emit('[ERROR_NOTCL] %s' %
  3389. _('Failed to open recent files file for writing.'))
  3390. return
  3391. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3392. f.close()
  3393. try:
  3394. fp = open(self.data_path + '/recent_projects.json', 'w')
  3395. except IOError:
  3396. App.log.error("Failed to open recent items file for writing.")
  3397. self.inform.emit('[ERROR_NOTCL] %s' %
  3398. _('Failed to open recent projects file for writing.'))
  3399. return
  3400. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3401. fp.close()
  3402. # Re-build the recent items menu
  3403. self.setup_recent_items()
  3404. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3405. """
  3406. Creates a new specialized FlatCAMObj and attaches it to the application,
  3407. this is, updates the GUI accordingly, any other records and plots it.
  3408. This method is thread-safe.
  3409. Notes:
  3410. * If the name is in use, the self.collection will modify it
  3411. when appending it to the collection. There is no need to handle
  3412. name conflicts here.
  3413. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3414. :type kind: str
  3415. :param name: Name for the object.
  3416. :type name: str
  3417. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3418. The function is called with 2 parameters: the new object and the App instance.
  3419. :type initialize: function
  3420. :param active:
  3421. :param fit:
  3422. :param plot: If to plot the resulting object
  3423. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3424. self.colleaction
  3425. :return: None
  3426. :rtype: None
  3427. """
  3428. App.log.debug("new_object()")
  3429. obj_plot = plot
  3430. obj_autoselected = autoselected
  3431. t0 = time.time() # Debug
  3432. # ## Create object
  3433. classdict = {
  3434. "gerber": FlatCAMGerber,
  3435. "excellon": FlatCAMExcellon,
  3436. "cncjob": FlatCAMCNCjob,
  3437. "geometry": FlatCAMGeometry,
  3438. "script": FlatCAMScript,
  3439. "document": FlatCAMDocument
  3440. }
  3441. App.log.debug("Calling object constructor...")
  3442. # Object creation/instantiation
  3443. obj = classdict[kind](name)
  3444. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3445. # IMPORTANT
  3446. # The key names in defaults and options dictionary's are not random:
  3447. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3448. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3449. # copied to self.options. After that, below, depending on the type of
  3450. # object that is created, it will strip the name of the object and the underline (if the original key was
  3451. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3452. # "toolchange"
  3453. for option in self.options:
  3454. if option.find(kind + "_") == 0:
  3455. oname = option[len(kind) + 1:]
  3456. obj.options[oname] = self.options[option]
  3457. obj.isHovering = False
  3458. obj.notHovering = True
  3459. # Initialize as per user request
  3460. # User must take care to implement initialize
  3461. # in a thread-safe way as is is likely that we
  3462. # have been invoked in a separate thread.
  3463. t1 = time.time()
  3464. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3465. try:
  3466. return_value = initialize(obj, self)
  3467. except Exception as e:
  3468. msg = '[ERROR_NOTCL] %s' % \
  3469. _("An internal error has ocurred. See shell.\n")
  3470. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3471. msg += traceback.format_exc()
  3472. self.inform.emit(msg)
  3473. # if str(e) == "Empty Geometry":
  3474. # self.inform.emit("[ERROR_NOTCL] )
  3475. # else:
  3476. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3477. return "fail"
  3478. t2 = time.time()
  3479. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3480. if return_value == 'fail':
  3481. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3482. return "fail"
  3483. # Check units and convert if necessary
  3484. # This condition CAN be true because initialize() can change obj.units
  3485. if self.options["units"].upper() != obj.units.upper():
  3486. self.inform.emit('%s: %s' %
  3487. (_("Converting units to "), self.options["units"]))
  3488. obj.convert_units(self.options["units"])
  3489. t3 = time.time()
  3490. self.log.debug("%f seconds converting units." % (t3 - t2))
  3491. # Create the bounding box for the object and then add the results to the obj.options
  3492. # But not for Scripts or for Documents
  3493. if kind != 'document' and kind != 'script':
  3494. try:
  3495. xmin, ymin, xmax, ymax = obj.bounds()
  3496. obj.options['xmin'] = xmin
  3497. obj.options['ymin'] = ymin
  3498. obj.options['xmax'] = xmax
  3499. obj.options['ymax'] = ymax
  3500. except Exception as e:
  3501. log.warning("The object has no bounds properties. %s" % str(e))
  3502. return "fail"
  3503. # update the KeyWords list with the name of the file
  3504. self.myKeywords.append(obj.options['name'])
  3505. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3506. # Move the object to the main thread and let the app know that it is available.
  3507. obj.moveToThread(self.main_thread)
  3508. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3509. return obj
  3510. def new_excellon_object(self):
  3511. """
  3512. Creates a new, blank Excellon object.
  3513. :return: None
  3514. """
  3515. self.report_usage("new_excellon_object()")
  3516. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3517. def new_geometry_object(self):
  3518. """
  3519. Creates a new, blank and single-tool Geometry object.
  3520. :return: None
  3521. """
  3522. self.report_usage("new_geometry_object()")
  3523. def initialize(obj, app):
  3524. obj.multitool = False
  3525. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3526. def new_gerber_object(self):
  3527. """
  3528. Creates a new, blank Gerber object.
  3529. :return: None
  3530. """
  3531. self.report_usage("new_gerber_object()")
  3532. def initialize(grb_obj, app):
  3533. grb_obj.multitool = False
  3534. grb_obj.source_file = []
  3535. grb_obj.multigeo = False
  3536. grb_obj.follow = False
  3537. grb_obj.apertures = {}
  3538. grb_obj.solid_geometry = []
  3539. try:
  3540. grb_obj.options['xmin'] = 0
  3541. grb_obj.options['ymin'] = 0
  3542. grb_obj.options['xmax'] = 0
  3543. grb_obj.options['ymax'] = 0
  3544. except KeyError:
  3545. pass
  3546. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3547. def new_script_object(self, name=None, text=None):
  3548. """
  3549. Creates a new, blank TCL Script object.
  3550. :param name: a name for the new object
  3551. :param text: pass a source file to the newly created script to be loaded in it
  3552. :return: None
  3553. """
  3554. self.report_usage("new_script_object()")
  3555. if text is not None:
  3556. new_source_file = text
  3557. else:
  3558. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3559. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3560. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3561. "ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3562. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3563. "ListSys, MillDrills,\n"\
  3564. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3565. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3566. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3567. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3568. "# SubtractRectangle, Version, WriteGCode\n"
  3569. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3570. '# %s:\n' % _('TCL Tutorial is here') + \
  3571. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3572. '# %s:\n' % _("FlatCAM commands list")
  3573. new_source_file += commands_list + '\n'
  3574. def initialize(obj, app):
  3575. obj.source_file = deepcopy(new_source_file)
  3576. if name is None:
  3577. outname = 'new_script'
  3578. else:
  3579. outname = name
  3580. self.new_object('script', outname, initialize, plot=False)
  3581. def new_document_object(self):
  3582. """
  3583. Creates a new, blank Document object.
  3584. :return: None
  3585. """
  3586. self.report_usage("new_document_object()")
  3587. def initialize(obj, app):
  3588. obj.source_file = ""
  3589. self.new_object('document', 'new_document', initialize, plot=False)
  3590. def on_object_created(self, obj, plot, auto_select):
  3591. """
  3592. Event callback for object creation.
  3593. It will add the new object to the collection. After that it will plot the object in a threaded way
  3594. :param obj: The newly created FlatCAM object.
  3595. :param plot: if the newly create object t obe plotted
  3596. :param auto_select: if the newly created object to be autoselected after creation
  3597. :return: None
  3598. """
  3599. t0 = time.time() # DEBUG
  3600. self.log.debug("on_object_created()")
  3601. # The Collection might change the name if there is a collision
  3602. self.collection.append(obj)
  3603. # after adding the object to the collection always update the list of objects that are in the collection
  3604. self.all_objects_list = self.collection.get_list()
  3605. # self.inform.emit('[selected] %s created & selected: %s' %
  3606. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3607. if obj.kind == 'gerber':
  3608. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3609. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3610. elif obj.kind == 'excellon':
  3611. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3612. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3613. elif obj.kind == 'cncjob':
  3614. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3615. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3616. elif obj.kind == 'geometry':
  3617. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3618. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3619. elif obj.kind == 'script':
  3620. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3621. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3622. elif obj.kind == 'document':
  3623. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3624. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3625. # update the SHELL auto-completer model with the name of the new object
  3626. self.shell._edit.set_model_data(self.myKeywords)
  3627. if auto_select:
  3628. # select the just opened object but deselect the previous ones
  3629. self.collection.set_all_inactive()
  3630. self.collection.set_active(obj.options["name"])
  3631. else:
  3632. self.collection.set_all_inactive()
  3633. # here it is done the object plotting
  3634. def worker_task(t_obj):
  3635. with self.proc_container.new(_("Plotting")):
  3636. if isinstance(t_obj, FlatCAMCNCjob):
  3637. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3638. else:
  3639. t_obj.plot()
  3640. t1 = time.time() # DEBUG
  3641. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3642. self.object_plotted.emit(t_obj)
  3643. # Send to worker
  3644. # self.worker.add_task(worker_task, [self])
  3645. if plot is True:
  3646. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3647. def on_object_changed(self, obj):
  3648. """
  3649. Called whenever the geometry of the object was changed in some way.
  3650. This require the update of it's bounding values so it can be the selected on canvas.
  3651. Update the bounding box data from obj.options
  3652. :param obj: the object that was changed
  3653. :return: None
  3654. """
  3655. xmin, ymin, xmax, ymax = obj.bounds()
  3656. obj.options['xmin'] = xmin
  3657. obj.options['ymin'] = ymin
  3658. obj.options['xmax'] = xmax
  3659. obj.options['ymax'] = ymax
  3660. log.debug("Object changed, updating the bounding box data on self.options")
  3661. # delete the old selection shape
  3662. self.delete_selection_shape()
  3663. self.should_we_save = True
  3664. def on_object_plotted(self):
  3665. """
  3666. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3667. :return: None
  3668. """
  3669. self.on_zoom_fit(None)
  3670. def on_about(self):
  3671. """
  3672. Displays the "about" dialog found in the Menu --> Help.
  3673. :return: None
  3674. """
  3675. self.report_usage("on_about")
  3676. version = self.version
  3677. version_date = self.version_date
  3678. beta = self.beta
  3679. class AboutDialog(QtWidgets.QDialog):
  3680. def __init__(self, parent=None):
  3681. QtWidgets.QDialog.__init__(self, parent)
  3682. # Icon and title
  3683. self.setWindowIcon(parent.app_icon)
  3684. self.setWindowTitle(_("About FlatCAM"))
  3685. self.resize(600, 200)
  3686. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3687. # self.setStyleSheet(
  3688. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3689. # "background-attachment: fixed"
  3690. # )
  3691. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3692. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3693. # palette = QtGui.QPalette()
  3694. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3695. # self.setPalette(palette)
  3696. logo = QtWidgets.QLabel()
  3697. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3698. title = QtWidgets.QLabel(
  3699. "<font size=8><B>FlatCAM</B></font><BR>"
  3700. "{title}<BR>"
  3701. "<BR>"
  3702. "<BR>"
  3703. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3704. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3705. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3706. "<B>{issue}</B></a><BR>".format(
  3707. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3708. devel=_("Development"),
  3709. down=_("DOWNLOAD"),
  3710. issue=_("Issue tracker"))
  3711. )
  3712. title.setOpenExternalLinks(True)
  3713. closebtn = QtWidgets.QPushButton(_("Close"))
  3714. tab_widget = QtWidgets.QTabWidget()
  3715. description_label = QtWidgets.QLabel(
  3716. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3717. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3718. version=version,
  3719. beta=('BETA' if beta else ''),
  3720. date=version_date,
  3721. arch=platform.architecture()[0])
  3722. )
  3723. description_label.setOpenExternalLinks(True)
  3724. lic_lbl_header = QtWidgets.QLabel(
  3725. '%s:<br>%s<br>' % (
  3726. _('Licensed under the MIT license'),
  3727. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3728. "http://www.opensource.org/licenses/mit-license.php</a>"
  3729. )
  3730. )
  3731. lic_lbl_header.setOpenExternalLinks(True)
  3732. lic_lbl_body = QtWidgets.QLabel(
  3733. _(
  3734. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3735. 'of this software and associated documentation files (the "Software"), to deal\n'
  3736. 'in the Software without restriction, including without limitation the rights\n'
  3737. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3738. 'copies of the Software, and to permit persons to whom the Software is\n'
  3739. 'furnished to do so, subject to the following conditions:\n\n'
  3740. 'The above copyright notice and this permission notice shall be included in\n'
  3741. 'all copies or substantial portions of the Software.\n\n'
  3742. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3743. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3744. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3745. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3746. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3747. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3748. 'THE SOFTWARE.'
  3749. )
  3750. )
  3751. attributions_label = QtWidgets.QLabel(
  3752. _(
  3753. 'Some of the icons used are from the following sources:<br>'
  3754. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3755. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3756. 'title="Flaticon">www.flaticon.com</a></div>'
  3757. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3758. )
  3759. )
  3760. # layouts
  3761. layout1 = QtWidgets.QVBoxLayout()
  3762. layout1_1 = QtWidgets.QHBoxLayout()
  3763. layout1_2 = QtWidgets.QHBoxLayout()
  3764. layout2 = QtWidgets.QHBoxLayout()
  3765. layout3 = QtWidgets.QHBoxLayout()
  3766. self.setLayout(layout1)
  3767. layout1.addLayout(layout1_1)
  3768. layout1.addLayout(layout1_2)
  3769. layout1.addLayout(layout2)
  3770. layout1.addLayout(layout3)
  3771. layout1_1.addStretch()
  3772. layout1_1.addWidget(description_label)
  3773. layout1_2.addWidget(tab_widget)
  3774. self.splash_tab = QtWidgets.QWidget()
  3775. self.splash_tab.setObjectName("splash_about")
  3776. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3777. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3778. tab_widget.addTab(self.splash_tab, _("Splash"))
  3779. self.programmmers_tab = QtWidgets.QWidget()
  3780. self.programmmers_tab.setObjectName("programmers_about")
  3781. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3782. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3783. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3784. self.translators_tab = QtWidgets.QWidget()
  3785. self.translators_tab.setObjectName("translators_about")
  3786. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3787. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3788. tab_widget.addTab(self.translators_tab, _("Translators"))
  3789. self.license_tab = QtWidgets.QWidget()
  3790. self.license_tab.setObjectName("license_about")
  3791. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3792. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3793. tab_widget.addTab(self.license_tab, _("License"))
  3794. self.attributions_tab = QtWidgets.QWidget()
  3795. self.attributions_tab.setObjectName("attributions_about")
  3796. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3797. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3798. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3799. self.splash_tab_layout.addWidget(logo, stretch=0)
  3800. self.splash_tab_layout.addWidget(title, stretch=1)
  3801. pal = QtGui.QPalette()
  3802. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3803. self.prog_grid_lay = QtWidgets.QGridLayout()
  3804. self.prog_grid_lay.setHorizontalSpacing(20)
  3805. self.prog_grid_lay.setColumnStretch(0, 0)
  3806. self.prog_grid_lay.setColumnStretch(2, 1)
  3807. prog_widget = QtWidgets.QWidget()
  3808. prog_widget.setLayout(self.prog_grid_lay)
  3809. prog_scroll = QtWidgets.QScrollArea()
  3810. prog_scroll.setWidget(prog_widget)
  3811. prog_scroll.setWidgetResizable(True)
  3812. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3813. prog_scroll.setPalette(pal)
  3814. self.programmmers_tab_layout.addWidget(prog_scroll)
  3815. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3816. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3817. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3818. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3819. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3820. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3821. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3822. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3823. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3824. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3825. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3826. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3827. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3828. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3829. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3830. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3831. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3832. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3833. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3834. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3835. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3836. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3837. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3838. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3839. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3840. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3841. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3842. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3843. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3844. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3845. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3846. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3847. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3848. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3849. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3850. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  3851. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  3852. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  3853. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  3854. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  3855. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  3856. self.translator_grid_lay = QtWidgets.QGridLayout()
  3857. self.translator_grid_lay.setColumnStretch(0, 0)
  3858. self.translator_grid_lay.setColumnStretch(1, 0)
  3859. self.translator_grid_lay.setColumnStretch(2, 1)
  3860. self.translator_grid_lay.setColumnStretch(3, 0)
  3861. # trans_widget = QtWidgets.QWidget()
  3862. # trans_widget.setLayout(self.translator_grid_lay)
  3863. # self.translators_tab_layout.addWidget(trans_widget)
  3864. # self.translators_tab_layout.addStretch()
  3865. trans_widget = QtWidgets.QWidget()
  3866. trans_widget.setLayout(self.translator_grid_lay)
  3867. trans_scroll = QtWidgets.QScrollArea()
  3868. trans_scroll.setWidget(trans_widget)
  3869. trans_scroll.setWidgetResizable(True)
  3870. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3871. trans_scroll.setPalette(pal)
  3872. self.translators_tab_layout.addWidget(trans_scroll)
  3873. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3874. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3875. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3876. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3877. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3878. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3879. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3880. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3881. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  3882. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  3883. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3884. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3885. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3886. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  3887. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3888. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3889. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3890. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3891. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3892. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3893. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3894. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3895. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  3896. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  3897. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3898. self.translator_grid_lay.setColumnStretch(0, 0)
  3899. self.translators_tab_layout.addStretch()
  3900. self.license_tab_layout.addWidget(lic_lbl_header)
  3901. self.license_tab_layout.addWidget(lic_lbl_body)
  3902. self.license_tab_layout.addStretch()
  3903. self.attributions_tab_layout.addWidget(attributions_label)
  3904. self.attributions_tab_layout.addStretch()
  3905. layout3.addStretch()
  3906. layout3.addWidget(closebtn)
  3907. closebtn.clicked.connect(self.accept)
  3908. AboutDialog(self.ui).exec_()
  3909. def install_bookmarks(self, book_dict=None):
  3910. """
  3911. Install the bookmarks actions in the Help menu -> Bookmarks
  3912. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3913. :return: None
  3914. """
  3915. if book_dict is None:
  3916. self.defaults["global_bookmarks"].update(
  3917. {
  3918. '1': ['FlatCAM', "http://flatcam.org"],
  3919. '2': ['Backup Site', ""]
  3920. }
  3921. )
  3922. else:
  3923. self.defaults["global_bookmarks"].clear()
  3924. self.defaults["global_bookmarks"].update(book_dict)
  3925. # first try to disconnect if somehow they get connected from elsewhere
  3926. for act in self.ui.menuhelp_bookmarks.actions():
  3927. try:
  3928. act.triggered.disconnect()
  3929. except TypeError:
  3930. pass
  3931. # clear all actions except the last one who is the Bookmark manager
  3932. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3933. pass
  3934. else:
  3935. self.ui.menuhelp_bookmarks.removeAction(act)
  3936. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3937. if self.defaults["global_bookmarks"]:
  3938. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3939. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3940. # the JSON is first making the keys as strings (therefore I have to use strings too
  3941. # or do the conversion :(
  3942. # )
  3943. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3944. # the '10' entry jsut after '1' therefore ordering as strings
  3945. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3946. key=lambda x: int(x[0]))
  3947. for entry, bookmark in sorted_bookmarks:
  3948. title = bookmark[0]
  3949. weblink = bookmark[1]
  3950. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3951. act.setText(title)
  3952. act.setIcon(QtGui.QIcon('share/link16.png'))
  3953. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3954. if title == 'Backup Site' and weblink == "":
  3955. act.triggered.connect(self.on_backup_site)
  3956. else:
  3957. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3958. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3959. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3960. def on_bookmarks_manager(self):
  3961. """
  3962. Adds the bookmark manager in a Tab in Plot Area
  3963. :return:
  3964. """
  3965. for idx in range(self.ui.plot_tab_area.count()):
  3966. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3967. # there can be only one instance of Bookmark Manager at one time
  3968. return
  3969. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3970. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3971. # add the tab if it was closed
  3972. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3973. # delete the absolute and relative position and messages in the infobar
  3974. self.ui.position_label.setText("")
  3975. self.ui.rel_position_label.setText("")
  3976. # Switch plot_area to preferences page
  3977. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3978. @staticmethod
  3979. def on_backup_site():
  3980. msgbox = QtWidgets.QMessageBox()
  3981. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  3982. "1. FlatCAM.org website is down\n"
  3983. "2. Someone forked FlatCAM project and wants to point\n"
  3984. "to his own website\n\n"
  3985. "If you can't get any informations about FlatCAM beta\n"
  3986. "use the YouTube channel link from the Help menu."))
  3987. msgbox.setWindowTitle(_("Alternative website"))
  3988. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  3989. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  3990. msgbox.setDefaultButton(bt_yes)
  3991. msgbox.exec_()
  3992. # response = msgbox.clickedButton()
  3993. def on_file_savedefaults(self):
  3994. """
  3995. Callback for menu item File->Save Defaults. Saves application default options
  3996. ``self.defaults`` to current_defaults.FlatConfig.
  3997. :return: None
  3998. """
  3999. self.save_defaults()
  4000. # def on_app_exit(self):
  4001. # self.report_usage("on_app_exit()")
  4002. #
  4003. # if self.collection.get_list():
  4004. # msgbox = QtWidgets.QMessageBox()
  4005. # # msgbox.setText("<B>Save changes ...</B>")
  4006. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4007. # "\n"
  4008. # "Do you want to Save the project?")
  4009. # msgbox.setWindowTitle("Save changes")
  4010. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4011. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4012. # QtWidgets.QMessageBox.Cancel)
  4013. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4014. #
  4015. # response = msgbox.exec_()
  4016. #
  4017. # if response == QtWidgets.QMessageBox.Yes:
  4018. # self.on_file_saveprojectas(thread=False)
  4019. # elif response == QtWidgets.QMessageBox.Cancel:
  4020. # return
  4021. # self.save_defaults()
  4022. # else:
  4023. # self.save_defaults()
  4024. # log.debug("Application defaults saved ... Exit event.")
  4025. # QtWidgets.qApp.quit()
  4026. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4027. """
  4028. Saves application default options
  4029. ``self.defaults`` to current_defaults.FlatConfig file.
  4030. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4031. used at the next launch of the application.
  4032. :param silent: whether to display a message in status bar or not; boolean
  4033. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4034. When the application is portable it should be a mobile location.
  4035. :return: None
  4036. """
  4037. self.report_usage("save_defaults")
  4038. if data_path is None:
  4039. data_path = self.data_path
  4040. # Read options from file
  4041. try:
  4042. f = open(data_path + "/current_defaults.FlatConfig")
  4043. defaults_file_content = f.read()
  4044. f.close()
  4045. except Exception:
  4046. e = sys.exc_info()[0]
  4047. App.log.error("Could not load defaults file.")
  4048. App.log.error(str(e))
  4049. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4050. return
  4051. try:
  4052. defaults = json.loads(defaults_file_content)
  4053. except Exception:
  4054. e = sys.exc_info()[0]
  4055. App.log.error("Failed to parse defaults file.")
  4056. App.log.error(str(e))
  4057. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4058. return
  4059. # Update options
  4060. self.defaults_read_form()
  4061. defaults.update(self.defaults)
  4062. self.propagate_defaults(silent=True)
  4063. # Save the toolbar view
  4064. tb_status = 0
  4065. if self.ui.toolbarfile.isVisible():
  4066. tb_status += 1
  4067. if self.ui.toolbargeo.isVisible():
  4068. tb_status += 2
  4069. if self.ui.toolbarview.isVisible():
  4070. tb_status += 4
  4071. if self.ui.toolbartools.isVisible():
  4072. tb_status += 8
  4073. if self.ui.exc_edit_toolbar.isVisible():
  4074. tb_status += 16
  4075. if self.ui.geo_edit_toolbar.isVisible():
  4076. tb_status += 32
  4077. if self.ui.grb_edit_toolbar.isVisible():
  4078. tb_status += 64
  4079. if self.ui.snap_toolbar.isVisible():
  4080. tb_status += 128
  4081. if self.ui.toolbarshell.isVisible():
  4082. tb_status += 256
  4083. if first_time is False:
  4084. self.defaults["global_toolbar_view"] = tb_status
  4085. # Save update options
  4086. try:
  4087. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4088. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4089. f.close()
  4090. except Exception as e:
  4091. log.debug("App.save_defaults() --> %s" % str(e))
  4092. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write defaults to file."))
  4093. return
  4094. if not silent:
  4095. self.inform.emit('[success] %s' % _("Preferences saved."))
  4096. def save_factory_defaults(self, silent_message=False, data_path=None):
  4097. """
  4098. Saves application factory default options
  4099. ``self.defaults`` to factory_defaults.FlatConfig.
  4100. It's a one time job done just after the first install.
  4101. :param silent_message: whether to display a message in status bar or not; boolean
  4102. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4103. When the application is portable it should be a mobile location.
  4104. :return: None
  4105. """
  4106. self.report_usage("save_factory_defaults")
  4107. if data_path is None:
  4108. data_path = self.data_path
  4109. # Read options from file
  4110. try:
  4111. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4112. factory_defaults_file_content = f_f_def.read()
  4113. f_f_def.close()
  4114. except Exception:
  4115. e = sys.exc_info()[0]
  4116. App.log.error("Could not load factory defaults file.")
  4117. App.log.error(str(e))
  4118. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4119. return
  4120. try:
  4121. factory_defaults = json.loads(factory_defaults_file_content)
  4122. except Exception:
  4123. e = sys.exc_info()[0]
  4124. App.log.error("Failed to parse factory defaults file.")
  4125. App.log.error(str(e))
  4126. if silent_message is False:
  4127. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4128. return
  4129. # Update options
  4130. self.defaults_read_form()
  4131. factory_defaults.update(self.defaults)
  4132. self.propagate_defaults(silent=True)
  4133. # Save update options
  4134. try:
  4135. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4136. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4137. f_f_def_s.close()
  4138. except Exception as e:
  4139. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4140. if silent_message is False:
  4141. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4142. return
  4143. if silent_message is False:
  4144. self.inform.emit(_("Factory defaults saved."))
  4145. def final_save(self):
  4146. """
  4147. Callback for doing a preferences save to file whenever the application is about to quit.
  4148. If the project has changes, it will ask the user to save the project.
  4149. :return: None
  4150. """
  4151. if self.save_in_progress:
  4152. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4153. return
  4154. if self.should_we_save and self.collection.get_list():
  4155. msgbox = QtWidgets.QMessageBox()
  4156. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4157. "\n"
  4158. "Do you want to Save the project?"))
  4159. msgbox.setWindowTitle(_("Save changes"))
  4160. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4161. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4162. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4163. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4164. msgbox.setDefaultButton(bt_yes)
  4165. msgbox.exec_()
  4166. response = msgbox.clickedButton()
  4167. if response == bt_yes:
  4168. try:
  4169. self.trayIcon.hide()
  4170. except Exception:
  4171. pass
  4172. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4173. elif response == bt_no:
  4174. try:
  4175. self.trayIcon.hide()
  4176. except Exception:
  4177. pass
  4178. self.quit_application()
  4179. elif response == bt_cancel:
  4180. return
  4181. else:
  4182. try:
  4183. self.trayIcon.hide()
  4184. except Exception:
  4185. pass
  4186. self.quit_application()
  4187. def quit_application(self):
  4188. """
  4189. Called (as a pyslot or not) when the application is quit.
  4190. :return: None
  4191. """
  4192. self.save_defaults()
  4193. log.debug("App.final_save() --> App Defaults saved.")
  4194. if self.cmd_line_headless != 1:
  4195. # save app state to file
  4196. stgs = QSettings("Open Source", "FlatCAM")
  4197. stgs.setValue('saved_gui_state', self.ui.saveState())
  4198. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4199. stgs.setValue(
  4200. 'language',
  4201. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4202. )
  4203. stgs.setValue(
  4204. 'notebook_font_size',
  4205. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4206. )
  4207. stgs.setValue(
  4208. 'axis_font_size',
  4209. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4210. )
  4211. stgs.setValue(
  4212. 'textbox_font_size',
  4213. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4214. )
  4215. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4216. stgs.setValue(
  4217. 'machinist',
  4218. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  4219. )
  4220. # This will write the setting to the platform specific storage.
  4221. del stgs
  4222. log.debug("App.final_save() --> App UI state saved.")
  4223. QtWidgets.qApp.quit()
  4224. def on_portable_checked(self, state):
  4225. """
  4226. Callback called when the checkbox in Preferences GUI is checked.
  4227. It will set the application as portable by creating the preferences and recent files in the
  4228. 'config' folder found in the FlatCAM installation folder.
  4229. :param state: boolean, the state of the checkbox when clicked/checked
  4230. :return:
  4231. """
  4232. line_no = 0
  4233. data = None
  4234. if sys.platform != 'win32':
  4235. # this won't work in Linux or MacOS
  4236. return
  4237. # test if the app was frozen and choose the path for the configuration file
  4238. if getattr(sys, "frozen", False) is True:
  4239. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4240. else:
  4241. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4242. config_file = current_data_path + '\\configuration.txt'
  4243. try:
  4244. with open(config_file, 'r') as f:
  4245. try:
  4246. data = f.readlines()
  4247. except Exception as e:
  4248. log.debug('App.__init__() -->%s' % str(e))
  4249. return
  4250. except FileNotFoundError:
  4251. pass
  4252. for line in data:
  4253. line = line.strip('\n')
  4254. param = str(line).rpartition('=')
  4255. if param[0] == 'portable':
  4256. break
  4257. line_no += 1
  4258. if state:
  4259. data[line_no] = 'portable=True\n'
  4260. # create the new defauults files
  4261. # create current_defaults.FlatConfig file if there is none
  4262. try:
  4263. f = open(current_data_path + '/current_defaults.FlatConfig')
  4264. f.close()
  4265. except IOError:
  4266. App.log.debug('Creating empty current_defaults.FlatConfig')
  4267. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4268. json.dump({}, f)
  4269. f.close()
  4270. # create factory_defaults.FlatConfig file if there is none
  4271. try:
  4272. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4273. f.close()
  4274. except IOError:
  4275. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4276. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4277. json.dump({}, f)
  4278. f.close()
  4279. try:
  4280. f = open(current_data_path + '/recent.json')
  4281. f.close()
  4282. except IOError:
  4283. App.log.debug('Creating empty recent.json')
  4284. f = open(current_data_path + '/recent.json', 'w')
  4285. json.dump([], f)
  4286. f.close()
  4287. try:
  4288. fp = open(current_data_path + '/recent_projects.json')
  4289. fp.close()
  4290. except IOError:
  4291. App.log.debug('Creating empty recent_projects.json')
  4292. fp = open(current_data_path + '/recent_projects.json', 'w')
  4293. json.dump([], fp)
  4294. fp.close()
  4295. # save the current defaults to the new defaults file
  4296. self.save_defaults(silent=True, data_path=current_data_path)
  4297. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4298. else:
  4299. data[line_no] = 'portable=False\n'
  4300. with open(config_file, 'w') as f:
  4301. f.writelines(data)
  4302. def on_toggle_shell(self):
  4303. """
  4304. Toggle shell: if is visible close it, if it is closed then open it
  4305. :return: None
  4306. """
  4307. self.report_usage("on_toggle_shell()")
  4308. if self.ui.shell_dock.isVisible():
  4309. self.ui.shell_dock.hide()
  4310. else:
  4311. self.ui.shell_dock.show()
  4312. def on_register_files(self, obj_type=None):
  4313. """
  4314. Called whenever there is a need to register file extensions with FlatCAM.
  4315. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4316. :param obj_type: the type of object to be register for.
  4317. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4318. :return: None
  4319. """
  4320. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4321. new_reg_path = 'Software\\Classes\\'
  4322. # find if the current user is admin
  4323. try:
  4324. is_admin = os.getuid() == 0
  4325. except AttributeError:
  4326. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4327. if is_admin is True:
  4328. root_path = winreg.HKEY_LOCAL_MACHINE
  4329. else:
  4330. root_path = winreg.HKEY_CURRENT_USER
  4331. # create the keys
  4332. def set_reg(name, root_path, new_reg_path, value):
  4333. try:
  4334. winreg.CreateKey(root_path, new_reg_path)
  4335. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4336. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4337. return True
  4338. except WindowsError:
  4339. return False
  4340. # delete key in registry
  4341. def delete_reg(root_path, reg_path, key_to_del):
  4342. key_to_del_path = reg_path + key_to_del
  4343. try:
  4344. winreg.DeleteKey(root_path, key_to_del_path)
  4345. return True
  4346. except WindowsError:
  4347. return False
  4348. if obj_type is None or obj_type == 'excellon':
  4349. exc_list = \
  4350. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4351. exc_list = [x for x in exc_list if x != '']
  4352. # register all keys in the Preferences window
  4353. for ext in exc_list:
  4354. new_k = new_reg_path + '.%s' % ext
  4355. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4356. # and unregister those that are no longer in the Preferences windows but are in the file
  4357. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4358. if ext not in exc_list:
  4359. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4360. # now write the updated extensions to the self.defaults
  4361. # new_ext = ''
  4362. # for ext in exc_list:
  4363. # new_ext = new_ext + ext + ', '
  4364. # self.defaults["fa_excellon"] = new_ext
  4365. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4366. if obj_type is None or obj_type == 'gcode':
  4367. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4368. gco_list = [x for x in gco_list if x != '']
  4369. # register all keys in the Preferences window
  4370. for ext in gco_list:
  4371. new_k = new_reg_path + '.%s' % ext
  4372. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4373. # and unregister those that are no longer in the Preferences windows but are in the file
  4374. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4375. if ext not in gco_list:
  4376. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4377. # now write the updated extensions to the self.defaults
  4378. # new_ext = ''
  4379. # for ext in gco_list:
  4380. # new_ext = new_ext + ext + ', '
  4381. # self.defaults["fa_gcode"] = new_ext
  4382. self.inform.emit('[success] %s' %
  4383. _("Selected GCode file extensions registered with FlatCAM."))
  4384. if obj_type is None or obj_type == 'gerber':
  4385. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4386. grb_list = [x for x in grb_list if x != '']
  4387. # register all keys in the Preferences window
  4388. for ext in grb_list:
  4389. new_k = new_reg_path + '.%s' % ext
  4390. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4391. # and unregister those that are no longer in the Preferences windows but are in the file
  4392. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4393. if ext not in grb_list:
  4394. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4395. # now write the updated extensions to the self.defaults
  4396. # new_ext = ''
  4397. # for ext in grb_list:
  4398. # new_ext = new_ext + ext + ', '
  4399. # self.defaults["fa_gerber"] = new_ext
  4400. self.inform.emit('[success] %s' %
  4401. _("Selected Gerber file extensions registered with FlatCAM."))
  4402. def add_extension(self, ext_type):
  4403. """
  4404. Add a file extension to the list for a specific object
  4405. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4406. :return:
  4407. """
  4408. if ext_type == 'excellon':
  4409. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4410. if new_ext == '':
  4411. return
  4412. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4413. if new_ext in old_val:
  4414. return
  4415. old_val.append(new_ext)
  4416. old_val.sort()
  4417. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4418. if ext_type == 'gcode':
  4419. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4420. if new_ext == '':
  4421. return
  4422. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4423. if new_ext in old_val:
  4424. return
  4425. old_val.append(new_ext)
  4426. old_val.sort()
  4427. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4428. if ext_type == 'gerber':
  4429. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4430. if new_ext == '':
  4431. return
  4432. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4433. if new_ext in old_val:
  4434. return
  4435. old_val.append(new_ext)
  4436. old_val.sort()
  4437. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4438. if ext_type == 'keyword':
  4439. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4440. if new_kw == '':
  4441. return
  4442. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4443. if new_kw in old_val:
  4444. return
  4445. old_val.append(new_kw)
  4446. old_val.sort()
  4447. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4448. # update the self.myKeywords so the model is updated
  4449. self.autocomplete_kw_list = \
  4450. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4451. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4452. self.shell._edit.set_model_data(self.myKeywords)
  4453. def del_extension(self, ext_type):
  4454. """
  4455. Remove a file extension from the list for a specific object
  4456. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4457. :return:
  4458. """
  4459. if ext_type == 'excellon':
  4460. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4461. if new_ext == '':
  4462. return
  4463. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4464. if new_ext not in old_val:
  4465. return
  4466. old_val.remove(new_ext)
  4467. old_val.sort()
  4468. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4469. if ext_type == 'gcode':
  4470. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4471. if new_ext == '':
  4472. return
  4473. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4474. if new_ext not in old_val:
  4475. return
  4476. old_val.remove(new_ext)
  4477. old_val.sort()
  4478. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4479. if ext_type == 'gerber':
  4480. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4481. if new_ext == '':
  4482. return
  4483. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4484. if new_ext not in old_val:
  4485. return
  4486. old_val.remove(new_ext)
  4487. old_val.sort()
  4488. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4489. if ext_type == 'keyword':
  4490. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4491. if new_kw == '':
  4492. return
  4493. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4494. if new_kw not in old_val:
  4495. return
  4496. old_val.remove(new_kw)
  4497. old_val.sort()
  4498. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4499. # update the self.myKeywords so the model is updated
  4500. self.autocomplete_kw_list = \
  4501. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4502. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4503. self.shell._edit.set_model_data(self.myKeywords)
  4504. def restore_extensions(self, ext_type):
  4505. """
  4506. Restore all file extensions associations with FlatCAM, for a specific object
  4507. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4508. :return:
  4509. """
  4510. if ext_type == 'excellon':
  4511. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4512. # for the ability to open Excellon files with .txt extension
  4513. new_exc_list = deepcopy(self.exc_list)
  4514. try:
  4515. new_exc_list.remove('txt')
  4516. except ValueError:
  4517. pass
  4518. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4519. if ext_type == 'gcode':
  4520. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4521. if ext_type == 'gerber':
  4522. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4523. if ext_type == 'keyword':
  4524. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4525. # update the self.myKeywords so the model is updated
  4526. self.autocomplete_kw_list = self.default_keywords
  4527. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4528. self.shell._edit.set_model_data(self.myKeywords)
  4529. def delete_all_extensions(self, ext_type):
  4530. """
  4531. Delete all file extensions associations with FlatCAM, for a specific object
  4532. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4533. :return:
  4534. """
  4535. if ext_type == 'excellon':
  4536. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4537. if ext_type == 'gcode':
  4538. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4539. if ext_type == 'gerber':
  4540. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4541. if ext_type == 'keyword':
  4542. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4543. # update the self.myKeywords so the model is updated
  4544. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4545. self.shell._edit.set_model_data(self.myKeywords)
  4546. def on_edit_join(self, name=None):
  4547. """
  4548. Callback for Edit->Join. Joins the selected geometry objects into
  4549. a new one.
  4550. :return: None
  4551. """
  4552. self.report_usage("on_edit_join()")
  4553. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4554. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4555. geo_type_set = set()
  4556. objs = self.collection.get_selected()
  4557. if len(objs) < 2:
  4558. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4559. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4560. return 'fail'
  4561. for obj in objs:
  4562. geo_type_set.add(obj.multigeo)
  4563. # if len(geo_type_list) == 1 means that all list elements are the same
  4564. if len(geo_type_set) != 1:
  4565. self.inform.emit('[ERROR] %s' %
  4566. _("Failed join. The Geometry objects are of different types.\n"
  4567. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4568. "convert from one to another and retry joining \n"
  4569. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4570. "the result may not be what was expected. \n"
  4571. "Check the generated GCODE."))
  4572. return
  4573. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4574. if True in geo_type_set:
  4575. def initialize(geo_obj, app):
  4576. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4577. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4578. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4579. for v in obj.tools.values():
  4580. v['data']['name'] = obj_name_multi
  4581. self.new_object("geometry", obj_name_multi, initialize)
  4582. else:
  4583. def initialize(geo_obj, app):
  4584. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4585. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4586. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4587. for v in obj.tools.values():
  4588. v['data']['name'] = obj_name_single
  4589. self.new_object("geometry", obj_name_single, initialize)
  4590. self.should_we_save = True
  4591. def on_edit_join_exc(self):
  4592. """
  4593. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4594. a new Excellon.
  4595. :return: None
  4596. """
  4597. self.report_usage("on_edit_join_exc()")
  4598. objs = self.collection.get_selected()
  4599. for obj in objs:
  4600. if not isinstance(obj, FlatCAMExcellon):
  4601. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4602. return
  4603. if len(objs) < 2:
  4604. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4605. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4606. return 'fail'
  4607. def initialize(exc_obj, app):
  4608. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4609. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4610. self.new_object("excellon", 'Combo_Excellon', initialize)
  4611. self.should_we_save = True
  4612. def on_edit_join_grb(self):
  4613. """
  4614. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4615. a new Gerber object.
  4616. :return: None
  4617. """
  4618. self.report_usage("on_edit_join_grb()")
  4619. objs = self.collection.get_selected()
  4620. for obj in objs:
  4621. if not isinstance(obj, FlatCAMGerber):
  4622. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4623. return
  4624. if len(objs) < 2:
  4625. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4626. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4627. return 'fail'
  4628. def initialize(grb_obj, app):
  4629. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4630. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4631. self.new_object("gerber", 'Combo_Gerber', initialize)
  4632. self.should_we_save = True
  4633. def on_convert_singlegeo_to_multigeo(self):
  4634. """
  4635. Called for converting a Geometry object from single-geo to multi-geo.
  4636. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4637. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4638. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4639. the solid-geometry of that tool.
  4640. :return: None
  4641. """
  4642. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4643. obj = self.collection.get_active()
  4644. if obj is None:
  4645. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4646. return
  4647. if not isinstance(obj, FlatCAMGeometry):
  4648. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4649. return
  4650. obj.multigeo = True
  4651. for tooluid, dict_value in obj.tools.items():
  4652. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4653. if not isinstance(obj.solid_geometry, list):
  4654. obj.solid_geometry = [obj.solid_geometry]
  4655. obj.solid_geometry[:] = []
  4656. obj.plot()
  4657. self.should_we_save = True
  4658. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4659. def on_convert_multigeo_to_singlegeo(self):
  4660. """
  4661. Called for converting a Geometry object from multi-geo to single-geo.
  4662. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4663. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4664. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4665. the solid-geometry of that tool.
  4666. :return: None
  4667. """
  4668. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4669. obj = self.collection.get_active()
  4670. if obj is None:
  4671. self.inform.emit('[ERROR_NOTCL] %s' %
  4672. _("Failed. Select a Geometry Object and try again."))
  4673. return
  4674. if not isinstance(obj, FlatCAMGeometry):
  4675. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4676. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4677. return
  4678. obj.multigeo = False
  4679. total_solid_geometry = []
  4680. for tooluid, dict_value in obj.tools.items():
  4681. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4682. # clear the original geometry
  4683. dict_value['solid_geometry'][:] = []
  4684. obj.solid_geometry = deepcopy(total_solid_geometry)
  4685. obj.plot()
  4686. self.should_we_save = True
  4687. self.inform.emit('[success] %s' %
  4688. _("A Geometry object was converted to SingleGeo type."))
  4689. def on_defaults_dict_change(self, field):
  4690. """
  4691. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4692. Edit -> Preferences tab window.
  4693. :param field: the key of the self.defaults dictionary that was changed.
  4694. :return: None
  4695. """
  4696. self.defaults_write_form_field(field)
  4697. if field == "units":
  4698. self.set_screen_units(self.defaults['units'])
  4699. def set_screen_units(self, units):
  4700. """
  4701. Set the FlatCAM units on the status bar.
  4702. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4703. :return: None
  4704. """
  4705. self.ui.units_label.setText("[" + units.lower() + "]")
  4706. def on_toggle_units(self, no_pref=False):
  4707. """
  4708. Callback for the Units radio-button change in the Preferences tab.
  4709. Changes the application's default units adn for the project too.
  4710. If changing the project's units, the change propagates to all of
  4711. the objects in the project.
  4712. :return: None
  4713. """
  4714. self.report_usage("on_toggle_units")
  4715. if self.toggle_units_ignore:
  4716. return
  4717. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4718. # If option is the same, then ignore
  4719. if new_units == self.defaults["units"].upper():
  4720. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4721. return
  4722. # Options to scale
  4723. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4724. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4725. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4726. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4727. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4728. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4729. "excellon_editor_slot_lin_pitch",
  4730. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4731. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4732. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4733. "geometry_feedrate_probe", "geometry_startz",
  4734. 'cncjob_tooldia',
  4735. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4736. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4737. "tools_nccnewdia",
  4738. "tools_2sided_drilldia", "tools_film_boundary",
  4739. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4740. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4741. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4742. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4743. "tools_transform_offset_y",
  4744. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4745. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4746. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4747. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4748. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4749. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4750. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4751. "tools_fiducials_mode", "tools_fiducials_second_pos", "tools_fiducials_type",
  4752. "tools_fiducials_line_thickness",
  4753. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4754. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4755. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4756. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4757. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4758. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4759. def scale_defaults(sfactor):
  4760. for dim in dimensions:
  4761. if dim == 'excellon_toolchangexy':
  4762. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4763. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4764. coords_xy[0] *= sfactor
  4765. coords_xy[1] *= sfactor
  4766. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4767. self.decimals, coords_xy[1])
  4768. elif dim == 'geometry_toolchangexy':
  4769. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4770. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4771. coords_xy[0] *= sfactor
  4772. coords_xy[1] *= sfactor
  4773. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4774. self.decimals, coords_xy[1])
  4775. elif dim == 'geometry_cnctooldia':
  4776. tools_diameters = []
  4777. try:
  4778. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4779. tools_diameters = [eval(a) for a in tools_string if a != '']
  4780. except Exception as e:
  4781. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4782. self.defaults['geometry_cnctooldia'] = ''
  4783. for t in range(len(tools_diameters)):
  4784. tools_diameters[t] *= sfactor
  4785. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4786. elif dim == 'tools_ncctools':
  4787. ncctools = []
  4788. try:
  4789. tools_string = self.defaults["tools_ncctools"].split(",")
  4790. ncctools = [eval(a) for a in tools_string if a != '']
  4791. except Exception as e:
  4792. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4793. self.defaults['tools_ncctools'] = ''
  4794. for t in range(len(ncctools)):
  4795. ncctools[t] *= sfactor
  4796. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  4797. elif dim == 'tools_solderpaste_tools':
  4798. sptools = []
  4799. try:
  4800. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4801. sptools = [eval(a) for a in tools_string if a != '']
  4802. except Exception as e:
  4803. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4804. self.defaults['tools_solderpaste_tools'] = ""
  4805. for t in range(len(sptools)):
  4806. sptools[t] *= sfactor
  4807. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  4808. elif dim == 'tools_solderpaste_xy_toolchange':
  4809. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4810. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4811. sp_coords[0] *= sfactor
  4812. sp_coords[1] *= sfactor
  4813. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  4814. self.decimals, sp_coords[1])
  4815. elif dim == 'global_gridx' or dim == 'global_gridy':
  4816. if new_units == 'IN':
  4817. val = 0.1
  4818. try:
  4819. val = float(self.defaults[dim]) * sfactor
  4820. except Exception as e:
  4821. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4822. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4823. else:
  4824. val = 0.1
  4825. try:
  4826. val = float(self.defaults[dim]) * sfactor
  4827. except Exception as e:
  4828. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4829. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4830. else:
  4831. val = 0.1
  4832. if self.defaults[dim]:
  4833. try:
  4834. val = float(self.defaults[dim]) * sfactor
  4835. except Exception as e:
  4836. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4837. self.defaults[dim] = val
  4838. # The scaling factor depending on choice of units.
  4839. factor = 1/25.4
  4840. if new_units == 'MM':
  4841. factor = 25.4
  4842. # Changing project units. Warn user.
  4843. msgbox = QtWidgets.QMessageBox()
  4844. msgbox.setWindowTitle(_("Toggle Units"))
  4845. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4846. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4847. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4848. "properties of all objects to be scaled accordingly.\nContinue?"))
  4849. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4850. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4851. msgbox.setDefaultButton(bt_ok)
  4852. msgbox.exec_()
  4853. response = msgbox.clickedButton()
  4854. if response == bt_ok:
  4855. if no_pref is False:
  4856. self.defaults_read_form()
  4857. scale_defaults(factor)
  4858. self.defaults_write_form(fl_units=new_units)
  4859. self.defaults["units"] = new_units
  4860. # save the defaults to file, some may assume that the conversion is enough and it's not
  4861. self.on_save_button(save_to_file=True)
  4862. self.should_we_save = True
  4863. # change this only if the workspace is active
  4864. if self.defaults['global_workspace'] is True:
  4865. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4866. # adjust the grid values on the main toolbar
  4867. dec = 6 if new_units == 'IN'else 4
  4868. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4869. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4870. if not self.ui.grid_gap_link_cb.isChecked():
  4871. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4872. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4873. for obj in self.collection.get_list():
  4874. obj.convert_units(new_units)
  4875. # make that the properties stored in the object are also updated
  4876. self.object_changed.emit(obj)
  4877. obj.build_ui()
  4878. current = self.collection.get_active()
  4879. if current is not None:
  4880. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4881. if not isinstance(current, FlatCAMGeometry):
  4882. current.to_form()
  4883. self.plot_all()
  4884. self.inform.emit('[success] %s: %s' %
  4885. (_("Converted units to"), new_units))
  4886. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4887. self.set_screen_units(new_units)
  4888. else:
  4889. # Undo toggling
  4890. self.toggle_units_ignore = True
  4891. if self.defaults['units'].upper() == 'MM':
  4892. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4893. else:
  4894. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4895. self.toggle_units_ignore = False
  4896. self.inform.emit('[WARNING_NOTCL]%s' %
  4897. _(" Units conversion cancelled."))
  4898. self.defaults_read_form()
  4899. def on_toggle_units_click(self):
  4900. try:
  4901. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4902. except (TypeError, AttributeError):
  4903. pass
  4904. if self.defaults["units"] == 'MM':
  4905. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4906. else:
  4907. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4908. self.on_toggle_units(no_pref=True)
  4909. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4910. lambda: self.on_toggle_units(no_pref=False))
  4911. def on_fullscreen(self, disable=False):
  4912. self.report_usage("on_fullscreen()")
  4913. if self.toggle_fscreen is False and disable is False:
  4914. # self.ui.showFullScreen()
  4915. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4916. a = self.ui.geometry()
  4917. self.x_pos = a.x()
  4918. self.y_pos = a.y()
  4919. self.width = a.width()
  4920. self.height = a.height()
  4921. # set new geometry to full desktop rect
  4922. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4923. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4924. # everything else will not work without this hack. This happen in Windows.
  4925. # https://bugreports.qt.io/browse/QTBUG-41309
  4926. desktop = QtWidgets.QApplication.desktop()
  4927. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4928. rec = desktop.screenGeometry(screen)
  4929. x = rec.x() - 1
  4930. y = rec.y() - 1
  4931. h = rec.height() + 2
  4932. w = rec.width() + 2
  4933. self.ui.setGeometry(x, y, w, h)
  4934. self.ui.show()
  4935. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4936. tb.setVisible(False)
  4937. self.ui.splitter_left.setVisible(False)
  4938. self.toggle_fscreen = True
  4939. elif self.toggle_fscreen is True or disable is True:
  4940. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4941. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4942. self.ui.showNormal()
  4943. self.restore_toolbar_view()
  4944. self.ui.splitter_left.setVisible(True)
  4945. self.toggle_fscreen = False
  4946. def on_toggle_plotarea(self):
  4947. self.report_usage("on_toggle_plotarea()")
  4948. try:
  4949. name = self.ui.plot_tab_area.widget(0).objectName()
  4950. except AttributeError:
  4951. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4952. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4953. self.ui.plot_tab_area.protectTab(0)
  4954. return
  4955. if name != 'plotarea':
  4956. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4957. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4958. self.ui.plot_tab_area.protectTab(0)
  4959. else:
  4960. self.ui.plot_tab_area.closeTab(0)
  4961. def on_toggle_notebook(self):
  4962. if self.ui.splitter.sizes()[0] == 0:
  4963. self.ui.splitter.setSizes([1, 1])
  4964. self.ui.menu_toggle_nb.setChecked(True)
  4965. else:
  4966. self.ui.splitter.setSizes([0, 1])
  4967. self.ui.menu_toggle_nb.setChecked(False)
  4968. def on_toggle_axis(self):
  4969. self.report_usage("on_toggle_axis()")
  4970. if self.toggle_axis is False:
  4971. if self.is_legacy is False:
  4972. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4973. parent=self.plotcanvas.view.scene)
  4974. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4975. parent=self.plotcanvas.view.scene)
  4976. else:
  4977. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  4978. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  4979. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4980. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4981. self.plotcanvas.canvas.draw()
  4982. self.toggle_axis = True
  4983. else:
  4984. if self.is_legacy is False:
  4985. self.plotcanvas.v_line.parent = None
  4986. self.plotcanvas.h_line.parent = None
  4987. else:
  4988. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  4989. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  4990. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  4991. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  4992. self.plotcanvas.canvas.draw()
  4993. self.toggle_axis = False
  4994. def on_toggle_grid(self):
  4995. self.report_usage("on_toggle_grid()")
  4996. self.ui.grid_snap_btn.trigger()
  4997. def on_toggle_grid_lines(self):
  4998. self.report_usage("on_toggle_grd_lines()")
  4999. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5000. if tt_settings.contains("theme"):
  5001. theme = tt_settings.value('theme', type=str)
  5002. else:
  5003. theme = 'white'
  5004. if self.toggle_grid_lines is False:
  5005. if self.is_legacy is False:
  5006. if theme == 'white':
  5007. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5008. else:
  5009. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5010. else:
  5011. self.plotcanvas.axes.grid(True)
  5012. try:
  5013. self.plotcanvas.canvas.draw()
  5014. except IndexError:
  5015. pass
  5016. pass
  5017. self.toggle_grid_lines = True
  5018. else:
  5019. if self.is_legacy is False:
  5020. if theme == 'white':
  5021. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5022. else:
  5023. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5024. else:
  5025. self.plotcanvas.axes.grid(False)
  5026. try:
  5027. self.plotcanvas.canvas.draw()
  5028. except IndexError:
  5029. pass
  5030. self.toggle_grid_lines = False
  5031. if self.is_legacy is False:
  5032. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5033. # - perhaps is a bug in VisPy implementation
  5034. if self.grid_status() is True:
  5035. self.app_cursor.enabled = False
  5036. self.app_cursor.enabled = True
  5037. else:
  5038. self.app_cursor.enabled = True
  5039. self.app_cursor.enabled = False
  5040. def show_preferences_gui(self):
  5041. """
  5042. Called to initialize and show the Preferences GUI
  5043. :return: None
  5044. """
  5045. self.gen_form = self.ui.general_defaults_form
  5046. self.ger_form = self.ui.gerber_defaults_form
  5047. self.exc_form = self.ui.excellon_defaults_form
  5048. self.geo_form = self.ui.geometry_defaults_form
  5049. self.cnc_form = self.ui.cncjob_defaults_form
  5050. self.tools_form = self.ui.tools_defaults_form
  5051. self.tools2_form = self.ui.tools2_defaults_form
  5052. self.fa_form = self.ui.util_defaults_form
  5053. try:
  5054. self.ui.general_scroll_area.takeWidget()
  5055. except Exception:
  5056. self.log.debug("Nothing to remove")
  5057. self.ui.general_scroll_area.setWidget(self.gen_form)
  5058. self.gen_form.show()
  5059. try:
  5060. self.ui.gerber_scroll_area.takeWidget()
  5061. except Exception:
  5062. self.log.debug("Nothing to remove")
  5063. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5064. self.ger_form.show()
  5065. try:
  5066. self.ui.excellon_scroll_area.takeWidget()
  5067. except Exception:
  5068. self.log.debug("Nothing to remove")
  5069. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5070. self.exc_form.show()
  5071. try:
  5072. self.ui.geometry_scroll_area.takeWidget()
  5073. except Exception:
  5074. self.log.debug("Nothing to remove")
  5075. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5076. self.geo_form.show()
  5077. try:
  5078. self.ui.cncjob_scroll_area.takeWidget()
  5079. except Exception:
  5080. self.log.debug("Nothing to remove")
  5081. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5082. self.cnc_form.show()
  5083. try:
  5084. self.ui.tools_scroll_area.takeWidget()
  5085. except Exception:
  5086. self.log.debug("Nothing to remove")
  5087. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5088. self.tools_form.show()
  5089. try:
  5090. self.ui.tools2_scroll_area.takeWidget()
  5091. except Exception:
  5092. self.log.debug("Nothing to remove")
  5093. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5094. self.tools2_form.show()
  5095. try:
  5096. self.ui.fa_scroll_area.takeWidget()
  5097. except Exception:
  5098. self.log.debug("Nothing to remove")
  5099. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5100. self.fa_form.show()
  5101. self.log.debug("Finished Preferences GUI form initialization.")
  5102. # self.options2form()
  5103. def init_color_pickers_in_preferences_gui(self):
  5104. # Init Plot Colors
  5105. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  5106. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5107. "background-color:%s;"
  5108. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  5109. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  5110. int(self.defaults['global_plot_fill'][7:9], 16))
  5111. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  5112. int(self.defaults['global_plot_fill'][7:9], 16))
  5113. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  5114. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5115. "background-color:%s;"
  5116. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  5117. # Init Left-Right Selection colors
  5118. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5119. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5120. "background-color:%s;"
  5121. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5122. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5123. int(self.defaults['global_sel_fill'][7:9], 16))
  5124. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5125. int(self.defaults['global_sel_fill'][7:9], 16))
  5126. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5127. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5128. "background-color:%s;"
  5129. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5130. # Init Right-Left Selection colors
  5131. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5132. self.defaults['global_alt_sel_fill'])
  5133. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5134. "background-color:%s;"
  5135. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5136. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5137. int(self.defaults['global_sel_fill'][7:9], 16))
  5138. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5139. int(self.defaults['global_sel_fill'][7:9], 16))
  5140. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5141. self.defaults['global_alt_sel_line'])
  5142. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5143. "background-color:%s;"
  5144. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5145. # Init Draw color and Selection Draw Color
  5146. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5147. self.defaults['global_draw_color'])
  5148. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5149. "background-color:%s;"
  5150. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5151. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5152. self.defaults['global_sel_draw_color'])
  5153. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5154. "background-color:%s;"
  5155. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5156. # Init Project Items color
  5157. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5158. self.defaults['global_proj_item_color'])
  5159. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5160. "background-color:%s;"
  5161. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5162. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5163. self.defaults['global_proj_item_dis_color'])
  5164. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5165. "background-color:%s;"
  5166. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5167. # Init the Annotation CNC Job color
  5168. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5169. self.defaults['cncjob_annotation_fontcolor'])
  5170. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5171. "background-color:%s;"
  5172. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5173. # Init the Tool Film color
  5174. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5175. self.defaults['tools_film_color'])
  5176. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5177. "background-color:%s;"
  5178. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5179. )
  5180. # Init the Tool QRCode colors
  5181. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5182. self.defaults['tools_qrcode_fill_color'])
  5183. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5184. "background-color:%s;"
  5185. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5186. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5187. self.defaults['tools_qrcode_back_color'])
  5188. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5189. "background-color:%s;"
  5190. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5191. def on_excellon_defaults_button(self):
  5192. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5193. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5194. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5195. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5196. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5197. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5198. log.debug("Excellon app defaults loaded ...")
  5199. def on_update_exc_export(self, state):
  5200. """
  5201. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5202. if the update_excellon_cb checkbox is checked
  5203. :param state: state of the checkbox whose signals is tied to his slot
  5204. :return:
  5205. """
  5206. if state:
  5207. # first try to disconnect
  5208. try:
  5209. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5210. disconnect(self.on_excellon_format_changed)
  5211. except TypeError:
  5212. pass
  5213. try:
  5214. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5215. disconnect(self.on_excellon_format_changed)
  5216. except TypeError:
  5217. pass
  5218. try:
  5219. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5220. disconnect(self.on_excellon_format_changed)
  5221. except TypeError:
  5222. pass
  5223. try:
  5224. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5225. disconnect(self.on_excellon_format_changed)
  5226. except TypeError:
  5227. pass
  5228. try:
  5229. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5230. disconnect(self.on_excellon_zeros_changed)
  5231. except TypeError:
  5232. pass
  5233. try:
  5234. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5235. disconnect(self.on_excellon_zeros_changed)
  5236. except TypeError:
  5237. pass
  5238. # the connect them
  5239. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5240. self.on_excellon_format_changed)
  5241. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5242. self.on_excellon_format_changed)
  5243. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5244. self.on_excellon_format_changed)
  5245. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5246. self.on_excellon_format_changed)
  5247. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5248. self.on_excellon_zeros_changed)
  5249. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5250. self.on_excellon_units_changed)
  5251. else:
  5252. # disconnect the signals
  5253. try:
  5254. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5255. disconnect(self.on_excellon_format_changed)
  5256. except TypeError:
  5257. pass
  5258. try:
  5259. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5260. disconnect(self.on_excellon_format_changed)
  5261. except TypeError:
  5262. pass
  5263. try:
  5264. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5265. disconnect(self.on_excellon_format_changed)
  5266. except TypeError:
  5267. pass
  5268. try:
  5269. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5270. disconnect(self.on_excellon_format_changed)
  5271. except TypeError:
  5272. pass
  5273. try:
  5274. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5275. disconnect(self.on_excellon_zeros_changed)
  5276. except TypeError:
  5277. pass
  5278. try:
  5279. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5280. disconnect(self.on_excellon_zeros_changed)
  5281. except TypeError:
  5282. pass
  5283. def on_excellon_format_changed(self):
  5284. """
  5285. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5286. :return: None
  5287. """
  5288. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5289. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5290. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5291. )
  5292. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5293. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5294. )
  5295. else:
  5296. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5297. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5298. )
  5299. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5300. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5301. )
  5302. def on_excellon_zeros_changed(self):
  5303. """
  5304. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5305. :return: None
  5306. """
  5307. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5308. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5309. )
  5310. def on_excellon_units_changed(self):
  5311. """
  5312. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5313. :return: None
  5314. """
  5315. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5316. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5317. )
  5318. self.on_excellon_format_changed()
  5319. # Setting plot colors handlers
  5320. def on_pf_color_entry(self):
  5321. self.defaults['global_plot_fill'] = \
  5322. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5323. self.defaults['global_plot_fill'][7:9]
  5324. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5325. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5326. def on_pf_color_button(self):
  5327. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5328. c_dialog = QtWidgets.QColorDialog()
  5329. plot_fill_color = c_dialog.getColor(initial=current_color)
  5330. if plot_fill_color.isValid() is False:
  5331. return
  5332. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5333. "background-color:%s" % str(plot_fill_color.name()))
  5334. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5335. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5336. self.defaults['global_plot_fill'] = new_val
  5337. def on_pf_color_spinner(self):
  5338. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5339. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5340. self.defaults['global_plot_fill'] = \
  5341. self.defaults['global_plot_fill'][:7] + \
  5342. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5343. self.defaults['global_plot_line'] = \
  5344. self.defaults['global_plot_line'][:7] + \
  5345. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5346. def on_pf_color_slider(self):
  5347. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5348. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5349. def on_pl_color_entry(self):
  5350. self.defaults['global_plot_line'] = \
  5351. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5352. self.defaults['global_plot_line'][7:9]
  5353. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5354. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5355. def on_pl_color_button(self):
  5356. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5357. # print(current_color)
  5358. c_dialog = QtWidgets.QColorDialog()
  5359. plot_line_color = c_dialog.getColor(initial=current_color)
  5360. if plot_line_color.isValid() is False:
  5361. return
  5362. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5363. "background-color:%s" % str(plot_line_color.name()))
  5364. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5365. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5366. self.defaults['global_plot_line'] = new_val_line
  5367. # Setting selection colors (left - right) handlers
  5368. def on_sf_color_entry(self):
  5369. self.defaults['global_sel_fill'] = \
  5370. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5371. self.defaults['global_sel_fill'][7:9]
  5372. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5373. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5374. def on_sf_color_button(self):
  5375. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5376. c_dialog = QtWidgets.QColorDialog()
  5377. plot_fill_color = c_dialog.getColor(initial=current_color)
  5378. if plot_fill_color.isValid() is False:
  5379. return
  5380. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5381. "background-color:%s" % str(plot_fill_color.name()))
  5382. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5383. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5384. self.defaults['global_sel_fill'] = new_val
  5385. def on_sf_color_spinner(self):
  5386. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5387. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5388. self.defaults['global_sel_fill'] = \
  5389. self.defaults['global_sel_fill'][:7] + \
  5390. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5391. self.defaults['global_sel_line'] = \
  5392. self.defaults['global_sel_line'][:7] + \
  5393. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5394. def on_sf_color_slider(self):
  5395. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5396. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5397. def on_sl_color_entry(self):
  5398. self.defaults['global_sel_line'] = \
  5399. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5400. self.defaults['global_sel_line'][7:9]
  5401. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5402. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5403. def on_sl_color_button(self):
  5404. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5405. c_dialog = QtWidgets.QColorDialog()
  5406. plot_line_color = c_dialog.getColor(initial=current_color)
  5407. if plot_line_color.isValid() is False:
  5408. return
  5409. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5410. "background-color:%s" % str(plot_line_color.name()))
  5411. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5412. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5413. self.defaults['global_sel_line'] = new_val_line
  5414. # Setting selection colors (right - left) handlers
  5415. def on_alt_sf_color_entry(self):
  5416. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5417. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5418. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5419. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5420. def on_alt_sf_color_button(self):
  5421. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5422. c_dialog = QtWidgets.QColorDialog()
  5423. plot_fill_color = c_dialog.getColor(initial=current_color)
  5424. if plot_fill_color.isValid() is False:
  5425. return
  5426. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5427. "background-color:%s" % str(plot_fill_color.name()))
  5428. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5429. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5430. self.defaults['global_alt_sel_fill'] = new_val
  5431. def on_alt_sf_color_spinner(self):
  5432. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5433. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5434. self.defaults['global_alt_sel_fill'] = \
  5435. self.defaults['global_alt_sel_fill'][:7] + \
  5436. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5437. self.defaults['global_alt_sel_line'] = \
  5438. self.defaults['global_alt_sel_line'][:7] + \
  5439. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5440. def on_alt_sf_color_slider(self):
  5441. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5442. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5443. def on_alt_sl_color_entry(self):
  5444. self.defaults['global_alt_sel_line'] = \
  5445. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5446. self.defaults['global_alt_sel_line'][7:9]
  5447. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5448. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5449. def on_alt_sl_color_button(self):
  5450. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5451. c_dialog = QtWidgets.QColorDialog()
  5452. plot_line_color = c_dialog.getColor(initial=current_color)
  5453. if plot_line_color.isValid() is False:
  5454. return
  5455. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5456. "background-color:%s" % str(plot_line_color.name()))
  5457. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5458. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5459. self.defaults['global_alt_sel_line'] = new_val_line
  5460. # Setting Editor colors
  5461. def on_draw_color_entry(self):
  5462. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5463. .draw_color_entry.get_value()
  5464. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5465. "background-color:%s" % str(self.defaults['global_draw_color']))
  5466. def on_draw_color_button(self):
  5467. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5468. c_dialog = QtWidgets.QColorDialog()
  5469. draw_color = c_dialog.getColor(initial=current_color)
  5470. if draw_color.isValid() is False:
  5471. return
  5472. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5473. "background-color:%s" % str(draw_color.name()))
  5474. new_val = str(draw_color.name())
  5475. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5476. self.defaults['global_draw_color'] = new_val
  5477. def on_sel_draw_color_entry(self):
  5478. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5479. .sel_draw_color_entry.get_value()
  5480. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5481. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5482. def on_sel_draw_color_button(self):
  5483. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5484. c_dialog = QtWidgets.QColorDialog()
  5485. sel_draw_color = c_dialog.getColor(initial=current_color)
  5486. if sel_draw_color.isValid() is False:
  5487. return
  5488. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5489. "background-color:%s" % str(sel_draw_color.name()))
  5490. new_val_sel = str(sel_draw_color.name())
  5491. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5492. self.defaults['global_sel_draw_color'] = new_val_sel
  5493. def on_proj_color_entry(self):
  5494. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5495. .proj_color_entry.get_value()
  5496. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5497. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5498. def on_proj_color_button(self):
  5499. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5500. c_dialog = QtWidgets.QColorDialog()
  5501. proj_color = c_dialog.getColor(initial=current_color)
  5502. if proj_color.isValid() is False:
  5503. return
  5504. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5505. "background-color:%s" % str(proj_color.name()))
  5506. new_val_sel = str(proj_color.name())
  5507. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5508. self.defaults['global_proj_item_color'] = new_val_sel
  5509. def on_proj_color_dis_entry(self):
  5510. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5511. .proj_color_dis_entry.get_value()
  5512. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5513. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5514. def on_proj_color_dis_button(self):
  5515. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5516. c_dialog = QtWidgets.QColorDialog()
  5517. proj_color = c_dialog.getColor(initial=current_color)
  5518. if proj_color.isValid() is False:
  5519. return
  5520. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5521. "background-color:%s" % str(proj_color.name()))
  5522. new_val_sel = str(proj_color.name())
  5523. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5524. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5525. def on_annotation_fontcolor_entry(self):
  5526. self.defaults['cncjob_annotation_fontcolor'] = \
  5527. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5528. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5529. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5530. def on_annotation_fontcolor_button(self):
  5531. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5532. c_dialog = QtWidgets.QColorDialog()
  5533. annotation_color = c_dialog.getColor(initial=current_color)
  5534. if annotation_color.isValid() is False:
  5535. return
  5536. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5537. "background-color:%s" % str(annotation_color.name()))
  5538. new_val_sel = str(annotation_color.name())
  5539. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5540. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5541. def on_film_color_entry(self):
  5542. self.defaults['tools_film_color'] = \
  5543. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5544. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5545. "background-color:%s;"
  5546. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5547. )
  5548. def on_film_color_button(self):
  5549. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5550. c_dialog = QtWidgets.QColorDialog()
  5551. film_color = c_dialog.getColor(initial=current_color)
  5552. if film_color.isValid() is False:
  5553. return
  5554. # if new color is different then mark that the Preferences are changed
  5555. if film_color != current_color:
  5556. self.on_preferences_edited()
  5557. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5558. "background-color:%s;"
  5559. "border-color: dimgray" % str(film_color.name())
  5560. )
  5561. new_val_sel = str(film_color.name())
  5562. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5563. self.defaults['tools_film_color'] = new_val_sel
  5564. def on_qrcode_fill_color_entry(self):
  5565. self.defaults['tools_qrcode_fill_color'] = \
  5566. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5567. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5568. "background-color:%s;"
  5569. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5570. )
  5571. def on_qrcode_fill_color_button(self):
  5572. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5573. c_dialog = QtWidgets.QColorDialog()
  5574. fill_color = c_dialog.getColor(initial=current_color)
  5575. if fill_color.isValid() is False:
  5576. return
  5577. # if new color is different then mark that the Preferences are changed
  5578. if fill_color != current_color:
  5579. self.on_preferences_edited()
  5580. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5581. "background-color:%s;"
  5582. "border-color: dimgray" % str(fill_color.name())
  5583. )
  5584. new_val_sel = str(fill_color.name())
  5585. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5586. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5587. def on_qrcode_back_color_entry(self):
  5588. self.defaults['tools_qrcode_back_color'] = \
  5589. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5590. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5591. "background-color:%s;"
  5592. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5593. )
  5594. def on_qrcode_back_color_button(self):
  5595. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5596. c_dialog = QtWidgets.QColorDialog()
  5597. back_color = c_dialog.getColor(initial=current_color)
  5598. if back_color.isValid() is False:
  5599. return
  5600. # if new color is different then mark that the Preferences are changed
  5601. if back_color != current_color:
  5602. self.on_preferences_edited()
  5603. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5604. "background-color:%s;"
  5605. "border-color: dimgray" % str(back_color.name())
  5606. )
  5607. new_val_sel = str(back_color.name())
  5608. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5609. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5610. def on_splash_changed(self, state):
  5611. settings = QSettings("Open Source", "FlatCAM")
  5612. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5613. # This will write the setting to the platform specific storage.
  5614. del settings
  5615. def on_tab_rmb_click(self, checked):
  5616. self.ui.notebook.set_detachable(val=checked)
  5617. self.defaults["global_tabs_detachable"] = checked
  5618. self.ui.plot_tab_area.set_detachable(val=checked)
  5619. self.defaults["global_tabs_detachable"] = checked
  5620. def on_tab_setup_context_menu(self):
  5621. initial_checked = self.defaults["global_tabs_detachable"]
  5622. action_name = str(_("Detachable Tabs"))
  5623. action = QtWidgets.QAction(self)
  5624. action.setCheckable(True)
  5625. action.setText(action_name)
  5626. action.setChecked(initial_checked)
  5627. self.ui.notebook.tabBar.addAction(action)
  5628. self.ui.plot_tab_area.tabBar.addAction(action)
  5629. try:
  5630. action.triggered.disconnect()
  5631. except TypeError:
  5632. pass
  5633. action.triggered.connect(self.on_tab_rmb_click)
  5634. def on_deselect_all(self):
  5635. self.collection.set_all_inactive()
  5636. self.delete_selection_shape()
  5637. def on_workspace_modified(self):
  5638. # self.save_defaults(silent=True)
  5639. if self.is_legacy is True:
  5640. self.plotcanvas.delete_workspace()
  5641. self.defaults_read_form()
  5642. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5643. def on_workspace(self):
  5644. if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value():
  5645. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5646. else:
  5647. self.plotcanvas.delete_workspace()
  5648. self.defaults_read_form()
  5649. # self.save_defaults(silent=True)
  5650. def on_workspace_toggle(self):
  5651. state = False if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value() else True
  5652. try:
  5653. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5654. except TypeError:
  5655. pass
  5656. self.ui.general_defaults_form.general_gui_group.workspace_cb.set_value(state)
  5657. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5658. self.on_workspace()
  5659. def on_layout(self, index=None, lay=None):
  5660. """
  5661. Set the toolbars layout (location)
  5662. :param index:
  5663. :param lay: type of layout to be set on the toolbard
  5664. :return: None
  5665. """
  5666. self.report_usage("on_layout()")
  5667. if lay:
  5668. current_layout = lay
  5669. else:
  5670. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5671. lay_settings = QSettings("Open Source", "FlatCAM")
  5672. lay_settings.setValue('layout', current_layout)
  5673. # This will write the setting to the platform specific storage.
  5674. del lay_settings
  5675. # first remove the toolbars:
  5676. try:
  5677. self.ui.removeToolBar(self.ui.toolbarfile)
  5678. self.ui.removeToolBar(self.ui.toolbargeo)
  5679. self.ui.removeToolBar(self.ui.toolbarview)
  5680. self.ui.removeToolBar(self.ui.toolbarshell)
  5681. self.ui.removeToolBar(self.ui.toolbartools)
  5682. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5683. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5684. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5685. self.ui.removeToolBar(self.ui.snap_toolbar)
  5686. self.ui.removeToolBar(self.ui.toolbarshell)
  5687. except Exception:
  5688. pass
  5689. if current_layout == 'standard':
  5690. # ## TOOLBAR INSTALLATION # ##
  5691. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5692. self.ui.toolbarfile.setObjectName('File_TB')
  5693. self.ui.addToolBar(self.ui.toolbarfile)
  5694. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5695. self.ui.toolbargeo.setObjectName('Edit_TB')
  5696. self.ui.addToolBar(self.ui.toolbargeo)
  5697. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5698. self.ui.toolbarview.setObjectName('View_TB')
  5699. self.ui.addToolBar(self.ui.toolbarview)
  5700. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5701. self.ui.toolbarshell.setObjectName('Shell_TB')
  5702. self.ui.addToolBar(self.ui.toolbarshell)
  5703. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5704. self.ui.toolbartools.setObjectName('Tools_TB')
  5705. self.ui.addToolBar(self.ui.toolbartools)
  5706. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5707. # self.ui.exc_edit_toolbar.setVisible(False)
  5708. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5709. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5710. self.ui.addToolBarBreak()
  5711. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5712. # self.ui.geo_edit_toolbar.setVisible(False)
  5713. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5714. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5715. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5716. # self.ui.grb_edit_toolbar.setVisible(False)
  5717. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5718. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5719. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5720. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5721. # self.ui.snap_toolbar.setMaximumHeight(30)
  5722. self.ui.addToolBar(self.ui.snap_toolbar)
  5723. self.ui.corner_snap_btn.setVisible(False)
  5724. self.ui.snap_magnet.setVisible(False)
  5725. elif current_layout == 'compact':
  5726. # ## TOOLBAR INSTALLATION # ##
  5727. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5728. self.ui.toolbarfile.setObjectName('File_TB')
  5729. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5730. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5731. self.ui.toolbargeo.setObjectName('Edit_TB')
  5732. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5733. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5734. self.ui.toolbarshell.setObjectName('Shell_TB')
  5735. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5736. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5737. self.ui.toolbartools.setObjectName('Tools_TB')
  5738. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5739. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5740. # self.ui.geo_edit_toolbar.setVisible(False)
  5741. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5742. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5743. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5744. self.ui.toolbarview.setObjectName('View_TB')
  5745. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5746. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5747. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5748. # self.ui.grb_edit_toolbar.setVisible(False)
  5749. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5750. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5751. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5752. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5753. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5754. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5755. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5756. self.ui.snap_toolbar.setMaximumHeight(30)
  5757. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5758. self.ui.corner_snap_btn.setVisible(True)
  5759. self.ui.snap_magnet.setVisible(True)
  5760. # add all the actions to the toolbars
  5761. self.ui.populate_toolbars()
  5762. # reconnect all the signals to the toolbar actions
  5763. self.connect_toolbar_signals()
  5764. self.ui.grid_snap_btn.setChecked(True)
  5765. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5766. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5767. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5768. self.ui.grid_gap_link_cb.setChecked(True)
  5769. def on_cursor_type(self, val):
  5770. """
  5771. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5772. :return: None
  5773. """
  5774. self.app_cursor.enabled = False
  5775. if val == 'small':
  5776. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5777. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5778. self.app_cursor = self.plotcanvas.new_cursor()
  5779. else:
  5780. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5781. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5782. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5783. if self.ui.grid_snap_btn.isChecked():
  5784. self.app_cursor.enabled = True
  5785. else:
  5786. self.app_cursor.enabled = False
  5787. def on_cnc_custom_parameters(self, signal_text):
  5788. if signal_text == 'Parameters':
  5789. return
  5790. else:
  5791. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5792. def on_save_button(self, save_to_file=True):
  5793. log.debug("App.on_save_button() --> Applying preferences to file.")
  5794. # Preferences saved, update flag
  5795. self.preferences_changed_flag = False
  5796. # Preferences save, update the color of the Preferences Tab text
  5797. for idx in range(self.ui.plot_tab_area.count()):
  5798. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5799. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5800. self.inform.emit('%s' % _("Preferences applied."))
  5801. if save_to_file:
  5802. self.save_defaults(silent=False)
  5803. # load the defaults so they are updated into the app
  5804. self.load_defaults(filename='current_defaults')
  5805. # Re-fresh project options
  5806. self.on_options_app2project()
  5807. settgs = QSettings("Open Source", "FlatCAM")
  5808. # save the notebook font size
  5809. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5810. settgs.setValue('notebook_font_size', fsize)
  5811. # save the axis font size
  5812. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5813. settgs.setValue('axis_font_size', g_fsize)
  5814. # save the textbox font size
  5815. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5816. settgs.setValue('textbox_font_size', tb_fsize)
  5817. settgs.setValue(
  5818. 'machinist',
  5819. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  5820. )
  5821. # This will write the setting to the platform specific storage.
  5822. del settgs
  5823. def on_pref_close_button(self):
  5824. # Preferences saved, update flag
  5825. self.preferences_changed_flag = False
  5826. try:
  5827. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5828. except TypeError:
  5829. pass
  5830. self.defaults_write_form()
  5831. # Preferences save, update the color of the Preferences Tab text
  5832. for idx in range(self.ui.plot_tab_area.count()):
  5833. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5834. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5835. self.ui.plot_tab_area.closeTab(idx)
  5836. break
  5837. self.inform.emit('%s' % _("Preferences closed without saving."))
  5838. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5839. def on_tool_add_keypress(self):
  5840. # ## Current application units in Upper Case
  5841. self.units = self.defaults['units'].upper()
  5842. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5843. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5844. if notebook_widget_name == 'selected_tab':
  5845. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5846. # Tool add works for Geometry only if Advanced is True in Preferences
  5847. if self.defaults["global_app_level"] == 'a':
  5848. tool_add_popup = FCInputDialog(title="New Tool ...",
  5849. text='Enter a Tool Diameter:',
  5850. min=0.0000, max=99.9999, decimals=4)
  5851. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5852. val, ok = tool_add_popup.get_value()
  5853. if ok:
  5854. if float(val) == 0:
  5855. self.inform.emit('[WARNING_NOTCL] %s' %
  5856. _("Please enter a tool diameter with non-zero value, in Float format."))
  5857. return
  5858. self.collection.get_active().on_tool_add(dia=float(val))
  5859. else:
  5860. self.inform.emit('[WARNING_NOTCL] %s...' %
  5861. _("Adding Tool cancelled"))
  5862. else:
  5863. msgbox = QtWidgets.QMessageBox()
  5864. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5865. "Go to Preferences -> General - Show Advanced Options."))
  5866. msgbox.setWindowTitle("Tool adding ...")
  5867. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5868. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5869. msgbox.setDefaultButton(bt_ok)
  5870. msgbox.exec_()
  5871. # work only if the notebook tab on focus is the Tools_Tab
  5872. if notebook_widget_name == 'tool_tab':
  5873. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5874. # and only if the tool is NCC Tool
  5875. if tool_widget == self.ncclear_tool.toolName:
  5876. self.ncclear_tool.on_add_tool_by_key()
  5877. # and only if the tool is Paint Area Tool
  5878. elif tool_widget == self.paint_tool.toolName:
  5879. self.paint_tool.on_add_tool_by_key()
  5880. # and only if the tool is Solder Paste Dispensing Tool
  5881. elif tool_widget == self.paste_tool.toolName:
  5882. self.paste_tool.on_add_tool_by_key()
  5883. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5884. # See description bellow.
  5885. def on_delete_keypress(self):
  5886. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5887. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5888. if notebook_widget_name == 'selected_tab':
  5889. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5890. self.collection.get_active().on_tool_delete()
  5891. # work only if the notebook tab on focus is the Tools_Tab
  5892. elif notebook_widget_name == 'tool_tab':
  5893. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5894. # and only if the tool is NCC Tool
  5895. if tool_widget == self.ncclear_tool.toolName:
  5896. self.ncclear_tool.on_tool_delete()
  5897. # and only if the tool is Paint Tool
  5898. elif tool_widget == self.paint_tool.toolName:
  5899. self.paint_tool.on_tool_delete()
  5900. # and only if the tool is Solder Paste Dispensing Tool
  5901. elif tool_widget == self.paste_tool.toolName:
  5902. self.paste_tool.on_tool_delete()
  5903. else:
  5904. self.on_delete()
  5905. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5906. # some screens you have to be careful where you hover with your mouse.
  5907. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5908. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5909. # Complicated, I know :)
  5910. def on_delete(self):
  5911. """
  5912. Delete the currently selected FlatCAMObjs.
  5913. :return: None
  5914. """
  5915. self.report_usage("on_delete()")
  5916. response = None
  5917. bt_ok = None
  5918. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5919. # a geometry object before we update it.
  5920. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5921. and self.grb_editor.editor_active is False:
  5922. if self.defaults["global_delete_confirmation"] is True:
  5923. msgbox = QtWidgets.QMessageBox()
  5924. msgbox.setWindowTitle(_("Delete objects"))
  5925. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5926. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5927. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5928. "the selected objects?"))
  5929. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5930. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5931. msgbox.setDefaultButton(bt_ok)
  5932. msgbox.exec_()
  5933. response = msgbox.clickedButton()
  5934. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5935. if self.collection.get_active():
  5936. self.log.debug("App.on_delete()")
  5937. while self.collection.get_active():
  5938. obj_active = self.collection.get_active()
  5939. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5940. if isinstance(obj_active, FlatCAMGerber):
  5941. for el in obj_active.mark_shapes:
  5942. obj_active.mark_shapes[el].clear(update=True)
  5943. obj_active.mark_shapes[el].enabled = False
  5944. # obj_active.mark_shapes[el] = None
  5945. del el
  5946. elif isinstance(obj_active, FlatCAMCNCjob):
  5947. try:
  5948. obj_active.annotation.clear(update=True)
  5949. obj_active.annotation.enabled = False
  5950. except AttributeError:
  5951. pass
  5952. self.delete_first_selected()
  5953. self.inform.emit('%s...' %
  5954. _("Object(s) deleted"))
  5955. # make sure that the selection shape is deleted, too
  5956. self.delete_selection_shape()
  5957. else:
  5958. self.inform.emit(_("Failed. No object(s) selected..."))
  5959. else:
  5960. self.inform.emit(_("Save the work in Editor and try again ..."))
  5961. def delete_first_selected(self):
  5962. # Keep this for later
  5963. try:
  5964. sel_obj = self.collection.get_active()
  5965. name = sel_obj.options["name"]
  5966. isPlotted = sel_obj.options["plot"]
  5967. except AttributeError:
  5968. self.log.debug("Nothing selected for deletion")
  5969. return
  5970. if self.is_legacy is True:
  5971. # Remove plot only if the object was plotted otherwise delaxes will fail
  5972. if isPlotted:
  5973. try:
  5974. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5975. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5976. except Exception as e:
  5977. log.debug("App.delete_first_selected() --> %s" % str(e))
  5978. self.plotcanvas.auto_adjust_axes()
  5979. # Remove from dictionary
  5980. self.collection.delete_active()
  5981. # Clear form
  5982. self.setup_component_editor()
  5983. self.inform.emit('%s: %s' %
  5984. (_("Object deleted"), name))
  5985. def on_set_origin(self):
  5986. """
  5987. Set the origin to the left mouse click position
  5988. :return: None
  5989. """
  5990. # display the message for the user
  5991. # and ask him to click on the desired position
  5992. self.report_usage("on_set_origin()")
  5993. def origin_replot():
  5994. def worker_task():
  5995. with self.proc_container.new('%s...' % _("Plotting")):
  5996. for obj in self.collection.get_list():
  5997. obj.plot()
  5998. self.plotcanvas.fit_view()
  5999. if self.is_legacy:
  6000. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6001. else:
  6002. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6003. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6004. self.inform.emit(_('Click to set the origin ...'))
  6005. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6006. # first disconnect it as it may have been used by something else
  6007. try:
  6008. self.replot_signal.disconnect()
  6009. except TypeError:
  6010. pass
  6011. self.replot_signal[list].connect(origin_replot)
  6012. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6013. """
  6014. :param event:
  6015. :param location:
  6016. :param noplot:
  6017. :param use_thread:
  6018. :return:
  6019. """
  6020. noplot_sig = noplot
  6021. def worker_task():
  6022. with self.proc_container.new(_("Setting Origin...")):
  6023. for obj in self.collection.get_list():
  6024. obj.offset((x, y))
  6025. self.object_changed.emit(obj)
  6026. # Update the object bounding box options
  6027. a, b, c, d = obj.bounds()
  6028. obj.options['xmin'] = a
  6029. obj.options['ymin'] = b
  6030. obj.options['xmax'] = c
  6031. obj.options['ymax'] = d
  6032. self.inform.emit('[success] %s...' %
  6033. _('Origin set'))
  6034. if noplot_sig is False:
  6035. self.replot_signal.emit([])
  6036. if location is not None:
  6037. if len(location) != 2:
  6038. self.inform.emit('[ERROR_NOTCL] %s...' %
  6039. _("Origin coordinates specified but incomplete."))
  6040. return 'fail'
  6041. x, y = location
  6042. if use_thread is True:
  6043. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6044. else:
  6045. worker_task()
  6046. self.should_we_save = True
  6047. return
  6048. if event.button == 1:
  6049. if self.is_legacy is False:
  6050. event_pos = event.pos
  6051. else:
  6052. event_pos = (event.xdata, event.ydata)
  6053. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6054. if self.grid_status() == True:
  6055. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6056. else:
  6057. pos = pos_canvas
  6058. x = 0 - pos[0]
  6059. y = 0 - pos[1]
  6060. if use_thread is True:
  6061. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6062. else:
  6063. worker_task()
  6064. self.should_we_save = True
  6065. def on_jump_to(self, custom_location=None, fit_center=True):
  6066. """
  6067. Jump to a location by setting the mouse cursor location
  6068. :return:
  6069. """
  6070. self.report_usage("on_jump_to()")
  6071. # if self.is_legacy is True:
  6072. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  6073. # return
  6074. if not custom_location:
  6075. dia_box_location = None
  6076. try:
  6077. dia_box_location = eval(self.clipboard.text())
  6078. except Exception:
  6079. pass
  6080. if type(dia_box_location) == tuple:
  6081. dia_box_location = str(dia_box_location)
  6082. else:
  6083. dia_box_location = None
  6084. dia_box = Dialog_box(title=_("Jump to ..."),
  6085. label=_("Enter the coordinates in format X,Y:"),
  6086. icon=QtGui.QIcon('share/jump_to16.png'),
  6087. initial_text=dia_box_location)
  6088. if dia_box.ok is True:
  6089. try:
  6090. location = eval(dia_box.location)
  6091. if not isinstance(location, tuple):
  6092. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6093. return
  6094. except Exception:
  6095. return
  6096. else:
  6097. return
  6098. else:
  6099. location = custom_location
  6100. if fit_center:
  6101. self.plotcanvas.fit_center(loc=location)
  6102. cursor = QtGui.QCursor()
  6103. if self.is_legacy is False:
  6104. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6105. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  6106. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  6107. cursor.setPos(j_pos[0], j_pos[1])
  6108. else:
  6109. # find the canvas origin which is in the top left corner
  6110. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6111. # determine the coordinates for the lowest left point of the canvas
  6112. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6113. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6114. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6115. # canvas) and the point (width, height) is in the top-right location
  6116. loc = self.plotcanvas.axes.transData.transform_point(location)
  6117. j_pos = (x0 + loc[0], y0 - loc[1])
  6118. cursor.setPos(j_pos[0], j_pos[1])
  6119. if self.grid_status() == True:
  6120. # Update cursor
  6121. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6122. symbol='++', edge_color=self.cursor_color_3D,
  6123. size=self.defaults["global_cursor_size"])
  6124. # Set the position label
  6125. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6126. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6127. # Set the relative position label
  6128. dx = location[0] - float(self.rel_point1[0])
  6129. dy = location[1] - float(self.rel_point1[1])
  6130. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6131. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6132. self.inform.emit('[success] %s' %
  6133. _("Done."))
  6134. return location
  6135. def on_copy_object(self):
  6136. self.report_usage("on_copy_object()")
  6137. def initialize(obj_init, app):
  6138. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6139. try:
  6140. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6141. except AttributeError:
  6142. pass
  6143. try:
  6144. obj_init.apertures = deepcopy(obj.apertures)
  6145. except AttributeError:
  6146. pass
  6147. try:
  6148. if obj.tools:
  6149. obj_init.tools = deepcopy(obj.tools)
  6150. except Exception as e:
  6151. log.debug("App.on_copy_object() --> %s" % str(e))
  6152. try:
  6153. obj_init.source_file = deepcopy(obj.source_file)
  6154. except (AttributeError, TypeError):
  6155. pass
  6156. def initialize_excellon(obj_init, app):
  6157. obj_init.source_file = deepcopy(obj.source_file)
  6158. obj_init.tools = deepcopy(obj.tools)
  6159. # drills are offset, so they need to be deep copied
  6160. obj_init.drills = deepcopy(obj.drills)
  6161. # slots are offset, so they need to be deep copied
  6162. obj_init.slots = deepcopy(obj.slots)
  6163. obj_init.create_geometry()
  6164. def initialize_script(obj_init, app_obj):
  6165. obj_init.source_file = deepcopy(obj.source_file)
  6166. def initialize_document(obj_init, app_obj):
  6167. obj_init.source_file = deepcopy(obj.source_file)
  6168. for obj in self.collection.get_selected():
  6169. obj_name = obj.options["name"]
  6170. try:
  6171. if isinstance(obj, FlatCAMExcellon):
  6172. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6173. elif isinstance(obj, FlatCAMGerber):
  6174. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6175. elif isinstance(obj, FlatCAMGeometry):
  6176. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6177. elif isinstance(obj, FlatCAMScript):
  6178. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6179. elif isinstance(obj, FlatCAMDocument):
  6180. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6181. except Exception as e:
  6182. return "Operation failed: %s" % str(e)
  6183. def on_copy_object2(self, custom_name):
  6184. def initialize_geometry(obj_init, app):
  6185. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6186. try:
  6187. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6188. except AttributeError:
  6189. pass
  6190. try:
  6191. obj_init.apertures = deepcopy(obj.apertures)
  6192. except AttributeError:
  6193. pass
  6194. try:
  6195. if obj.tools:
  6196. obj_init.tools = deepcopy(obj.tools)
  6197. except Exception as ee:
  6198. log.debug("on_copy_object2() --> %s" % str(ee))
  6199. def initialize_gerber(obj_init, app):
  6200. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6201. obj_init.apertures = deepcopy(obj.apertures)
  6202. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6203. def initialize_excellon(obj_init, app):
  6204. obj_init.tools = deepcopy(obj.tools)
  6205. # drills are offset, so they need to be deep copied
  6206. obj_init.drills = deepcopy(obj.drills)
  6207. # slots are offset, so they need to be deep copied
  6208. obj_init.slots = deepcopy(obj.slots)
  6209. obj_init.create_geometry()
  6210. for obj in self.collection.get_selected():
  6211. obj_name = obj.options["name"]
  6212. try:
  6213. if isinstance(obj, FlatCAMExcellon):
  6214. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6215. elif isinstance(obj, FlatCAMGerber):
  6216. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6217. elif isinstance(obj, FlatCAMGeometry):
  6218. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6219. except Exception as e:
  6220. return "Operation failed: %s" % str(e)
  6221. def on_rename_object(self, text):
  6222. self.report_usage("on_rename_object()")
  6223. named_obj = self.collection.get_active()
  6224. for obj in named_obj:
  6225. if obj is list:
  6226. self.on_rename_object(text)
  6227. else:
  6228. try:
  6229. obj.options['name'] = text
  6230. except Exception as e:
  6231. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6232. def convert_any2geo(self):
  6233. self.report_usage("convert_any2geo()")
  6234. def initialize(obj_init, app):
  6235. obj_init.solid_geometry = obj.solid_geometry
  6236. try:
  6237. obj_init.follow_geometry = obj.follow_geometry
  6238. except AttributeError:
  6239. pass
  6240. try:
  6241. obj_init.apertures = obj.apertures
  6242. except AttributeError:
  6243. pass
  6244. try:
  6245. if obj.tools:
  6246. obj_init.tools = obj.tools
  6247. except AttributeError:
  6248. pass
  6249. def initialize_excellon(obj_init, app):
  6250. # objs = self.collection.get_selected()
  6251. # FlatCAMGeometry.merge(objs, obj)
  6252. solid_geo = []
  6253. for tool in obj.tools:
  6254. for geo in obj.tools[tool]['solid_geometry']:
  6255. solid_geo.append(geo)
  6256. obj_init.solid_geometry = deepcopy(solid_geo)
  6257. if not self.collection.get_selected():
  6258. log.warning("App.convert_any2geo --> No object selected")
  6259. self.inform.emit('[WARNING_NOTCL] %s' %
  6260. _("No object is selected. Select an object and try again."))
  6261. return
  6262. for obj in self.collection.get_selected():
  6263. obj_name = obj.options["name"]
  6264. try:
  6265. if isinstance(obj, FlatCAMExcellon):
  6266. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6267. else:
  6268. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6269. except Exception as e:
  6270. return "Operation failed: %s" % str(e)
  6271. def convert_any2gerber(self):
  6272. self.report_usage("convert_any2gerber()")
  6273. def initialize_geometry(obj_init, app):
  6274. apertures = {}
  6275. apid = 0
  6276. apertures[str(apid)] = {}
  6277. apertures[str(apid)]['geometry'] = []
  6278. for obj_orig in obj.solid_geometry:
  6279. new_elem = dict()
  6280. new_elem['solid'] = obj_orig
  6281. try:
  6282. new_elem['follow'] = obj_orig.exterior
  6283. except AttributeError:
  6284. pass
  6285. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6286. apertures[str(apid)]['size'] = 0.0
  6287. apertures[str(apid)]['type'] = 'C'
  6288. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6289. obj_init.apertures = deepcopy(apertures)
  6290. def initialize_excellon(obj_init, app):
  6291. apertures = {}
  6292. apid = 10
  6293. for tool in obj.tools:
  6294. apertures[str(apid)] = {}
  6295. apertures[str(apid)]['geometry'] = []
  6296. for geo in obj.tools[tool]['solid_geometry']:
  6297. new_el = dict()
  6298. new_el['solid'] = geo
  6299. new_el['follow'] = geo.exterior
  6300. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6301. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6302. apertures[str(apid)]['type'] = 'C'
  6303. apid += 1
  6304. # create solid_geometry
  6305. solid_geometry = []
  6306. for apid in apertures:
  6307. for geo_el in apertures[apid]['geometry']:
  6308. solid_geometry.append(geo_el['solid'])
  6309. solid_geometry = MultiPolygon(solid_geometry)
  6310. solid_geometry = solid_geometry.buffer(0.0000001)
  6311. obj_init.solid_geometry = deepcopy(solid_geometry)
  6312. obj_init.apertures = deepcopy(apertures)
  6313. # clear the working objects (perhaps not necessary due of Python GC)
  6314. apertures.clear()
  6315. if not self.collection.get_selected():
  6316. log.warning("App.convert_any2gerber --> No object selected")
  6317. self.inform.emit('[WARNING_NOTCL] %s' %
  6318. _("No object is selected. Select an object and try again."))
  6319. return
  6320. for obj in self.collection.get_selected():
  6321. obj_name = obj.options["name"]
  6322. try:
  6323. if isinstance(obj, FlatCAMExcellon):
  6324. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6325. elif isinstance(obj, FlatCAMGeometry):
  6326. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6327. else:
  6328. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6329. except Exception as e:
  6330. return "Operation failed: %s" % str(e)
  6331. def abort_all_tasks(self):
  6332. if self.abort_flag is False:
  6333. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6334. self.abort_flag = True
  6335. def app_is_idle(self):
  6336. if self.abort_flag:
  6337. self.inform.emit('[WARNING_NOTCL] %s' %
  6338. _("The current task was gracefully closed on user request..."))
  6339. self.abort_flag = False
  6340. def on_selectall(self):
  6341. self.report_usage("on_selectall()")
  6342. # delete the possible selection box around a possible selected object
  6343. self.delete_selection_shape()
  6344. for name in self.collection.get_names():
  6345. self.collection.set_active(name)
  6346. curr_sel_obj = self.collection.get_by_name(name)
  6347. # create the selection box around the selected object
  6348. if self.defaults['global_selection_shape'] is True:
  6349. self.draw_selection_shape(curr_sel_obj)
  6350. def on_preferences(self):
  6351. """
  6352. Adds the Preferences in a Tab in Plot Area
  6353. :return:
  6354. """
  6355. # add the tab if it was closed
  6356. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6357. # delete the absolute and relative position and messages in the infobar
  6358. self.ui.position_label.setText("")
  6359. self.ui.rel_position_label.setText("")
  6360. # Switch plot_area to preferences page
  6361. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6362. # self.ui.show()
  6363. # detect changes in the preferences
  6364. for idx in range(self.ui.pref_tab_area.count()):
  6365. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6366. try:
  6367. try:
  6368. tb.textEdited.disconnect(self.on_preferences_edited)
  6369. except (TypeError, AttributeError):
  6370. pass
  6371. tb.textEdited.connect(self.on_preferences_edited)
  6372. except AttributeError:
  6373. pass
  6374. try:
  6375. try:
  6376. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6377. except (TypeError, AttributeError):
  6378. pass
  6379. tb.modificationChanged.connect(self.on_preferences_edited)
  6380. except AttributeError:
  6381. pass
  6382. try:
  6383. try:
  6384. tb.toggled.disconnect(self.on_preferences_edited)
  6385. except (TypeError, AttributeError):
  6386. pass
  6387. tb.toggled.connect(self.on_preferences_edited)
  6388. except AttributeError:
  6389. pass
  6390. try:
  6391. try:
  6392. tb.valueChanged.disconnect(self.on_preferences_edited)
  6393. except (TypeError, AttributeError):
  6394. pass
  6395. tb.valueChanged.connect(self.on_preferences_edited)
  6396. except AttributeError:
  6397. pass
  6398. try:
  6399. try:
  6400. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6401. except (TypeError, AttributeError):
  6402. pass
  6403. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6404. except AttributeError:
  6405. pass
  6406. def on_preferences_edited(self):
  6407. self.inform.emit('[WARNING_NOTCL] %s' %
  6408. _("Preferences edited but not saved."))
  6409. for idx in range(self.ui.plot_tab_area.count()):
  6410. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6411. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6412. self.preferences_changed_flag = True
  6413. def on_tools_database(self):
  6414. """
  6415. Adds the Tools Database in a Tab in Plot Area
  6416. :return:
  6417. """
  6418. for idx in range(self.ui.plot_tab_area.count()):
  6419. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6420. # there can be only one instance of Tools Database at one time
  6421. return
  6422. self.tools_db_tab = ToolsDB(
  6423. app=self,
  6424. parent=self.ui,
  6425. callback_on_edited=self.on_tools_db_edited,
  6426. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6427. )
  6428. # add the tab if it was closed
  6429. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6430. self.tools_db_tab.setObjectName("database_tab")
  6431. # delete the absolute and relative position and messages in the infobar
  6432. self.ui.position_label.setText("")
  6433. self.ui.rel_position_label.setText("")
  6434. # Switch plot_area to preferences page
  6435. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6436. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6437. self.tools_db_tab.ui_connect()
  6438. def on_tools_db_edited(self):
  6439. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6440. for idx in range(self.ui.plot_tab_area.count()):
  6441. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6442. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6443. self.tools_db_changed_flag = True
  6444. def on_geometry_tool_add_from_db_executed(self, tool):
  6445. """
  6446. Here add the tool from DB in the selected geometry object
  6447. :return:
  6448. """
  6449. tool_from_db = deepcopy(tool)
  6450. obj = self.collection.get_active()
  6451. if isinstance(obj, FlatCAMGeometry):
  6452. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6453. for idx in range(self.ui.plot_tab_area.count()):
  6454. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6455. wdg = self.ui.plot_tab_area.widget(idx)
  6456. wdg.deleteLater()
  6457. self.ui.plot_tab_area.removeTab(idx)
  6458. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6459. else:
  6460. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6461. def on_plot_area_tab_closed(self, title):
  6462. if title == _("Preferences"):
  6463. # disconnect
  6464. for idx in range(self.ui.pref_tab_area.count()):
  6465. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6466. try:
  6467. tb.textEdited.disconnect(self.on_preferences_edited)
  6468. except (TypeError, AttributeError):
  6469. pass
  6470. try:
  6471. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6472. except (TypeError, AttributeError):
  6473. pass
  6474. try:
  6475. tb.toggled.disconnect(self.on_preferences_edited)
  6476. except (TypeError, AttributeError):
  6477. pass
  6478. try:
  6479. tb.valueChanged.disconnect(self.on_preferences_edited)
  6480. except (TypeError, AttributeError):
  6481. pass
  6482. try:
  6483. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6484. except (TypeError, AttributeError):
  6485. pass
  6486. if self.preferences_changed_flag is True:
  6487. msgbox = QtWidgets.QMessageBox()
  6488. msgbox.setText(_("One or more values are changed.\n"
  6489. "Do you want to save the Preferences?"))
  6490. msgbox.setWindowTitle(_("Save Preferences"))
  6491. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6492. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6493. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6494. msgbox.setDefaultButton(bt_yes)
  6495. msgbox.exec_()
  6496. response = msgbox.clickedButton()
  6497. if response == bt_yes:
  6498. self.on_save_button(save_to_file=True)
  6499. self.inform.emit('[success] %s' % _("Preferences saved."))
  6500. else:
  6501. self.preferences_changed_flag = False
  6502. self.inform.emit('')
  6503. return
  6504. if title == _("Tools Database"):
  6505. # disconnect the signals from the table widget in tab
  6506. self.tools_db_tab.ui_disconnect()
  6507. if self.tools_db_changed_flag is True:
  6508. msgbox = QtWidgets.QMessageBox()
  6509. msgbox.setText(_("One or more Tools are edited.\n"
  6510. "Do you want to update the Tools Database?"))
  6511. msgbox.setWindowTitle(_("Save Tools Database"))
  6512. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6513. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6514. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6515. msgbox.setDefaultButton(bt_yes)
  6516. msgbox.exec_()
  6517. response = msgbox.clickedButton()
  6518. if response == bt_yes:
  6519. self.tools_db_tab.on_save_tools_db()
  6520. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6521. else:
  6522. self.tools_db_changed_flag = False
  6523. self.inform.emit('')
  6524. return
  6525. self.tools_db_tab.deleteLater()
  6526. if title == _("Code Editor"):
  6527. self.toggle_codeeditor = False
  6528. if title == _("Bookmarks Manager"):
  6529. self.book_dialog_tab.rebuild_actions()
  6530. self.book_dialog_tab.deleteLater()
  6531. def on_flipy(self):
  6532. self.report_usage("on_flipy()")
  6533. obj_list = self.collection.get_selected()
  6534. xminlist = []
  6535. yminlist = []
  6536. xmaxlist = []
  6537. ymaxlist = []
  6538. if not obj_list:
  6539. self.inform.emit('[WARNING_NOTCL] %s' %
  6540. _("No object selected to Flip on Y axis."))
  6541. else:
  6542. try:
  6543. # first get a bounding box to fit all
  6544. for obj in obj_list:
  6545. xmin, ymin, xmax, ymax = obj.bounds()
  6546. xminlist.append(xmin)
  6547. yminlist.append(ymin)
  6548. xmaxlist.append(xmax)
  6549. ymaxlist.append(ymax)
  6550. # get the minimum x,y and maximum x,y for all objects selected
  6551. xminimal = min(xminlist)
  6552. yminimal = min(yminlist)
  6553. xmaximal = max(xmaxlist)
  6554. ymaximal = max(ymaxlist)
  6555. px = 0.5 * (xminimal + xmaximal)
  6556. py = 0.5 * (yminimal + ymaximal)
  6557. # execute mirroring
  6558. for obj in obj_list:
  6559. obj.mirror('X', [px, py])
  6560. obj.plot()
  6561. self.object_changed.emit(obj)
  6562. self.inform.emit('[success] %s' %
  6563. _("Flip on Y axis done."))
  6564. except Exception as e:
  6565. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6566. return
  6567. def on_flipx(self):
  6568. self.report_usage("on_flipx()")
  6569. obj_list = self.collection.get_selected()
  6570. xminlist = []
  6571. yminlist = []
  6572. xmaxlist = []
  6573. ymaxlist = []
  6574. if not obj_list:
  6575. self.inform.emit('[WARNING_NOTCL] %s' %
  6576. _("No object selected to Flip on X axis."))
  6577. else:
  6578. try:
  6579. # first get a bounding box to fit all
  6580. for obj in obj_list:
  6581. xmin, ymin, xmax, ymax = obj.bounds()
  6582. xminlist.append(xmin)
  6583. yminlist.append(ymin)
  6584. xmaxlist.append(xmax)
  6585. ymaxlist.append(ymax)
  6586. # get the minimum x,y and maximum x,y for all objects selected
  6587. xminimal = min(xminlist)
  6588. yminimal = min(yminlist)
  6589. xmaximal = max(xmaxlist)
  6590. ymaximal = max(ymaxlist)
  6591. px = 0.5 * (xminimal + xmaximal)
  6592. py = 0.5 * (yminimal + ymaximal)
  6593. # execute mirroring
  6594. for obj in obj_list:
  6595. obj.mirror('Y', [px, py])
  6596. obj.plot()
  6597. self.object_changed.emit(obj)
  6598. self.inform.emit('[success] %s' %
  6599. _("Flip on X axis done."))
  6600. except Exception as e:
  6601. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6602. return
  6603. def on_rotate(self, silent=False, preset=None):
  6604. self.report_usage("on_rotate()")
  6605. obj_list = self.collection.get_selected()
  6606. xminlist = []
  6607. yminlist = []
  6608. xmaxlist = []
  6609. ymaxlist = []
  6610. if not obj_list:
  6611. self.inform.emit('[WARNING_NOTCL] %s' %
  6612. _("No object selected to Rotate."))
  6613. else:
  6614. if silent is False:
  6615. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6616. min=-360, max=360, decimals=4,
  6617. init_val=float(self.defaults['tools_transform_rotate']))
  6618. num, ok = rotatebox.get_value()
  6619. else:
  6620. num = preset
  6621. ok = True
  6622. if ok:
  6623. try:
  6624. # first get a bounding box to fit all
  6625. for obj in obj_list:
  6626. xmin, ymin, xmax, ymax = obj.bounds()
  6627. xminlist.append(xmin)
  6628. yminlist.append(ymin)
  6629. xmaxlist.append(xmax)
  6630. ymaxlist.append(ymax)
  6631. # get the minimum x,y and maximum x,y for all objects selected
  6632. xminimal = min(xminlist)
  6633. yminimal = min(yminlist)
  6634. xmaximal = max(xmaxlist)
  6635. ymaximal = max(ymaxlist)
  6636. px = 0.5 * (xminimal + xmaximal)
  6637. py = 0.5 * (yminimal + ymaximal)
  6638. for sel_obj in obj_list:
  6639. sel_obj.rotate(-float(num), point=(px, py))
  6640. sel_obj.plot()
  6641. self.object_changed.emit(sel_obj)
  6642. self.inform.emit('[success] %s' %
  6643. _("Rotation done."))
  6644. except Exception as e:
  6645. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6646. return
  6647. def on_skewx(self):
  6648. self.report_usage("on_skewx()")
  6649. obj_list = self.collection.get_selected()
  6650. xminlist = []
  6651. yminlist = []
  6652. if not obj_list:
  6653. self.inform.emit('[WARNING_NOTCL] %s' %
  6654. _("No object selected to Skew/Shear on X axis."))
  6655. else:
  6656. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6657. min=-360, max=360, decimals=4,
  6658. init_val=float(self.defaults['tools_transform_skew_x']))
  6659. num, ok = skewxbox.get_value()
  6660. if ok:
  6661. # first get a bounding box to fit all
  6662. for obj in obj_list:
  6663. xmin, ymin, xmax, ymax = obj.bounds()
  6664. xminlist.append(xmin)
  6665. yminlist.append(ymin)
  6666. # get the minimum x,y and maximum x,y for all objects selected
  6667. xminimal = min(xminlist)
  6668. yminimal = min(yminlist)
  6669. for obj in obj_list:
  6670. obj.skew(num, 0, point=(xminimal, yminimal))
  6671. obj.plot()
  6672. self.object_changed.emit(obj)
  6673. self.inform.emit('[success] %s' %
  6674. _("Skew on X axis done."))
  6675. def on_skewy(self):
  6676. self.report_usage("on_skewy()")
  6677. obj_list = self.collection.get_selected()
  6678. xminlist = []
  6679. yminlist = []
  6680. if not obj_list:
  6681. self.inform.emit('[WARNING_NOTCL] %s' %
  6682. _("No object selected to Skew/Shear on Y axis."))
  6683. else:
  6684. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6685. min=-360, max=360, decimals=4,
  6686. init_val=float(self.defaults['tools_transform_skew_y']))
  6687. num, ok = skewybox.get_value()
  6688. if ok:
  6689. # first get a bounding box to fit all
  6690. for obj in obj_list:
  6691. xmin, ymin, xmax, ymax = obj.bounds()
  6692. xminlist.append(xmin)
  6693. yminlist.append(ymin)
  6694. # get the minimum x,y and maximum x,y for all objects selected
  6695. xminimal = min(xminlist)
  6696. yminimal = min(yminlist)
  6697. for obj in obj_list:
  6698. obj.skew(0, num, point=(xminimal, yminimal))
  6699. obj.plot()
  6700. self.object_changed.emit(obj)
  6701. self.inform.emit('[success] %s' %
  6702. _("Skew on Y axis done."))
  6703. def on_plots_updated(self):
  6704. """
  6705. Callback used to report when the plots have changed.
  6706. Adjust axes and zooms to fit.
  6707. :return: None
  6708. """
  6709. if self.is_legacy is False:
  6710. self.plotcanvas.update() # TODO: Need update canvas?
  6711. else:
  6712. self.plotcanvas.auto_adjust_axes()
  6713. self.on_zoom_fit(None)
  6714. self.collection.update_view()
  6715. # self.inform.emit(_("Plots updated ..."))
  6716. # TODO: Rework toolbar 'clear', 'replot' functions
  6717. def on_toolbar_replot(self):
  6718. """
  6719. Callback for toolbar button. Re-plots all objects.
  6720. :return: None
  6721. """
  6722. self.report_usage("on_toolbar_replot")
  6723. self.log.debug("on_toolbar_replot()")
  6724. try:
  6725. self.collection.get_active().read_form()
  6726. except AttributeError:
  6727. self.log.debug("on_toolbar_replot(): AttributeError")
  6728. pass
  6729. self.plot_all()
  6730. def on_row_activated(self, index):
  6731. if index.isValid():
  6732. if index.internalPointer().parent_item != self.collection.root_item:
  6733. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6734. self.collection.on_item_activated(index)
  6735. def on_row_selected(self, obj_name):
  6736. # this is a special string; when received it will make all entries unchecked
  6737. # it mean we clicked outside of the items and deselected all
  6738. if obj_name == 'none':
  6739. for act in self.ui.menuobjects.actions():
  6740. act.setChecked(False)
  6741. return
  6742. # get the name of the selected objects and add them to a list
  6743. name_list = list()
  6744. for obj in self.collection.get_selected():
  6745. name_list.append(obj.options['name'])
  6746. # set all actions as unchecked but the ones selected make them checked
  6747. for act in self.ui.menuobjects.actions():
  6748. act.setChecked(False)
  6749. if act.text() in name_list:
  6750. act.setChecked(True)
  6751. def on_collection_updated(self, obj, state, old_name):
  6752. """
  6753. Create a menu from the object loaded in the collection.
  6754. TODO: should use the collection model to do this
  6755. :param obj: object that was changd (added, deleted, renamed)
  6756. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6757. :param old_name: the old name of the object before the action that triggered this slot happened
  6758. :return: None
  6759. """
  6760. icon_files = {
  6761. "gerber": "share/flatcam_icon16.png",
  6762. "excellon": "share/drill16.png",
  6763. "cncjob": "share/cnc16.png",
  6764. "geometry": "share/geometry16.png",
  6765. "script": "share/script_new16.png",
  6766. "document": "share/notes16_1.png"
  6767. }
  6768. if state == 'append':
  6769. for act in self.ui.menuobjects.actions():
  6770. try:
  6771. act.triggered.disconnect()
  6772. except TypeError:
  6773. pass
  6774. self.ui.menuobjects.clear()
  6775. gerber_list = list()
  6776. exc_list = list()
  6777. cncjob_list = list()
  6778. geo_list = list()
  6779. script_list = list()
  6780. doc_list = list()
  6781. for name in self.collection.get_names():
  6782. obj_named = self.collection.get_by_name(name)
  6783. if obj_named.kind == 'gerber':
  6784. gerber_list.append(name)
  6785. elif obj_named.kind == 'excellon':
  6786. exc_list.append(name)
  6787. elif obj_named.kind == 'cncjob':
  6788. cncjob_list.append(name)
  6789. elif obj_named.kind == 'geometry':
  6790. geo_list.append(name)
  6791. elif obj_named.kind == 'script':
  6792. script_list.append(name)
  6793. elif obj_named.kind == 'document':
  6794. doc_list.append(name)
  6795. def add_act(o_name):
  6796. obj_for_icon = self.collection.get_by_name(o_name)
  6797. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6798. add_action.setCheckable(True)
  6799. add_action.setText(o_name)
  6800. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6801. add_action.triggered.connect(
  6802. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6803. self.collection.set_inactive(o_name))
  6804. self.ui.menuobjects.addAction(add_action)
  6805. for name in gerber_list:
  6806. add_act(name)
  6807. self.ui.menuobjects.addSeparator()
  6808. for name in exc_list:
  6809. add_act(name)
  6810. self.ui.menuobjects.addSeparator()
  6811. for name in cncjob_list:
  6812. add_act(name)
  6813. self.ui.menuobjects.addSeparator()
  6814. for name in geo_list:
  6815. add_act(name)
  6816. self.ui.menuobjects.addSeparator()
  6817. for name in script_list:
  6818. add_act(name)
  6819. self.ui.menuobjects.addSeparator()
  6820. for name in doc_list:
  6821. add_act(name)
  6822. self.ui.menuobjects.addSeparator()
  6823. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6824. QtGui.QIcon('share/select_all.png'),
  6825. _('Select All')
  6826. )
  6827. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6828. QtGui.QIcon('share/deselect_all32.png'),
  6829. _('Deselect All')
  6830. )
  6831. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6832. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6833. elif state == 'delete':
  6834. for act in self.ui.menuobjects.actions():
  6835. if act.text() == obj.options['name']:
  6836. try:
  6837. act.triggered.disconnect()
  6838. except TypeError:
  6839. pass
  6840. self.ui.menuobjects.removeAction(act)
  6841. break
  6842. elif state == 'rename':
  6843. for act in self.ui.menuobjects.actions():
  6844. if act.text() == old_name:
  6845. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6846. add_action.setText(obj.options['name'])
  6847. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6848. add_action.triggered.connect(
  6849. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6850. self.collection.set_inactive(obj.options['name']))
  6851. self.ui.menuobjects.insertAction(act, add_action)
  6852. try:
  6853. act.triggered.disconnect()
  6854. except TypeError:
  6855. pass
  6856. self.ui.menuobjects.removeAction(act)
  6857. break
  6858. elif state == 'delete_all':
  6859. for act in self.ui.menuobjects.actions():
  6860. try:
  6861. act.triggered.disconnect()
  6862. except TypeError:
  6863. pass
  6864. self.ui.menuobjects.clear()
  6865. self.ui.menuobjects.addSeparator()
  6866. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6867. QtGui.QIcon('share/select_all.png'),
  6868. _('Select All')
  6869. )
  6870. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6871. QtGui.QIcon('share/deselect_all32.png'),
  6872. _('Deselect All')
  6873. )
  6874. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6875. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6876. def on_objects_selection(self, on_off):
  6877. obj_list = self.collection.get_names()
  6878. if on_off is True:
  6879. self.collection.set_all_active()
  6880. for act in self.ui.menuobjects.actions():
  6881. try:
  6882. act.setChecked(True)
  6883. except Exception:
  6884. pass
  6885. if obj_list:
  6886. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6887. else:
  6888. self.collection.set_all_inactive()
  6889. for act in self.ui.menuobjects.actions():
  6890. try:
  6891. act.setChecked(False)
  6892. except Exception:
  6893. pass
  6894. if obj_list:
  6895. self.inform.emit('%s' % _("Objects selection is cleared."))
  6896. else:
  6897. self.inform.emit('')
  6898. def grid_status(self):
  6899. if self.ui.grid_snap_btn.isChecked():
  6900. return True
  6901. else:
  6902. return False
  6903. def populate_cmenu_grids(self):
  6904. units = self.defaults['units'].lower()
  6905. self.ui.cmenu_gridmenu.clear()
  6906. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6907. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6908. grid_toggle.setCheckable(True)
  6909. if self.grid_status() == True:
  6910. grid_toggle.setChecked(True)
  6911. else:
  6912. grid_toggle.setChecked(False)
  6913. self.ui.cmenu_gridmenu.addSeparator()
  6914. for grid in sorted_list:
  6915. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6916. action.triggered.connect(self.set_grid)
  6917. self.ui.cmenu_gridmenu.addSeparator()
  6918. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6919. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6920. grid_add.triggered.connect(self.on_grid_add)
  6921. grid_delete.triggered.connect(self.on_grid_delete)
  6922. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6923. def set_grid(self):
  6924. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6925. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6926. def on_grid_add(self):
  6927. # ## Current application units in lower Case
  6928. units = self.defaults['units'].lower()
  6929. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6930. text=_('Enter a Grid Value:'),
  6931. min=0.0000, max=99.9999, decimals=4)
  6932. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6933. val, ok = grid_add_popup.get_value()
  6934. if ok:
  6935. if float(val) == 0:
  6936. self.inform.emit('[WARNING_NOTCL] %s' %
  6937. _("Please enter a grid value with non-zero value, in Float format."))
  6938. return
  6939. else:
  6940. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6941. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6942. self.inform.emit('[success] %s...' %
  6943. _("New Grid added"))
  6944. else:
  6945. self.inform.emit('[WARNING_NOTCL] %s...' %
  6946. _("Grid already exists"))
  6947. else:
  6948. self.inform.emit('[WARNING_NOTCL] %s...' %
  6949. _("Adding New Grid cancelled"))
  6950. def on_grid_delete(self):
  6951. # ## Current application units in lower Case
  6952. units = self.defaults['units'].lower()
  6953. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6954. text='Enter a Grid Value:',
  6955. min=0.0000, max=99.9999, decimals=4)
  6956. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6957. val, ok = grid_del_popup.get_value()
  6958. if ok:
  6959. if float(val) == 0:
  6960. self.inform.emit('[WARNING_NOTCL] %s' %
  6961. _("Please enter a grid value with non-zero value, in Float format."))
  6962. return
  6963. else:
  6964. try:
  6965. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6966. except ValueError:
  6967. self.inform.emit('[ERROR_NOTCL]%s...' %
  6968. _(" Grid Value does not exist"))
  6969. return
  6970. self.inform.emit('[success] %s...' %
  6971. _("Grid Value deleted"))
  6972. else:
  6973. self.inform.emit('[WARNING_NOTCL] %s...' %
  6974. _("Delete Grid value cancelled"))
  6975. def on_shortcut_list(self):
  6976. self.report_usage("on_shortcut_list()")
  6977. # add the tab if it was closed
  6978. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6979. # delete the absolute and relative position and messages in the infobar
  6980. self.ui.position_label.setText("")
  6981. self.ui.rel_position_label.setText("")
  6982. # Switch plot_area to preferences page
  6983. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6984. # self.ui.show()
  6985. def on_select_tab(self, name):
  6986. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6987. if self.ui.splitter.sizes()[0] == 0:
  6988. self.ui.splitter.setSizes([1, 1])
  6989. else:
  6990. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6991. self.ui.splitter.setSizes([0, 1])
  6992. if name == 'project':
  6993. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6994. elif name == 'selected':
  6995. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6996. elif name == 'tool':
  6997. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6998. def on_copy_name(self):
  6999. self.report_usage("on_copy_name()")
  7000. obj = self.collection.get_active()
  7001. try:
  7002. name = obj.options["name"]
  7003. except AttributeError:
  7004. log.debug("on_copy_name() --> No object selected to copy it's name")
  7005. self.inform.emit('[WARNING_NOTCL]%s' %
  7006. _(" No object selected to copy it's name"))
  7007. return
  7008. self.clipboard.setText(name)
  7009. self.inform.emit(_("Name copied on clipboard ..."))
  7010. def on_mouse_click_over_plot(self, event):
  7011. """
  7012. Default actions are:
  7013. :param event: Contains information about the event, like which button
  7014. was clicked, the pixel coordinates and the axes coordinates.
  7015. :return: None
  7016. """
  7017. self.pos = []
  7018. if self.is_legacy is False:
  7019. event_pos = event.pos
  7020. if self.defaults["global_pan_button"] == '2':
  7021. pan_button = 2
  7022. else:
  7023. pan_button = 3
  7024. # Set the mouse button for panning
  7025. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7026. else:
  7027. event_pos = (event.xdata, event.ydata)
  7028. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7029. if self.defaults["global_pan_button"] == '2':
  7030. pan_button = 3
  7031. else:
  7032. pan_button = 2
  7033. # So it can receive key presses
  7034. self.plotcanvas.native.setFocus()
  7035. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7036. if self.grid_status() == True:
  7037. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7038. else:
  7039. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7040. try:
  7041. if event.button == 1:
  7042. # Reset here the relative coordinates so there is a new reference on the click position
  7043. if self.rel_point1 is None:
  7044. self.rel_point1 = self.pos
  7045. else:
  7046. self.rel_point2 = copy(self.rel_point1)
  7047. self.rel_point1 = self.pos
  7048. self.on_mouse_move_over_plot(event, origin_click=True)
  7049. except Exception as e:
  7050. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7051. def on_mouse_double_click_over_plot(self, event):
  7052. if event.button == 1:
  7053. self.doubleclick = True
  7054. def on_mouse_move_over_plot(self, event, origin_click=None):
  7055. """
  7056. Callback for the mouse motion event over the plot.
  7057. :param event: Contains information about the event.
  7058. :param origin_click
  7059. :return: None
  7060. """
  7061. if self.is_legacy is False:
  7062. event_pos = event.pos
  7063. if self.defaults["global_pan_button"] == '2':
  7064. pan_button = 2
  7065. else:
  7066. pan_button = 3
  7067. self.event_is_dragging = event.is_dragging
  7068. else:
  7069. event_pos = (event.xdata, event.ydata)
  7070. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7071. if self.defaults["global_pan_button"] == '2':
  7072. pan_button = 3
  7073. else:
  7074. pan_button = 2
  7075. self.event_is_dragging = self.plotcanvas.is_dragging
  7076. # So it can receive key presses
  7077. self.plotcanvas.native.setFocus()
  7078. self.pos_jump = event_pos
  7079. self.ui.popMenu.mouse_is_panning = False
  7080. if not origin_click:
  7081. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7082. if event.button == pan_button and self.event_is_dragging == 1:
  7083. self.ui.popMenu.mouse_is_panning = True
  7084. return
  7085. if self.rel_point1 is not None:
  7086. try: # May fail in case mouse not within axes
  7087. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7088. if self.grid_status() == True:
  7089. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7090. # Update cursor
  7091. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7092. symbol='++', edge_color=self.cursor_color_3D,
  7093. size=self.defaults["global_cursor_size"])
  7094. else:
  7095. pos = (pos_canvas[0], pos_canvas[1])
  7096. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7097. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7098. dx = pos[0] - float(self.rel_point1[0])
  7099. dy = pos[1] - float(self.rel_point1[1])
  7100. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7101. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7102. self.mouse = [pos[0], pos[1]]
  7103. # if the mouse is moved and the LMB is clicked then the action is a selection
  7104. if self.event_is_dragging == 1 and event.button == 1:
  7105. self.delete_selection_shape()
  7106. if dx < 0:
  7107. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7108. face_color=self.defaults['global_alt_sel_fill'])
  7109. self.selection_type = False
  7110. elif dx > 0:
  7111. self.draw_moving_selection_shape(self.pos, pos)
  7112. self.selection_type = True
  7113. else:
  7114. self.selection_type = None
  7115. # hover effect - enabled in Preferences -> General -> GUI Settings
  7116. if self.defaults['global_hover']:
  7117. for obj in self.collection.get_list():
  7118. try:
  7119. # select the object(s) only if it is enabled (plotted)
  7120. if obj.options['plot']:
  7121. if obj not in self.collection.get_selected():
  7122. poly_obj = Polygon(
  7123. [(obj.options['xmin'], obj.options['ymin']),
  7124. (obj.options['xmax'], obj.options['ymin']),
  7125. (obj.options['xmax'], obj.options['ymax']),
  7126. (obj.options['xmin'], obj.options['ymax'])]
  7127. )
  7128. if Point(pos).within(poly_obj):
  7129. if obj.isHovering is False:
  7130. obj.isHovering = True
  7131. obj.notHovering = True
  7132. # create the selection box around the selected object
  7133. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7134. else:
  7135. if obj.notHovering is True:
  7136. obj.notHovering = False
  7137. obj.isHovering = False
  7138. self.delete_hover_shape()
  7139. except Exception:
  7140. # the Exception here will happen if we try to select on screen and we have an
  7141. # newly (and empty) just created Geometry or Excellon object that do not have the
  7142. # xmin, xmax, ymin, ymax options.
  7143. # In this case poly_obj creation (see above) will fail
  7144. pass
  7145. except Exception:
  7146. self.ui.position_label.setText("")
  7147. self.ui.rel_position_label.setText("")
  7148. self.mouse = None
  7149. def on_mouse_click_release_over_plot(self, event):
  7150. """
  7151. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7152. and has been registered in ''self.__init__()''.
  7153. :param event: contains information about the event.
  7154. :return:
  7155. """
  7156. if self.is_legacy is False:
  7157. event_pos = event.pos
  7158. right_button = 2
  7159. else:
  7160. event_pos = (event.xdata, event.ydata)
  7161. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7162. right_button = 3
  7163. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7164. if self.grid_status() == True:
  7165. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7166. else:
  7167. pos = (pos_canvas[0], pos_canvas[1])
  7168. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7169. # canvas menu
  7170. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7171. self.cursor = QtGui.QCursor()
  7172. self.populate_cmenu_grids()
  7173. self.ui.popMenu.popup(self.cursor.pos())
  7174. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7175. # selection and then select a type of selection ("enclosing" or "touching")
  7176. if event.button == 1: # left click
  7177. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7178. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7179. if modifiers == QtCore.Qt.ShiftModifier:
  7180. # do not auto open the Project Tab
  7181. self.click_noproject = True
  7182. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7183. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7184. return
  7185. if self.doubleclick is True:
  7186. self.doubleclick = False
  7187. if self.collection.get_selected():
  7188. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7189. if self.ui.splitter.sizes()[0] == 0:
  7190. self.ui.splitter.setSizes([1, 1])
  7191. try:
  7192. # delete the selection shape(S) as it may be in the way
  7193. self.delete_selection_shape()
  7194. self.delete_hover_shape()
  7195. except Exception as e:
  7196. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7197. return
  7198. else:
  7199. if self.selection_type is not None:
  7200. try:
  7201. self.selection_area_handler(self.pos, pos, self.selection_type)
  7202. self.selection_type = None
  7203. except Exception as e:
  7204. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7205. return
  7206. else:
  7207. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7208. if key_modifier == QtCore.Qt.ShiftModifier:
  7209. mod_key = 'Shift'
  7210. elif key_modifier == QtCore.Qt.ControlModifier:
  7211. mod_key = 'Control'
  7212. else:
  7213. mod_key = None
  7214. try:
  7215. if mod_key == self.defaults["global_mselect_key"]:
  7216. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7217. # deselect, and if it's not selected then it will be selected
  7218. # If there is no active command (self.command_active is None) then we check if we clicked
  7219. # on a object by checking the bounding limits against mouse click position
  7220. if self.command_active is None:
  7221. self.select_objects(key='CTRL')
  7222. self.delete_hover_shape()
  7223. else:
  7224. # If there is no active command (self.command_active is None) then we check if we clicked
  7225. # on a object by checking the bounding limits against mouse click position
  7226. if self.command_active is None:
  7227. self.select_objects()
  7228. self.delete_hover_shape()
  7229. except Exception as e:
  7230. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7231. return
  7232. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7233. """
  7234. :param start_pos: mouse position when the selection LMB click was done
  7235. :param end_pos: mouse position when the left mouse button is released
  7236. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7237. :return:
  7238. """
  7239. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7240. # delete previous selection shape
  7241. self.delete_selection_shape()
  7242. # make all objects inactive
  7243. self.collection.set_all_inactive()
  7244. for obj in self.collection.get_list():
  7245. try:
  7246. # select the object(s) only if it is enabled (plotted)
  7247. if obj.options['plot']:
  7248. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7249. (obj.options['xmax'], obj.options['ymin']),
  7250. (obj.options['xmax'], obj.options['ymax']),
  7251. (obj.options['xmin'], obj.options['ymax'])])
  7252. if sel_type is True:
  7253. if poly_obj.within(poly_selection):
  7254. # create the selection box around the selected object
  7255. if self.defaults['global_selection_shape'] is True:
  7256. self.draw_selection_shape(obj)
  7257. self.collection.set_active(obj.options['name'])
  7258. else:
  7259. if poly_selection.intersects(poly_obj):
  7260. # create the selection box around the selected object
  7261. if self.defaults['global_selection_shape'] is True:
  7262. self.draw_selection_shape(obj)
  7263. self.collection.set_active(obj.options['name'])
  7264. except Exception as e:
  7265. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7266. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7267. # In this case poly_obj creation (see above) will fail
  7268. log.debug("App.selection_area_handler() --> %s" % str(e))
  7269. def select_objects(self, key=None):
  7270. """
  7271. Will select objects clicked on canvas
  7272. :param key: for future use in cumulative selection
  7273. :return:
  7274. """
  7275. # list where we store the overlapped objects under our mouse left click position
  7276. objects_under_the_click_list = []
  7277. # Populate the list with the overlapped objects on the click position
  7278. curr_x, curr_y = self.pos
  7279. for obj in self.all_objects_list:
  7280. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7281. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7282. continue
  7283. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7284. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7285. if obj.options['name'] not in objects_under_the_click_list:
  7286. if obj.options['plot']:
  7287. # add objects to the objects_under_the_click list only if the object is plotted
  7288. # (active and not disabled)
  7289. objects_under_the_click_list.append(obj.options['name'])
  7290. try:
  7291. if objects_under_the_click_list:
  7292. curr_sel_obj = self.collection.get_active()
  7293. # case when there is only an object under the click and we toggle it
  7294. if len(objects_under_the_click_list) == 1:
  7295. if curr_sel_obj is None:
  7296. self.collection.set_active(objects_under_the_click_list[0])
  7297. curr_sel_obj = self.collection.get_active()
  7298. # create the selection box around the selected object
  7299. if self.defaults['global_selection_shape'] is True:
  7300. self.draw_selection_shape(curr_sel_obj)
  7301. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7302. self.on_objects_selection(False)
  7303. self.delete_selection_shape()
  7304. self.collection.set_active(objects_under_the_click_list[0])
  7305. curr_sel_obj = self.collection.get_active()
  7306. # create the selection box around the selected object
  7307. if self.defaults['global_selection_shape'] is True:
  7308. self.draw_selection_shape(curr_sel_obj)
  7309. self.selected_message(curr_sel_obj=curr_sel_obj)
  7310. else:
  7311. self.on_objects_selection(False)
  7312. self.delete_selection_shape()
  7313. if self.call_source != 'app':
  7314. self.call_source = 'app'
  7315. self.selected_message(curr_sel_obj=curr_sel_obj)
  7316. else:
  7317. # If there is no selected object
  7318. # make active the first element of the overlapped objects list
  7319. if self.collection.get_active() is None:
  7320. self.collection.set_active(objects_under_the_click_list[0])
  7321. name_sel_obj = self.collection.get_active().options['name']
  7322. # In case that there is a selected object but it is not in the overlapped object list
  7323. # make that object inactive and activate the first element in the overlapped object list
  7324. if name_sel_obj not in objects_under_the_click_list:
  7325. self.collection.set_inactive(name_sel_obj)
  7326. name_sel_obj = objects_under_the_click_list[0]
  7327. self.collection.set_active(name_sel_obj)
  7328. else:
  7329. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7330. self.collection.set_all_inactive()
  7331. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7332. len(objects_under_the_click_list)])
  7333. curr_sel_obj = self.collection.get_active()
  7334. # delete the possible selection box around a possible selected object
  7335. self.delete_selection_shape()
  7336. # create the selection box around the selected object
  7337. if self.defaults['global_selection_shape'] is True:
  7338. self.draw_selection_shape(curr_sel_obj)
  7339. self.selected_message(curr_sel_obj=curr_sel_obj)
  7340. else:
  7341. # deselect everything
  7342. self.on_objects_selection(False)
  7343. # delete the possible selection box around a possible selected object
  7344. self.delete_selection_shape()
  7345. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7346. # only when working on App
  7347. if self.call_source == 'app':
  7348. if self.click_noproject is False:
  7349. # if the Tool Tab is in focus don't change focus to Project Tab
  7350. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7351. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7352. else:
  7353. # restore auto open the Project Tab
  7354. self.click_noproject = False
  7355. # delete any text in the status bar, implicitly the last object name that was selected
  7356. # self.inform.emit("")
  7357. else:
  7358. self.call_source = 'app'
  7359. except Exception as e:
  7360. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7361. def selected_message(self, curr_sel_obj):
  7362. if curr_sel_obj:
  7363. if curr_sel_obj.kind == 'gerber':
  7364. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7365. color='green', name=str(curr_sel_obj.options['name'])))
  7366. elif curr_sel_obj.kind == 'excellon':
  7367. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7368. color='brown', name=str(curr_sel_obj.options['name'])))
  7369. elif curr_sel_obj.kind == 'cncjob':
  7370. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7371. color='blue', name=str(curr_sel_obj.options['name'])))
  7372. elif curr_sel_obj.kind == 'geometry':
  7373. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7374. color='red', name=str(curr_sel_obj.options['name'])))
  7375. def delete_hover_shape(self):
  7376. self.hover_shapes.clear()
  7377. self.hover_shapes.redraw()
  7378. def draw_hover_shape(self, sel_obj, color=None):
  7379. """
  7380. :param sel_obj: the object for which the hover shape must be drawn
  7381. :return:
  7382. """
  7383. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7384. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7385. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7386. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7387. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7388. if self.defaults['units'].upper() == 'MM':
  7389. hover_rect = hover_rect.buffer(-0.1)
  7390. hover_rect = hover_rect.buffer(0.2)
  7391. else:
  7392. hover_rect = hover_rect.buffer(-0.00393)
  7393. hover_rect = hover_rect.buffer(0.00787)
  7394. # if color:
  7395. # face = Color(color)
  7396. # face.alpha = 0.2
  7397. # outline = Color(color, alpha=0.8)
  7398. # else:
  7399. # face = Color(self.defaults['global_sel_fill'])
  7400. # face.alpha = 0.2
  7401. # outline = self.defaults['global_sel_line']
  7402. if color:
  7403. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7404. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7405. else:
  7406. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7407. outline = self.defaults['global_sel_line']
  7408. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7409. if self.is_legacy is True:
  7410. self.hover_shapes.redraw()
  7411. def delete_selection_shape(self):
  7412. self.move_tool.sel_shapes.clear()
  7413. self.move_tool.sel_shapes.redraw()
  7414. def draw_selection_shape(self, sel_obj, color=None):
  7415. """
  7416. :param sel_obj: the object for which the selection shape must be drawn
  7417. :return:
  7418. """
  7419. if sel_obj is None:
  7420. return
  7421. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7422. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7423. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7424. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7425. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7426. if self.defaults['units'].upper() == 'MM':
  7427. sel_rect = sel_rect.buffer(-0.1)
  7428. sel_rect = sel_rect.buffer(0.2)
  7429. else:
  7430. sel_rect = sel_rect.buffer(-0.00393)
  7431. sel_rect = sel_rect.buffer(0.00787)
  7432. if color:
  7433. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7434. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7435. else:
  7436. if self.is_legacy is False:
  7437. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7438. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7439. else:
  7440. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7441. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7442. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7443. color=outline,
  7444. face_color=face,
  7445. update=True,
  7446. layer=0,
  7447. tolerance=None))
  7448. if self.is_legacy is True:
  7449. self.move_tool.sel_shapes.redraw()
  7450. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7451. """
  7452. :param old_coords: old coordinates
  7453. :param coords: new coordinates
  7454. :return:
  7455. """
  7456. if 'color' in kwargs:
  7457. color = kwargs['color']
  7458. else:
  7459. color = self.defaults['global_sel_line']
  7460. if 'face_color' in kwargs:
  7461. face_color = kwargs['face_color']
  7462. else:
  7463. face_color = self.defaults['global_sel_fill']
  7464. if 'face_alpha' in kwargs:
  7465. face_alpha = kwargs['face_alpha']
  7466. else:
  7467. face_alpha = 0.3
  7468. x0, y0 = old_coords
  7469. x1, y1 = coords
  7470. pt1 = (x0, y0)
  7471. pt2 = (x1, y0)
  7472. pt3 = (x1, y1)
  7473. pt4 = (x0, y1)
  7474. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7475. # color_t = Color(face_color)
  7476. # color_t.alpha = face_alpha
  7477. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7478. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7479. layer=0, tolerance=None)
  7480. if self.is_legacy is True:
  7481. self.move_tool.sel_shapes.redraw()
  7482. def on_file_new_click(self):
  7483. if self.collection.get_list() and self.should_we_save:
  7484. msgbox = QtWidgets.QMessageBox()
  7485. # msgbox.setText("<B>Save changes ...</B>")
  7486. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7487. "Creating a New project will delete them.\n"
  7488. "Do you want to Save the project?"))
  7489. msgbox.setWindowTitle(_("Save changes"))
  7490. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7491. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7492. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7493. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7494. msgbox.setDefaultButton(bt_yes)
  7495. msgbox.exec_()
  7496. response = msgbox.clickedButton()
  7497. if response == bt_yes:
  7498. self.on_file_saveprojectas()
  7499. elif response == bt_cancel:
  7500. return
  7501. elif response == bt_no:
  7502. self.on_file_new()
  7503. else:
  7504. self.on_file_new()
  7505. self.inform.emit('[success] %s...' %
  7506. _("New Project created"))
  7507. def on_file_new(self, cli=None):
  7508. """
  7509. Callback for menu item File -> New. Returns the application to its
  7510. startup state. This method is thread-safe.
  7511. :return: None
  7512. """
  7513. self.report_usage("on_file_new")
  7514. # Remove everything from memory
  7515. App.log.debug("on_file_new()")
  7516. if self.call_source != 'app':
  7517. self.editor2object(cleanup=True)
  7518. # ## EDITOR section
  7519. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7520. self.exc_editor = FlatCAMExcEditor(self)
  7521. self.grb_editor = FlatCAMGrbEditor(self)
  7522. # Clear pool
  7523. self.clear_pool()
  7524. for obj in self.collection.get_list():
  7525. # delete shapes left drawn from mark shape_collections, if any
  7526. if isinstance(obj, FlatCAMGerber):
  7527. try:
  7528. obj.mark_shapes.enabled = False
  7529. obj.mark_shapes.clear(update=True)
  7530. except AttributeError:
  7531. pass
  7532. # also delete annotation shapes, if any
  7533. elif isinstance(obj, FlatCAMCNCjob):
  7534. try:
  7535. obj.annotation.enabled = False
  7536. obj.annotation.clear(update=True)
  7537. except AttributeError:
  7538. pass
  7539. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7540. self.init_tcl()
  7541. self.delete_selection_shape()
  7542. self.collection.delete_all()
  7543. self.setup_component_editor()
  7544. # Clear project filename
  7545. self.project_filename = None
  7546. # Load the application defaults
  7547. self.load_defaults(filename='current_defaults')
  7548. # Re-fresh project options
  7549. self.on_options_app2project()
  7550. # Init Tools
  7551. self.init_tools()
  7552. if cli is None:
  7553. # Close any Tabs opened in the Plot Tab Area section
  7554. for index in range(self.ui.plot_tab_area.count()):
  7555. self.ui.plot_tab_area.closeTab(index)
  7556. # for whatever reason previous command does not close the last tab so I do it manually
  7557. self.ui.plot_tab_area.closeTab(0)
  7558. # # And then add again the Plot Area
  7559. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7560. self.ui.plot_tab_area.protectTab(0)
  7561. # take the focus of the Notebook on Project Tab.
  7562. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7563. self.set_ui_title(name=_("New Project - Not saved"))
  7564. def obj_properties(self):
  7565. """
  7566. Will launch the object Properties Tool
  7567. :return:
  7568. """
  7569. self.report_usage("obj_properties()")
  7570. self.properties_tool.run(toggle=False)
  7571. def on_project_context_save(self):
  7572. """
  7573. Wrapper, will save the object function of it's type
  7574. :return:
  7575. """
  7576. obj = self.collection.get_active()
  7577. if type(obj) == FlatCAMGeometry:
  7578. self.on_file_exportdxf()
  7579. elif type(obj) == FlatCAMExcellon:
  7580. self.on_file_saveexcellon()
  7581. elif type(obj) == FlatCAMCNCjob:
  7582. obj.on_exportgcode_button_click()
  7583. elif type(obj) == FlatCAMGerber:
  7584. self.on_file_savegerber()
  7585. elif type(obj) == FlatCAMScript:
  7586. self.on_file_savescript()
  7587. elif type(obj) == FlatCAMDocument:
  7588. self.on_file_savedocument()
  7589. def obj_move(self):
  7590. self.report_usage("obj_move()")
  7591. self.move_tool.run(toggle=False)
  7592. def on_fileopengerber(self, signal: bool = None, name=None):
  7593. """
  7594. File menu callback for opening a Gerber.
  7595. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7596. :return: None
  7597. """
  7598. self.report_usage("on_fileopengerber")
  7599. App.log.debug("on_fileopengerber()")
  7600. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7601. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7602. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7603. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7604. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7605. "*.mil);;" \
  7606. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7607. "Allegro Files (*.art);;" \
  7608. "Mentor Files (*.pho *.gdo);;" \
  7609. "All Files (*.*)"
  7610. if name is None:
  7611. try:
  7612. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7613. directory=self.get_last_folder(),
  7614. filter=_filter_)
  7615. except TypeError:
  7616. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7617. filenames = [str(filename) for filename in filenames]
  7618. else:
  7619. filenames = [name]
  7620. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7621. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7622. _("Opening Gerber file.")),
  7623. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7624. color=QtGui.QColor("gray"))
  7625. if len(filenames) == 0:
  7626. self.inform.emit('[WARNING_NOTCL] %s' %
  7627. _("Open Gerber cancelled."))
  7628. else:
  7629. for filename in filenames:
  7630. if filename != '':
  7631. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7632. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7633. """
  7634. File menu callback for opening an Excellon file.
  7635. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7636. :return: None
  7637. """
  7638. self.report_usage("on_fileopenexcellon")
  7639. App.log.debug("on_fileopenexcellon()")
  7640. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7641. "All Files (*.*)"
  7642. if name is None:
  7643. try:
  7644. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7645. directory=self.get_last_folder(),
  7646. filter=_filter_)
  7647. except TypeError:
  7648. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7649. filenames = [str(filename) for filename in filenames]
  7650. else:
  7651. filenames = [str(name)]
  7652. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7653. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7654. _("Opening Excellon file.")),
  7655. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7656. color=QtGui.QColor("gray"))
  7657. if len(filenames) == 0:
  7658. self.inform.emit('[WARNING_NOTCL]%s' %
  7659. _(" Open Excellon cancelled."))
  7660. else:
  7661. for filename in filenames:
  7662. if filename != '':
  7663. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7664. def on_fileopengcode(self, signal: bool = None, name=None):
  7665. """
  7666. File menu call back for opening gcode.
  7667. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7668. :return: None
  7669. """
  7670. self.report_usage("on_fileopengcode")
  7671. App.log.debug("on_fileopengcode()")
  7672. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7673. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7674. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7675. "All Files (*.*)"
  7676. if name is None:
  7677. try:
  7678. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7679. directory=self.get_last_folder(),
  7680. filter=_filter_)
  7681. except TypeError:
  7682. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7683. filenames = [str(filename) for filename in filenames]
  7684. else:
  7685. filenames = [name]
  7686. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7687. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7688. _("Opening G-Code file.")),
  7689. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7690. color=QtGui.QColor("gray"))
  7691. if len(filenames) == 0:
  7692. self.inform.emit('[WARNING_NOTCL] %s' %
  7693. _("Open G-Code cancelled."))
  7694. else:
  7695. for filename in filenames:
  7696. if filename != '':
  7697. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7698. def on_file_openproject(self, signal: bool = None):
  7699. """
  7700. File menu callback for opening a project.
  7701. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7702. :return: None
  7703. """
  7704. self.report_usage("on_file_openproject")
  7705. App.log.debug("on_file_openproject()")
  7706. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7707. try:
  7708. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7709. directory=self.get_last_folder(), filter=_filter_)
  7710. except TypeError:
  7711. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7712. # The Qt methods above will return a QString which can cause problems later.
  7713. # So far json.dump() will fail to serialize it.
  7714. # TODO: Improve the serialization methods and remove this fix.
  7715. filename = str(filename)
  7716. if filename == "":
  7717. self.inform.emit('[WARNING_NOTCL] %s' %
  7718. _("Open Project cancelled."))
  7719. else:
  7720. # self.worker_task.emit({'fcn': self.open_project,
  7721. # 'params': [filename]})
  7722. # The above was failing because open_project() is not
  7723. # thread safe. The new_project()
  7724. self.open_project(filename)
  7725. def on_file_openconfig(self, signal: bool = None):
  7726. """
  7727. File menu callback for opening a config file.
  7728. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7729. :return: None
  7730. """
  7731. self.report_usage("on_file_openconfig")
  7732. App.log.debug("on_file_openconfig()")
  7733. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7734. try:
  7735. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7736. directory=self.data_path, filter=_filter_)
  7737. except TypeError:
  7738. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7739. filter=_filter_)
  7740. if filename == "":
  7741. self.inform.emit('[WARNING_NOTCL] %s' %
  7742. _("Open Config cancelled."))
  7743. else:
  7744. self.open_config_file(filename)
  7745. def on_file_exportsvg(self):
  7746. """
  7747. Callback for menu item File->Export SVG.
  7748. :return: None
  7749. """
  7750. self.report_usage("on_file_exportsvg")
  7751. App.log.debug("on_file_exportsvg()")
  7752. obj = self.collection.get_active()
  7753. if obj is None:
  7754. self.inform.emit('[WARNING_NOTCL] %s' %
  7755. _("No object selected."))
  7756. msg = _("Please Select a Geometry object to export")
  7757. msgbox = QtWidgets.QMessageBox()
  7758. msgbox.setInformativeText(msg)
  7759. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7760. msgbox.setDefaultButton(bt_ok)
  7761. msgbox.exec_()
  7762. return
  7763. # Check for more compatible types and add as required
  7764. if (not isinstance(obj, FlatCAMGeometry)
  7765. and not isinstance(obj, FlatCAMGerber)
  7766. and not isinstance(obj, FlatCAMCNCjob)
  7767. and not isinstance(obj, FlatCAMExcellon)):
  7768. msg = '[ERROR_NOTCL] %s' % \
  7769. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7770. msgbox = QtWidgets.QMessageBox()
  7771. msgbox.setInformativeText(msg)
  7772. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7773. msgbox.setDefaultButton(bt_ok)
  7774. msgbox.exec_()
  7775. return
  7776. name = obj.options["name"]
  7777. _filter = "SVG File (*.svg);;All Files (*.*)"
  7778. try:
  7779. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7780. caption=_("Export SVG"),
  7781. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7782. filter=_filter)
  7783. except TypeError:
  7784. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7785. filename = str(filename)
  7786. if filename == "":
  7787. self.inform.emit('[WARNING_NOTCL]%s' %
  7788. _(" Export SVG cancelled."))
  7789. return
  7790. else:
  7791. self.export_svg(name, filename)
  7792. if self.defaults["global_open_style"] is False:
  7793. self.file_opened.emit("SVG", filename)
  7794. self.file_saved.emit("SVG", filename)
  7795. def on_file_exportpng(self):
  7796. self.report_usage("on_file_exportpng")
  7797. App.log.debug("on_file_exportpng()")
  7798. self.date = str(datetime.today()).rpartition('.')[0]
  7799. self.date = ''.join(c for c in self.date if c not in ':-')
  7800. self.date = self.date.replace(' ', '_')
  7801. if self.is_legacy is False:
  7802. image = _screenshot()
  7803. data = np.asarray(image)
  7804. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7805. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7806. _('Data must be a 3D array with last dimension 3 or 4'))
  7807. return
  7808. filter_ = "PNG File (*.png);;All Files (*.*)"
  7809. try:
  7810. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7811. caption=_("Export PNG Image"),
  7812. directory=self.get_last_save_folder() + '/png_' + self.date,
  7813. filter=filter_)
  7814. except TypeError:
  7815. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7816. filename = str(filename)
  7817. if filename == "":
  7818. self.inform.emit(_("Export PNG cancelled."))
  7819. return
  7820. else:
  7821. if self.is_legacy is False:
  7822. write_png(filename, data)
  7823. else:
  7824. self.plotcanvas.figure.savefig(filename)
  7825. if self.defaults["global_open_style"] is False:
  7826. self.file_opened.emit("png", filename)
  7827. self.file_saved.emit("png", filename)
  7828. def on_file_savegerber(self):
  7829. """
  7830. Callback for menu item in Project context menu.
  7831. :return: None
  7832. """
  7833. self.report_usage("on_file_savegerber")
  7834. App.log.debug("on_file_savegerber()")
  7835. obj = self.collection.get_active()
  7836. if obj is None:
  7837. self.inform.emit('[WARNING_NOTCL] %s' %
  7838. _("No object selected. Please select an Gerber object to export."))
  7839. return
  7840. # Check for more compatible types and add as required
  7841. if not isinstance(obj, FlatCAMGerber):
  7842. self.inform.emit('[ERROR_NOTCL] %s' %
  7843. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7844. return
  7845. name = self.collection.get_active().options["name"]
  7846. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7847. try:
  7848. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7849. caption="Save Gerber source file",
  7850. directory=self.get_last_save_folder() + '/' + name,
  7851. filter=_filter)
  7852. except TypeError:
  7853. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7854. filename = str(filename)
  7855. if filename == "":
  7856. self.inform.emit('[WARNING_NOTCL] %s' %
  7857. _("Save Gerber source file cancelled."))
  7858. return
  7859. else:
  7860. self.save_source_file(name, filename)
  7861. if self.defaults["global_open_style"] is False:
  7862. self.file_opened.emit("Gerber", filename)
  7863. self.file_saved.emit("Gerber", filename)
  7864. def on_file_savescript(self):
  7865. """
  7866. Callback for menu item in Project context menu.
  7867. :return: None
  7868. """
  7869. self.report_usage("on_file_savescript")
  7870. App.log.debug("on_file_savescript()")
  7871. obj = self.collection.get_active()
  7872. if obj is None:
  7873. self.inform.emit('[WARNING_NOTCL] %s' %
  7874. _("No object selected. Please select an Script object to export."))
  7875. return
  7876. # Check for more compatible types and add as required
  7877. if not isinstance(obj, FlatCAMScript):
  7878. self.inform.emit('[ERROR_NOTCL] %s' %
  7879. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7880. return
  7881. name = self.collection.get_active().options["name"]
  7882. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7883. try:
  7884. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7885. caption="Save Script source file",
  7886. directory=self.get_last_save_folder() + '/' + name,
  7887. filter=_filter)
  7888. except TypeError:
  7889. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7890. filename = str(filename)
  7891. if filename == "":
  7892. self.inform.emit('[WARNING_NOTCL] %s' %
  7893. _("Save Script source file cancelled."))
  7894. return
  7895. else:
  7896. self.save_source_file(name, filename)
  7897. if self.defaults["global_open_style"] is False:
  7898. self.file_opened.emit("Script", filename)
  7899. self.file_saved.emit("Script", filename)
  7900. def on_file_savedocument(self):
  7901. """
  7902. Callback for menu item in Project context menu.
  7903. :return: None
  7904. """
  7905. self.report_usage("on_file_savedocument")
  7906. App.log.debug("on_file_savedocument()")
  7907. obj = self.collection.get_active()
  7908. if obj is None:
  7909. self.inform.emit('[WARNING_NOTCL] %s' %
  7910. _("No object selected. Please select an Document object to export."))
  7911. return
  7912. # Check for more compatible types and add as required
  7913. if not isinstance(obj, FlatCAMScript):
  7914. self.inform.emit('[ERROR_NOTCL] %s' %
  7915. _("Failed. Only Document objects can be saved as Document files..."))
  7916. return
  7917. name = self.collection.get_active().options["name"]
  7918. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7919. try:
  7920. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7921. caption="Save Document source file",
  7922. directory=self.get_last_save_folder() + '/' + name,
  7923. filter=_filter)
  7924. except TypeError:
  7925. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7926. filename = str(filename)
  7927. if filename == "":
  7928. self.inform.emit('[WARNING_NOTCL] %s' %
  7929. _("Save Document source file cancelled."))
  7930. return
  7931. else:
  7932. self.save_source_file(name, filename)
  7933. if self.defaults["global_open_style"] is False:
  7934. self.file_opened.emit("Document", filename)
  7935. self.file_saved.emit("Document", filename)
  7936. def on_file_saveexcellon(self):
  7937. """
  7938. Callback for menu item in project context menu.
  7939. :return: None
  7940. """
  7941. self.report_usage("on_file_saveexcellon")
  7942. App.log.debug("on_file_saveexcellon()")
  7943. obj = self.collection.get_active()
  7944. if obj is None:
  7945. self.inform.emit('[WARNING_NOTCL] %s' %
  7946. _("No object selected. Please select an Excellon object to export."))
  7947. return
  7948. # Check for more compatible types and add as required
  7949. if not isinstance(obj, FlatCAMExcellon):
  7950. self.inform.emit('[ERROR_NOTCL] %s' %
  7951. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7952. return
  7953. name = self.collection.get_active().options["name"]
  7954. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7955. try:
  7956. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7957. caption=_("Save Excellon source file"),
  7958. directory=self.get_last_save_folder() + '/' + name,
  7959. filter=_filter)
  7960. except TypeError:
  7961. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7962. filename = str(filename)
  7963. if filename == "":
  7964. self.inform.emit('[WARNING_NOTCL] %s' %
  7965. _("Saving Excellon source file cancelled."))
  7966. return
  7967. else:
  7968. self.save_source_file(name, filename)
  7969. if self.defaults["global_open_style"] is False:
  7970. self.file_opened.emit("Excellon", filename)
  7971. self.file_saved.emit("Excellon", filename)
  7972. def on_file_exportexcellon(self):
  7973. """
  7974. Callback for menu item File->Export->Excellon.
  7975. :return: None
  7976. """
  7977. self.report_usage("on_file_exportexcellon")
  7978. App.log.debug("on_file_exportexcellon()")
  7979. obj = self.collection.get_active()
  7980. if obj is None:
  7981. self.inform.emit('[WARNING_NOTCL] %s' %
  7982. _("No object selected. Please Select an Excellon object to export."))
  7983. return
  7984. # Check for more compatible types and add as required
  7985. if not isinstance(obj, FlatCAMExcellon):
  7986. self.inform.emit('[ERROR_NOTCL] %s' %
  7987. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7988. return
  7989. name = self.collection.get_active().options["name"]
  7990. _filter = self.defaults["excellon_save_filters"]
  7991. try:
  7992. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7993. caption=_("Export Excellon"),
  7994. directory=self.get_last_save_folder() + '/' + name,
  7995. filter=_filter)
  7996. except TypeError:
  7997. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7998. filename = str(filename)
  7999. if filename == "":
  8000. self.inform.emit('[WARNING_NOTCL] %s' %
  8001. _("Export Excellon cancelled."))
  8002. return
  8003. else:
  8004. used_extension = filename.rpartition('.')[2]
  8005. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8006. self.export_excellon(name, filename)
  8007. if self.defaults["global_open_style"] is False:
  8008. self.file_opened.emit("Excellon", filename)
  8009. self.file_saved.emit("Excellon", filename)
  8010. def on_file_exportgerber(self):
  8011. """
  8012. Callback for menu item File->Export->Gerber.
  8013. :return: None
  8014. """
  8015. self.report_usage("on_file_exportgerber")
  8016. App.log.debug("on_file_exportgerber()")
  8017. obj = self.collection.get_active()
  8018. if obj is None:
  8019. self.inform.emit('[WARNING_NOTCL] %s' %
  8020. _("No object selected. Please Select an Gerber object to export."))
  8021. return
  8022. # Check for more compatible types and add as required
  8023. if not isinstance(obj, FlatCAMGerber):
  8024. self.inform.emit('[ERROR_NOTCL] %s' %
  8025. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8026. return
  8027. name = self.collection.get_active().options["name"]
  8028. _filter_ = self.defaults['gerber_save_filters']
  8029. try:
  8030. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8031. caption=_("Export Gerber"),
  8032. directory=self.get_last_save_folder() + '/' + name,
  8033. filter=_filter_)
  8034. except TypeError:
  8035. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8036. filename = str(filename)
  8037. if filename == "":
  8038. self.inform.emit('[WARNING_NOTCL] %s' %
  8039. _("Export Gerber cancelled."))
  8040. return
  8041. else:
  8042. used_extension = filename.rpartition('.')[2]
  8043. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8044. self.export_gerber(name, filename)
  8045. if self.defaults["global_open_style"] is False:
  8046. self.file_opened.emit("Gerber", filename)
  8047. self.file_saved.emit("Gerber", filename)
  8048. def on_file_exportdxf(self):
  8049. """
  8050. Callback for menu item File->Export DXF.
  8051. :return: None
  8052. """
  8053. self.report_usage("on_file_exportdxf")
  8054. App.log.debug("on_file_exportdxf()")
  8055. obj = self.collection.get_active()
  8056. if obj is None:
  8057. self.inform.emit('[WARNING_NOTCL] %s' %
  8058. _("No object selected."))
  8059. msg = _("Please Select a Geometry object to export")
  8060. msgbox = QtWidgets.QMessageBox()
  8061. msgbox.setInformativeText(msg)
  8062. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8063. msgbox.setDefaultButton(bt_ok)
  8064. msgbox.exec_()
  8065. return
  8066. # Check for more compatible types and add as required
  8067. if not isinstance(obj, FlatCAMGeometry):
  8068. msg = '[ERROR_NOTCL] %s' % \
  8069. _("Only Geometry objects can be used.")
  8070. msgbox = QtWidgets.QMessageBox()
  8071. msgbox.setInformativeText(msg)
  8072. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8073. msgbox.setDefaultButton(bt_ok)
  8074. msgbox.exec_()
  8075. return
  8076. name = self.collection.get_active().options["name"]
  8077. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8078. try:
  8079. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8080. caption=_("Export DXF"),
  8081. directory=self.get_last_save_folder() + '/' + name,
  8082. filter=_filter_)
  8083. except TypeError:
  8084. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8085. filter=_filter_)
  8086. filename = str(filename)
  8087. if filename == "":
  8088. self.inform.emit('[WARNING_NOTCL] %s' %
  8089. _("Export DXF cancelled."))
  8090. return
  8091. else:
  8092. self.export_dxf(name, filename)
  8093. if self.defaults["global_open_style"] is False:
  8094. self.file_opened.emit("DXF", filename)
  8095. self.file_saved.emit("DXF", filename)
  8096. def on_file_importsvg(self, type_of_obj):
  8097. """
  8098. Callback for menu item File->Import SVG.
  8099. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8100. :type type_of_obj: str
  8101. :return: None
  8102. """
  8103. self.report_usage("on_file_importsvg")
  8104. App.log.debug("on_file_importsvg()")
  8105. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8106. try:
  8107. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8108. directory=self.get_last_folder(), filter=_filter_)
  8109. except TypeError:
  8110. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8111. filter=_filter_)
  8112. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8113. type_of_obj = "geometry"
  8114. filenames = [str(filename) for filename in filenames]
  8115. if len(filenames) == 0:
  8116. self.inform.emit('[WARNING_NOTCL] %s' %
  8117. _("Open SVG cancelled."))
  8118. else:
  8119. for filename in filenames:
  8120. if filename != '':
  8121. self.worker_task.emit({'fcn': self.import_svg,
  8122. 'params': [filename, type_of_obj]})
  8123. def on_file_importdxf(self, type_of_obj):
  8124. """
  8125. Callback for menu item File->Import DXF.
  8126. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8127. :type type_of_obj: str
  8128. :return: None
  8129. """
  8130. self.report_usage("on_file_importdxf")
  8131. App.log.debug("on_file_importdxf()")
  8132. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8133. try:
  8134. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8135. directory=self.get_last_folder(),
  8136. filter=_filter_)
  8137. except TypeError:
  8138. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8139. filter=_filter_)
  8140. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8141. type_of_obj = "geometry"
  8142. filenames = [str(filename) for filename in filenames]
  8143. if len(filenames) == 0:
  8144. self.inform.emit('[WARNING_NOTCL] %s' %
  8145. _("Open DXF cancelled."))
  8146. else:
  8147. for filename in filenames:
  8148. if filename != '':
  8149. self.worker_task.emit({'fcn': self.import_dxf,
  8150. 'params': [filename, type_of_obj]})
  8151. # ###############################################################################################################
  8152. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8153. # ###############################################################################################################
  8154. def init_code_editor(self, name):
  8155. self.text_editor_tab = TextEditor(app=self)
  8156. # add the tab if it was closed
  8157. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8158. self.text_editor_tab.setObjectName('text_editor_tab')
  8159. # delete the absolute and relative position and messages in the infobar
  8160. self.ui.position_label.setText("")
  8161. self.ui.rel_position_label.setText("")
  8162. # first clear previous text in text editor (if any)
  8163. self.text_editor_tab.code_editor.clear()
  8164. self.text_editor_tab.code_editor.setReadOnly(False)
  8165. self.toggle_codeeditor = True
  8166. self.text_editor_tab.code_editor.completer_enable = False
  8167. self.text_editor_tab.buttonRun.hide()
  8168. # make sure to keep a reference to the code editor
  8169. self.reference_code_editor = self.text_editor_tab.code_editor
  8170. # Switch plot_area to CNCJob tab
  8171. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8172. def on_view_source(self):
  8173. """
  8174. Called when the user wants to see the source file of the selected object
  8175. :return:
  8176. """
  8177. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8178. self.proc_container.view.set_busy(_("Loading..."))
  8179. try:
  8180. obj = self.collection.get_active()
  8181. except Exception as e:
  8182. log.debug("App.on_view_source() --> %s" % str(e))
  8183. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8184. return 'fail'
  8185. if obj is None:
  8186. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8187. return 'fail'
  8188. flt = "All Files (*.*)"
  8189. if obj.kind == 'gerber':
  8190. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8191. elif obj.kind == 'excellon':
  8192. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8193. elif obj.kind == 'cncjob':
  8194. "GCode Files (*.NC);;All Files (*.*)"
  8195. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8196. # add the tab if it was closed
  8197. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8198. self.source_editor_tab.setObjectName('source_editor_tab')
  8199. # delete the absolute and relative position and messages in the infobar
  8200. self.ui.position_label.setText("")
  8201. self.ui.rel_position_label.setText("")
  8202. # first clear previous text in text editor (if any)
  8203. self.source_editor_tab.code_editor.clear()
  8204. self.source_editor_tab.code_editor.setReadOnly(False)
  8205. self.source_editor_tab.code_editor.completer_enable = False
  8206. self.source_editor_tab.buttonRun.hide()
  8207. # Switch plot_area to CNCJob tab
  8208. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8209. try:
  8210. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8211. except TypeError:
  8212. pass
  8213. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8214. try:
  8215. self.source_editor_tab.buttonSave.clicked.disconnect()
  8216. except TypeError:
  8217. pass
  8218. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8219. # then append the text from GCode to the text editor
  8220. if obj.kind == 'cncjob':
  8221. try:
  8222. file = obj.export_gcode(
  8223. preamble=self.defaults["cncjob_prepend"],
  8224. postamble=self.defaults["cncjob_append"],
  8225. to_file=True)
  8226. if file == 'fail':
  8227. return 'fail'
  8228. except AttributeError:
  8229. self.inform.emit('[WARNING_NOTCL] %s' %
  8230. _("There is no selected object for which to see it's source file code."))
  8231. return 'fail'
  8232. else:
  8233. try:
  8234. file = StringIO(obj.source_file)
  8235. except (AttributeError, TypeError):
  8236. self.inform.emit('[WARNING_NOTCL] %s' %
  8237. _("There is no selected object for which to see it's source file code."))
  8238. return 'fail'
  8239. self.source_editor_tab.t_frame.hide()
  8240. try:
  8241. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8242. # for line in file:
  8243. # QtWidgets.QApplication.processEvents()
  8244. # proc_line = str(line).strip('\n')
  8245. # self.source_editor_tab.code_editor.append(proc_line)
  8246. except Exception as e:
  8247. log.debug('App.on_view_source() -->%s' % str(e))
  8248. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8249. return
  8250. self.source_editor_tab.handleTextChanged()
  8251. self.source_editor_tab.t_frame.show()
  8252. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8253. self.proc_container.view.set_idle()
  8254. # self.ui.show()
  8255. def on_toggle_code_editor(self):
  8256. self.report_usage("on_toggle_code_editor()")
  8257. if self.toggle_codeeditor is False:
  8258. self.init_code_editor(name=_("Code Editor"))
  8259. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8260. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8261. self.text_editor_tab.buttonSave.clicked.disconnect()
  8262. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8263. else:
  8264. for idx in range(self.ui.plot_tab_area.count()):
  8265. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8266. self.ui.plot_tab_area.closeTab(idx)
  8267. break
  8268. self.toggle_codeeditor = False
  8269. def on_code_editor_close(self):
  8270. print("closed")
  8271. self.toggle_codeeditor = False
  8272. def on_filenewscript(self, silent=False, name=None, text=None):
  8273. """
  8274. Will create a new script file and open it in the Code Editor
  8275. :param silent: if True will not display status messages
  8276. :param name: if specified will be the name of the new script
  8277. :param text: pass a source file to the newly created script to be loaded in it
  8278. :return: None
  8279. """
  8280. if silent is False:
  8281. self.inform.emit('[success] %s' %
  8282. _("New TCL script file created in Code Editor."))
  8283. # delete the absolute and relative position and messages in the infobar
  8284. self.ui.position_label.setText("")
  8285. self.ui.rel_position_label.setText("")
  8286. if name is not None:
  8287. self.new_script_object(name=name, text=text)
  8288. else:
  8289. self.new_script_object(text=text)
  8290. # script_text = script_obj.source_file
  8291. #
  8292. # self.proc_container.view.set_busy(_("Loading..."))
  8293. # script_obj.script_editor_tab.t_frame.hide()
  8294. #
  8295. # script_obj.script_editor_tab.t_frame.show()
  8296. # self.proc_container.view.set_idle()
  8297. def on_fileopenscript(self, name=None, silent=False):
  8298. """
  8299. Will open a Tcl script file into the Code Editor
  8300. :param silent: if True will not display status messages
  8301. :param name: name of a Tcl script file to open
  8302. :return:
  8303. """
  8304. self.report_usage("on_fileopenscript")
  8305. App.log.debug("on_fileopenscript()")
  8306. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8307. if name:
  8308. filenames = [name]
  8309. else:
  8310. try:
  8311. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8312. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8313. except TypeError:
  8314. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8315. if len(filenames) == 0:
  8316. if silent is False:
  8317. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8318. else:
  8319. for filename in filenames:
  8320. if filename != '':
  8321. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8322. def on_filerunscript(self, name=None, silent=False):
  8323. """
  8324. File menu callback for loading and running a TCL script.
  8325. :param silent: if True will not display status messages
  8326. :param name: name of a Tcl script file to be run by FlatCAM
  8327. :return: None
  8328. """
  8329. self.report_usage("on_filerunscript")
  8330. App.log.debug("on_file_runscript()")
  8331. if name:
  8332. filename = name
  8333. if self.cmd_line_headless != 1:
  8334. self.splash.showMessage('%s: %ssec\n%s' %
  8335. (_("Canvas initialization started.\n"
  8336. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8337. _("Executing FlatCAMScript file.")
  8338. ),
  8339. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8340. color=QtGui.QColor("gray"))
  8341. else:
  8342. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8343. try:
  8344. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8345. directory=self.get_last_folder(), filter=_filter_)
  8346. except TypeError:
  8347. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8348. # The Qt methods above will return a QString which can cause problems later.
  8349. # So far json.dump() will fail to serialize it.
  8350. # TODO: Improve the serialization methods and remove this fix.
  8351. filename = str(filename)
  8352. if filename == "":
  8353. if silent is False:
  8354. self.inform.emit('[WARNING_NOTCL] %s' %
  8355. _("Run TCL script cancelled."))
  8356. else:
  8357. if self.cmd_line_headless != 1:
  8358. if self.ui.shell_dock.isHidden():
  8359. self.ui.shell_dock.show()
  8360. try:
  8361. with open(filename, "r") as tcl_script:
  8362. cmd_line_shellfile_content = tcl_script.read()
  8363. if self.cmd_line_headless != 1:
  8364. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8365. else:
  8366. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8367. if silent is False:
  8368. self.inform.emit('[success] %s' %
  8369. _("TCL script file opened in Code Editor and executed."))
  8370. except Exception as e:
  8371. log.debug("App.on_filerunscript() -> %s" % str(e))
  8372. sys.exit(2)
  8373. def on_file_saveproject(self, silent=False):
  8374. """
  8375. Callback for menu item File->Save Project. Saves the project to
  8376. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8377. if set to None. The project is saved by calling ``self.save_project()``.
  8378. :param silent: if True will not display status messages
  8379. :return: None
  8380. """
  8381. self.report_usage("on_file_saveproject")
  8382. if self.project_filename is None:
  8383. self.on_file_saveprojectas()
  8384. else:
  8385. self.worker_task.emit({'fcn': self.save_project,
  8386. 'params': [self.project_filename, silent]})
  8387. if self.defaults["global_open_style"] is False:
  8388. self.file_opened.emit("project", self.project_filename)
  8389. self.file_saved.emit("project", self.project_filename)
  8390. self.set_ui_title(name=self.project_filename)
  8391. self.should_we_save = False
  8392. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8393. """
  8394. Callback for menu item File->Save Project As... Opens a file
  8395. chooser and saves the project to the given file via
  8396. ``self.save_project()``.
  8397. :param make_copy if to be create a copy of the project; boolean
  8398. :param use_thread: if to be run in a separate thread; boolean
  8399. :param quit_action: if to be followed by quiting the application; boolean
  8400. :return: None
  8401. """
  8402. self.report_usage("on_file_saveprojectas")
  8403. self.date = str(datetime.today()).rpartition('.')[0]
  8404. self.date = ''.join(c for c in self.date if c not in ':-')
  8405. self.date = self.date.replace(' ', '_')
  8406. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8407. try:
  8408. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8409. caption=_("Save Project As ..."),
  8410. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8411. filter=filter_)
  8412. except TypeError:
  8413. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8414. filename = str(filename)
  8415. if filename == '':
  8416. self.inform.emit('[WARNING_NOTCL] %s' %
  8417. _("Save Project cancelled."))
  8418. return
  8419. try:
  8420. f = open(filename, 'r')
  8421. f.close()
  8422. except IOError:
  8423. pass
  8424. if use_thread is True:
  8425. self.worker_task.emit({'fcn': self.save_project,
  8426. 'params': [filename, quit_action]})
  8427. else:
  8428. self.save_project(filename, quit_action)
  8429. # self.save_project(filename)
  8430. if self.defaults["global_open_style"] is False:
  8431. self.file_opened.emit("project", filename)
  8432. self.file_saved.emit("project", filename)
  8433. if not make_copy:
  8434. self.project_filename = filename
  8435. self.set_ui_title(name=self.project_filename)
  8436. self.should_we_save = False
  8437. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8438. """
  8439. Exports a Geometry Object to an SVG file.
  8440. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8441. :param filename: Path to the SVG file to save to.
  8442. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8443. :return:
  8444. """
  8445. self.report_usage("export_svg()")
  8446. if filename is None:
  8447. filename = self.defaults["global_last_save_folder"]
  8448. self.log.debug("export_svg()")
  8449. try:
  8450. obj = self.collection.get_by_name(str(obj_name))
  8451. except Exception:
  8452. # TODO: The return behavior has not been established... should raise exception?
  8453. return "Could not retrieve object: %s" % obj_name
  8454. with self.proc_container.new(_("Exporting SVG")) as proc:
  8455. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8456. # Determine bounding area for svg export
  8457. bounds = obj.bounds()
  8458. size = obj.size()
  8459. # Convert everything to strings for use in the xml doc
  8460. svgwidth = str(size[0])
  8461. svgheight = str(size[1])
  8462. minx = str(bounds[0])
  8463. miny = str(bounds[1] - size[1])
  8464. uom = obj.units.lower()
  8465. # Add a SVG Header and footer to the svg output from shapely
  8466. # The transform flips the Y Axis so that everything renders
  8467. # properly within svg apps such as inkscape
  8468. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8469. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8470. svg_header += 'width="' + svgwidth + uom + '" '
  8471. svg_header += 'height="' + svgheight + uom + '" '
  8472. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8473. svg_header += '<g transform="scale(1,-1)">'
  8474. svg_footer = '</g> </svg>'
  8475. svg_elem = svg_header + exported_svg + svg_footer
  8476. # Parse the xml through a xml parser just to add line feeds
  8477. # and to make it look more pretty for the output
  8478. svgcode = parse_xml_string(svg_elem)
  8479. svgcode = svgcode.toprettyxml()
  8480. try:
  8481. with open(filename, 'w') as fp:
  8482. fp.write(svgcode)
  8483. except PermissionError:
  8484. self.inform.emit('[WARNING] %s' %
  8485. _("Permission denied, saving not possible.\n"
  8486. "Most likely another app is holding the file open and not accessible."))
  8487. return 'fail'
  8488. if self.defaults["global_open_style"] is False:
  8489. self.file_opened.emit("SVG", filename)
  8490. self.file_saved.emit("SVG", filename)
  8491. self.inform.emit('[success] %s: %s' %
  8492. (_("SVG file exported to"), filename))
  8493. def save_source_file(self, obj_name, filename, use_thread=True):
  8494. """
  8495. Exports a FlatCAM Object to an Gerber/Excellon file.
  8496. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8497. :param filename: Path to the Gerber file to save to.
  8498. :param use_thread: if to be run in a separate thread
  8499. :return:
  8500. """
  8501. self.report_usage("save source file()")
  8502. if filename is None:
  8503. filename = self.defaults["global_last_save_folder"]
  8504. self.log.debug("save source file()")
  8505. obj = self.collection.get_by_name(obj_name)
  8506. file_string = StringIO(obj.source_file)
  8507. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8508. if file_string.getvalue() == '':
  8509. self.inform.emit('[ERROR_NOTCL] %s' %
  8510. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8511. return 'fail'
  8512. try:
  8513. with open(filename, 'w') as file:
  8514. file.writelines('G04*\n')
  8515. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8516. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8517. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8518. file.writelines('G04 Created on : %s*\n' % time_string)
  8519. for line in file_string:
  8520. file.writelines(line)
  8521. except PermissionError:
  8522. self.inform.emit('[WARNING] %s' %
  8523. _("Permission denied, saving not possible.\n"
  8524. "Most likely another app is holding the file open and not accessible."))
  8525. return 'fail'
  8526. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8527. """
  8528. Exports a Excellon Object to an Excellon file.
  8529. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8530. :param filename: Path to the Excellon file to save to.
  8531. :param local_use:
  8532. :param use_thread: if to be run in a separate thread
  8533. :return:
  8534. """
  8535. self.report_usage("export_excellon()")
  8536. if filename is None:
  8537. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8538. self.log.debug("export_excellon()")
  8539. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8540. self.defaults["excellon_exp_decimals"]
  8541. )
  8542. if local_use is None:
  8543. try:
  8544. obj = self.collection.get_by_name(str(obj_name))
  8545. except Exception:
  8546. # TODO: The return behavior has not been established... should raise exception?
  8547. return "Could not retrieve object: %s" % obj_name
  8548. else:
  8549. obj = local_use
  8550. if not isinstance(obj, FlatCAMExcellon):
  8551. self.inform.emit('[ERROR_NOTCL] %s' %
  8552. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8553. return
  8554. # updated units
  8555. eunits = self.defaults["excellon_exp_units"]
  8556. ewhole = self.defaults["excellon_exp_integer"]
  8557. efract = self.defaults["excellon_exp_decimals"]
  8558. ezeros = self.defaults["excellon_exp_zeros"]
  8559. eformat = self.defaults["excellon_exp_format"]
  8560. slot_type = self.defaults["excellon_exp_slot_type"]
  8561. fc_units = self.defaults['units'].upper()
  8562. if fc_units == 'MM':
  8563. factor = 1 if eunits == 'METRIC' else 0.03937
  8564. else:
  8565. factor = 25.4 if eunits == 'METRIC' else 1
  8566. def make_excellon():
  8567. try:
  8568. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8569. header = 'M48\n'
  8570. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8571. (str(self.version), str(self.version_date))
  8572. header += ';Filename: %s' % str(obj_name) + '\n'
  8573. header += ';Created on : %s' % time_str + '\n'
  8574. if eformat == 'dec':
  8575. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8576. header += eunits + '\n'
  8577. for tool in obj.tools:
  8578. if eunits == 'METRIC':
  8579. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8580. tool=str(tool),
  8581. dec=2)
  8582. else:
  8583. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8584. tool=str(tool),
  8585. dec=4)
  8586. else:
  8587. if ezeros == 'LZ':
  8588. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8589. form='ndec', e_zeros='LZ', factor=factor,
  8590. slot_type=slot_type)
  8591. header += '%s,%s\n' % (eunits, 'LZ')
  8592. header += format_exc
  8593. for tool in obj.tools:
  8594. if eunits == 'METRIC':
  8595. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8596. tool=str(tool),
  8597. dec=2)
  8598. else:
  8599. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8600. tool=str(tool),
  8601. dec=4)
  8602. else:
  8603. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8604. form='ndec', e_zeros='TZ', factor=factor,
  8605. slot_type=slot_type)
  8606. header += '%s,%s\n' % (eunits, 'TZ')
  8607. header += format_exc
  8608. for tool in obj.tools:
  8609. if eunits == 'METRIC':
  8610. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8611. tool=str(tool),
  8612. dec=2)
  8613. else:
  8614. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8615. tool=str(tool),
  8616. dec=4)
  8617. header += '%\n'
  8618. footer = 'M30\n'
  8619. exported_excellon = header
  8620. exported_excellon += excellon_code
  8621. exported_excellon += footer
  8622. if local_use is None:
  8623. try:
  8624. with open(filename, 'w') as fp:
  8625. fp.write(exported_excellon)
  8626. except PermissionError:
  8627. self.inform.emit('[WARNING] %s' %
  8628. _("Permission denied, saving not possible.\n"
  8629. "Most likely another app is holding the file open and not accessible."))
  8630. return 'fail'
  8631. if self.defaults["global_open_style"] is False:
  8632. self.file_opened.emit("Excellon", filename)
  8633. self.file_saved.emit("Excellon", filename)
  8634. self.inform.emit('[success] %s: %s' %
  8635. (_("Excellon file exported to"), filename))
  8636. else:
  8637. return exported_excellon
  8638. except Exception as e:
  8639. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8640. return 'fail'
  8641. if use_thread is True:
  8642. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8643. def job_thread_exc(app_obj):
  8644. ret = make_excellon()
  8645. if ret == 'fail':
  8646. self.inform.emit('[ERROR_NOTCL] %s' %
  8647. _('Could not export Excellon file.'))
  8648. return
  8649. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8650. else:
  8651. ret = make_excellon()
  8652. if ret == 'fail':
  8653. self.inform.emit('[ERROR_NOTCL] %s' %
  8654. _('Could not export Excellon file.'))
  8655. return 'fail'
  8656. if local_use is not None:
  8657. return ret
  8658. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8659. """
  8660. Exports a Gerber Object to an Gerber file.
  8661. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8662. :param filename: Path to the Gerber file to save to.
  8663. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8664. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8665. :param use_thread: if to be run in a separate thread
  8666. :return:
  8667. """
  8668. self.report_usage("export_gerber()")
  8669. if filename is None:
  8670. filename = self.defaults["global_last_save_folder"]
  8671. self.log.debug("export_gerber()")
  8672. if local_use is None:
  8673. try:
  8674. obj = self.collection.get_by_name(str(obj_name))
  8675. except Exception:
  8676. # TODO: The return behavior has not been established... should raise exception?
  8677. return "Could not retrieve object: %s" % obj_name
  8678. else:
  8679. obj = local_use
  8680. # updated units
  8681. gunits = self.defaults["gerber_exp_units"]
  8682. gwhole = self.defaults["gerber_exp_integer"]
  8683. gfract = self.defaults["gerber_exp_decimals"]
  8684. gzeros = self.defaults["gerber_exp_zeros"]
  8685. fc_units = self.defaults['units'].upper()
  8686. if fc_units == 'MM':
  8687. factor = 1 if gunits == 'MM' else 0.03937
  8688. else:
  8689. factor = 25.4 if gunits == 'MM' else 1
  8690. def make_gerber():
  8691. try:
  8692. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8693. header = 'G04*\n'
  8694. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8695. (str(self.version), str(self.version_date))
  8696. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8697. header += 'G04 Created on : %s*' % time_str + '\n'
  8698. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8699. header += "%MO{units}*%\n".format(units=gunits)
  8700. for apid in obj.apertures:
  8701. if obj.apertures[apid]['type'] == 'C':
  8702. header += "%ADD{apid}{type},{size}*%\n".format(
  8703. apid=str(apid),
  8704. type='C',
  8705. size=(factor * obj.apertures[apid]['size'])
  8706. )
  8707. elif obj.apertures[apid]['type'] == 'R':
  8708. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8709. apid=str(apid),
  8710. type='R',
  8711. width=(factor * obj.apertures[apid]['width']),
  8712. height=(factor * obj.apertures[apid]['height'])
  8713. )
  8714. elif obj.apertures[apid]['type'] == 'O':
  8715. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8716. apid=str(apid),
  8717. type='O',
  8718. width=(factor * obj.apertures[apid]['width']),
  8719. height=(factor * obj.apertures[apid]['height'])
  8720. )
  8721. header += '\n'
  8722. # obsolete units but some software may need it
  8723. if gunits == 'IN':
  8724. header += 'G70*\n'
  8725. else:
  8726. header += 'G71*\n'
  8727. # Absolute Mode
  8728. header += 'G90*\n'
  8729. header += 'G01*\n'
  8730. # positive polarity
  8731. header += '%LPD*%\n'
  8732. footer = 'M02*\n'
  8733. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8734. exported_gerber = header
  8735. exported_gerber += gerber_code
  8736. exported_gerber += footer
  8737. if local_use is None:
  8738. try:
  8739. with open(filename, 'w') as fp:
  8740. fp.write(exported_gerber)
  8741. except PermissionError:
  8742. self.inform.emit('[WARNING] %s' %
  8743. _("Permission denied, saving not possible.\n"
  8744. "Most likely another app is holding the file open and not accessible."))
  8745. return 'fail'
  8746. if self.defaults["global_open_style"] is False:
  8747. self.file_opened.emit("Gerber", filename)
  8748. self.file_saved.emit("Gerber", filename)
  8749. self.inform.emit('[success] %s: %s' %
  8750. (_("Gerber file exported to"), filename))
  8751. else:
  8752. return exported_gerber
  8753. except Exception as e:
  8754. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8755. return 'fail'
  8756. if use_thread is True:
  8757. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8758. def job_thread_grb(app_obj):
  8759. ret = make_gerber()
  8760. if ret == 'fail':
  8761. self.inform.emit('[ERROR_NOTCL] %s' %
  8762. _('Could not export Gerber file.'))
  8763. return
  8764. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8765. else:
  8766. ret = make_gerber()
  8767. if ret == 'fail':
  8768. self.inform.emit('[ERROR_NOTCL] %s' %
  8769. _('Could not export Gerber file.'))
  8770. return 'fail'
  8771. if local_use is not None:
  8772. return ret
  8773. def export_dxf(self, obj_name, filename, use_thread=True):
  8774. """
  8775. Exports a Geometry Object to an DXF file.
  8776. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8777. :param filename: Path to the DXF file to save to.
  8778. :param use_thread: if to be run in a separate thread
  8779. :return:
  8780. """
  8781. self.report_usage("export_dxf()")
  8782. if filename is None:
  8783. filename = self.defaults["global_last_save_folder"]
  8784. self.log.debug("export_dxf()")
  8785. try:
  8786. obj = self.collection.get_by_name(str(obj_name))
  8787. except Exception:
  8788. # TODO: The return behavior has not been established... should raise exception?
  8789. return "Could not retrieve object: %s" % obj_name
  8790. def make_dxf():
  8791. try:
  8792. dxf_code = obj.export_dxf()
  8793. dxf_code.saveas(filename)
  8794. if self.defaults["global_open_style"] is False:
  8795. self.file_opened.emit("DXF", filename)
  8796. self.file_saved.emit("DXF", filename)
  8797. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8798. except Exception:
  8799. return 'fail'
  8800. if use_thread is True:
  8801. with self.proc_container.new(_("Exporting DXF")) as proc:
  8802. def job_thread_exc(app_obj):
  8803. ret_dxf_val = make_dxf()
  8804. if ret_dxf_val == 'fail':
  8805. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8806. return
  8807. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8808. else:
  8809. ret = make_dxf()
  8810. if ret == 'fail':
  8811. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8812. return
  8813. def import_svg(self, filename, geo_type='geometry', outname=None):
  8814. """
  8815. Adds a new Geometry Object to the projects and populates
  8816. it with shapes extracted from the SVG file.
  8817. :param filename: Path to the SVG file.
  8818. :param geo_type: Type of FlatCAM object that will be created from SVG
  8819. :param outname:
  8820. :return:
  8821. """
  8822. self.report_usage("import_svg()")
  8823. log.debug("App.import_svg()")
  8824. obj_type = ""
  8825. if geo_type is None or geo_type == "geometry":
  8826. obj_type = "geometry"
  8827. elif geo_type == "gerber":
  8828. obj_type = "gerber"
  8829. else:
  8830. self.inform.emit('[ERROR_NOTCL] %s' %
  8831. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8832. return
  8833. units = self.defaults['units'].upper()
  8834. def obj_init(geo_obj, app_obj):
  8835. geo_obj.import_svg(filename, obj_type, units=units)
  8836. geo_obj.multigeo = False
  8837. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  8838. with self.proc_container.new(_("Importing SVG")) as proc:
  8839. # Object name
  8840. name = outname or filename.split('/')[-1].split('\\')[-1]
  8841. self.new_object(obj_type, name, obj_init, autoselected=False)
  8842. # Register recent file
  8843. self.file_opened.emit("svg", filename)
  8844. # GUI feedback
  8845. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8846. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8847. """
  8848. Adds a new Geometry Object to the projects and populates
  8849. it with shapes extracted from the DXF file.
  8850. :param filename: Path to the DXF file.
  8851. :param geo_type: Type of FlatCAM object that will be created from DXF
  8852. :param outname:
  8853. :type putname: str
  8854. :return:
  8855. """
  8856. self.report_usage("import_dxf()")
  8857. obj_type = ""
  8858. if geo_type is None or geo_type == "geometry":
  8859. obj_type = "geometry"
  8860. elif geo_type == "gerber":
  8861. obj_type = geo_type
  8862. else:
  8863. self.inform.emit('[ERROR_NOTCL] %s' %
  8864. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8865. return
  8866. units = self.defaults['units'].upper()
  8867. def obj_init(geo_obj, app_obj):
  8868. geo_obj.import_dxf(filename, obj_type, units=units)
  8869. geo_obj.multigeo = False
  8870. with self.proc_container.new(_("Importing DXF")) as proc:
  8871. # Object name
  8872. name = outname or filename.split('/')[-1].split('\\')[-1]
  8873. self.new_object(obj_type, name, obj_init, autoselected=False)
  8874. self.progress.emit(20)
  8875. # Register recent file
  8876. self.file_opened.emit("dxf", filename)
  8877. # GUI feedback
  8878. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8879. self.progress.emit(100)
  8880. def open_gerber(self, filename, outname=None):
  8881. """
  8882. Opens a Gerber file, parses it and creates a new object for
  8883. it in the program. Thread-safe.
  8884. :param outname: Name of the resulting object. None causes the
  8885. name to be that of the file.
  8886. :param filename: Gerber file filename
  8887. :type filename: str
  8888. :return: None
  8889. """
  8890. # How the object should be initialized
  8891. def obj_init(gerber_obj, app_obj):
  8892. assert isinstance(gerber_obj, FlatCAMGerber), \
  8893. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8894. # Opening the file happens here
  8895. try:
  8896. gerber_obj.parse_file(filename)
  8897. except IOError:
  8898. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8899. return "fail"
  8900. except ParseError as err:
  8901. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8902. app_obj.log.error(str(err))
  8903. return "fail"
  8904. except Exception as e:
  8905. log.debug("App.open_gerber() --> %s" % str(e))
  8906. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8907. msg += traceback.format_exc()
  8908. app_obj.inform.emit(msg)
  8909. return "fail"
  8910. if gerber_obj.is_empty():
  8911. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8912. _("Object is not Gerber file or empty. Aborting object creation."))
  8913. return "fail"
  8914. App.log.debug("open_gerber()")
  8915. with self.proc_container.new(_("Opening Gerber")) as proc:
  8916. # Object name
  8917. name = outname or filename.split('/')[-1].split('\\')[-1]
  8918. # # ## Object creation # ##
  8919. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8920. if ret == 'fail':
  8921. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  8922. return 'fail'
  8923. # Register recent file
  8924. self.file_opened.emit("gerber", filename)
  8925. # GUI feedback
  8926. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8927. def open_excellon(self, filename, outname=None, plot=True):
  8928. """
  8929. Opens an Excellon file, parses it and creates a new object for
  8930. it in the program. Thread-safe.
  8931. :param outname: Name of the resulting object. None causes the
  8932. name to be that of the file.
  8933. :param filename: Excellon file filename
  8934. :type filename: str
  8935. :return: None
  8936. """
  8937. App.log.debug("open_excellon()")
  8938. # How the object should be initialized
  8939. def obj_init(excellon_obj, app_obj):
  8940. # self.progress.emit(20)
  8941. try:
  8942. ret = excellon_obj.parse_file(filename=filename)
  8943. if ret == "fail":
  8944. log.debug("Excellon parsing failed.")
  8945. self.inform.emit('[ERROR_NOTCL] %s' %
  8946. _("This is not Excellon file."))
  8947. return "fail"
  8948. except IOError:
  8949. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8950. (_("Cannot open file"), filename))
  8951. log.debug("Could not open Excellon object.")
  8952. self.progress.emit(0) # TODO: self and app_bjj mixed
  8953. return "fail"
  8954. except Exception:
  8955. msg = '[ERROR_NOTCL] %s' % \
  8956. _("An internal error has occurred. See shell.\n")
  8957. msg += traceback.format_exc()
  8958. app_obj.inform.emit(msg)
  8959. return "fail"
  8960. ret = excellon_obj.create_geometry()
  8961. if ret == 'fail':
  8962. log.debug("Could not create geometry for Excellon object.")
  8963. return "fail"
  8964. for tool in excellon_obj.tools:
  8965. if excellon_obj.tools[tool]['solid_geometry']:
  8966. return
  8967. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8968. (_("No geometry found in file"), filename))
  8969. return "fail"
  8970. with self.proc_container.new(_("Opening Excellon.")):
  8971. # Object name
  8972. name = outname or filename.split('/')[-1].split('\\')[-1]
  8973. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8974. if ret_val == 'fail':
  8975. self.inform.emit('[ERROR_NOTCL] %s' %
  8976. _('Open Excellon file failed. Probable not an Excellon file.'))
  8977. return
  8978. # Register recent file
  8979. self.file_opened.emit("excellon", filename)
  8980. # GUI feedback
  8981. self.inform.emit('[success] %s: %s' %
  8982. (_("Opened"), filename))
  8983. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  8984. """
  8985. Opens a G-gcode file, parses it and creates a new object for
  8986. it in the program. Thread-safe.
  8987. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8988. :param filename: G-code file filename
  8989. :type filename: str
  8990. :return: None
  8991. """
  8992. App.log.debug("open_gcode()")
  8993. # How the object should be initialized
  8994. def obj_init(job_obj, app_obj_):
  8995. """
  8996. :param job_obj: the resulting object
  8997. :type app_obj_: App
  8998. """
  8999. assert isinstance(app_obj_, App), \
  9000. "Initializer expected App, got %s" % type(app_obj_)
  9001. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9002. try:
  9003. f = open(filename)
  9004. gcode = f.read()
  9005. f.close()
  9006. except IOError:
  9007. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9008. (_("Failed to open"), filename))
  9009. return "fail"
  9010. job_obj.gcode = gcode
  9011. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9012. if gcode_ret == "fail":
  9013. self.inform.emit('[ERROR_NOTCL] %s' %
  9014. _("This is not GCODE"))
  9015. return "fail"
  9016. job_obj.create_geometry()
  9017. with self.proc_container.new(_("Opening G-Code.")):
  9018. # Object name
  9019. name = outname or filename.split('/')[-1].split('\\')[-1]
  9020. # New object creation and file processing
  9021. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9022. if obj_ret == 'fail':
  9023. self.inform.emit('[ERROR_NOTCL] %s' %
  9024. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9025. "Try to load it from File menu.\n "
  9026. "Attempting to create a FlatCAM CNCJob Object from "
  9027. "G-Code file failed during processing"))
  9028. return "fail"
  9029. # Register recent file
  9030. self.file_opened.emit("cncjob", filename)
  9031. # GUI feedback
  9032. self.inform.emit('[success] %s: %s' %
  9033. (_("Opened"), filename))
  9034. def open_script(self, filename, outname=None, silent=False):
  9035. """
  9036. Opens a Script file, parses it and creates a new object for
  9037. it in the program. Thread-safe.
  9038. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9039. :param filename: Script file filename
  9040. :type filename: str
  9041. :return: None
  9042. """
  9043. App.log.debug("open_script()")
  9044. with self.proc_container.new(_("Opening TCL Script...")):
  9045. try:
  9046. with open(filename, "r") as opened_script:
  9047. script_content = opened_script.readlines()
  9048. script_content = ''.join(script_content)
  9049. if silent is False:
  9050. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9051. except Exception as e:
  9052. log.debug("App.open_script() -> %s" % str(e))
  9053. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9054. return
  9055. # Object name
  9056. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9057. # New object creation and file processing
  9058. self.on_filenewscript(name=script_name, text=script_content)
  9059. # Register recent file
  9060. self.file_opened.emit("script", filename)
  9061. # GUI feedback
  9062. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9063. def open_config_file(self, filename, run_from_arg=None):
  9064. """
  9065. Loads a config file from the specified file.
  9066. :param filename: Name of the file from which to load.
  9067. :type filename: str
  9068. :return: None
  9069. """
  9070. App.log.debug("Opening config file: " + filename)
  9071. if run_from_arg:
  9072. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9073. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9074. _("Opening FlatCAM Config file.")),
  9075. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9076. color=QtGui.QColor("gray"))
  9077. # # add the tab if it was closed
  9078. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9079. # # first clear previous text in text editor (if any)
  9080. # self.ui.text_editor_tab.code_editor.clear()
  9081. #
  9082. # # Switch plot_area to CNCJob tab
  9083. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9084. # close the Code editor if already open
  9085. if self.toggle_codeeditor:
  9086. self.on_toggle_code_editor()
  9087. self.on_toggle_code_editor()
  9088. try:
  9089. if filename:
  9090. f = QtCore.QFile(filename)
  9091. if f.open(QtCore.QIODevice.ReadOnly):
  9092. stream = QtCore.QTextStream(f)
  9093. code_edited = stream.readAll()
  9094. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9095. f.close()
  9096. except IOError:
  9097. App.log.error("Failed to open config file: %s" % filename)
  9098. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9099. (_("Failed to open config file"), filename))
  9100. return
  9101. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9102. """
  9103. Loads a project from the specified file.
  9104. 1) Loads and parses file
  9105. 2) Registers the file as recently opened.
  9106. 3) Calls on_file_new()
  9107. 4) Updates options
  9108. 5) Calls new_object() with the object's from_dict() as init method.
  9109. 6) Calls plot_all() if plot=True
  9110. :param filename: Name of the file from which to load.
  9111. :type filename: str
  9112. :param run_from_arg: True if run for arguments
  9113. :param plot: If True plot all objects in the project
  9114. :param cli: run from command line
  9115. :return: None
  9116. """
  9117. App.log.debug("Opening project: " + filename)
  9118. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9119. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9120. if cli is None:
  9121. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9122. if run_from_arg:
  9123. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9124. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9125. _("Opening FlatCAM Project file.")),
  9126. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9127. color=QtGui.QColor("gray"))
  9128. # Open and parse an uncompressed Project file
  9129. try:
  9130. f = open(filename, 'r')
  9131. except IOError:
  9132. App.log.error("Failed to open project file: %s" % filename)
  9133. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9134. (_("Failed to open project file"), filename))
  9135. return
  9136. try:
  9137. d = json.load(f, object_hook=dict2obj)
  9138. except Exception as e:
  9139. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9140. (filename, str(e)))
  9141. f.close()
  9142. # Open and parse a compressed Project file
  9143. try:
  9144. with lzma.open(filename) as f:
  9145. file_content = f.read().decode('utf-8')
  9146. d = json.loads(file_content, object_hook=dict2obj)
  9147. except Exception as e:
  9148. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9149. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9150. (_("Failed to open project file"), filename))
  9151. return
  9152. # Clear the current project
  9153. # # NOT THREAD SAFE # ##
  9154. if run_from_arg is True:
  9155. pass
  9156. elif cli is True:
  9157. self.delete_selection_shape()
  9158. else:
  9159. self.on_file_new()
  9160. # Project options
  9161. self.options.update(d['options'])
  9162. self.project_filename = filename
  9163. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9164. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9165. if cli is None:
  9166. self.set_screen_units(self.options["units"])
  9167. # Re create objects
  9168. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9169. for obj in d['objs']:
  9170. def obj_init(obj_inst, app_inst):
  9171. obj_inst.from_dict(obj)
  9172. App.log.debug("Recreating from opened project an %s object: %s" %
  9173. (obj['kind'].capitalize(), obj['options']['name']))
  9174. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9175. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9176. if cli is None:
  9177. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9178. obj['kind'].upper(),
  9179. obj['options']['name']
  9180. )
  9181. )
  9182. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9183. self.inform.emit('[success] %s: %s' %
  9184. (_("Project loaded from"), filename))
  9185. self.should_we_save = False
  9186. self.file_opened.emit("project", filename)
  9187. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9188. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9189. if cli is None:
  9190. self.set_ui_title(name=self.project_filename)
  9191. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9192. def propagate_defaults(self, silent=False):
  9193. """
  9194. This method is used to set default values in classes. It's
  9195. an alternative to project options but allows the use
  9196. of values invisible to the user.
  9197. :return: None
  9198. """
  9199. if silent is False:
  9200. self.log.debug("propagate_defaults()")
  9201. # Which objects to update the given parameters.
  9202. routes = {
  9203. "global_zdownrate": CNCjob,
  9204. "excellon_zeros": Excellon,
  9205. "excellon_format_upper_in": Excellon,
  9206. "excellon_format_lower_in": Excellon,
  9207. "excellon_format_upper_mm": Excellon,
  9208. "excellon_format_lower_mm": Excellon,
  9209. "excellon_units": Excellon,
  9210. "gerber_use_buffer_for_union": Gerber,
  9211. "geometry_multidepth": Geometry
  9212. }
  9213. for param in routes:
  9214. if param in routes[param].defaults:
  9215. try:
  9216. routes[param].defaults[param] = self.defaults[param]
  9217. if silent is False:
  9218. self.log.debug(" " + param + " OK")
  9219. except KeyError:
  9220. if silent is False:
  9221. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9222. else:
  9223. # Try extracting the name:
  9224. # classname_param here is param in the object
  9225. if param.find(routes[param].__name__.lower() + "_") == 0:
  9226. p = param[len(routes[param].__name__) + 1:]
  9227. if p in routes[param].defaults:
  9228. routes[param].defaults[p] = self.defaults[param]
  9229. if silent is False:
  9230. self.log.debug(" " + param + " OK!")
  9231. def plot_all(self, zoom=True):
  9232. """
  9233. Re-generates all plots from all objects.
  9234. :return: None
  9235. """
  9236. self.log.debug("Plot_all()")
  9237. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9238. for obj in self.collection.get_list():
  9239. def worker_task(obj):
  9240. with self.proc_container.new("Plotting"):
  9241. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9242. if zoom:
  9243. self.object_plotted.emit(obj)
  9244. # Send to worker
  9245. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9246. def register_folder(self, filename):
  9247. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9248. def register_save_folder(self, filename):
  9249. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9250. def set_progress_bar(self, percentage, text=""):
  9251. self.ui.progress_bar.setValue(int(percentage))
  9252. def setup_shell(self):
  9253. """
  9254. Creates shell functions. Runs once at startup.
  9255. :return: None
  9256. """
  9257. self.log.debug("setup_shell()")
  9258. def shelp(p=None):
  9259. if not p:
  9260. return _("Available commands:\n") + \
  9261. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9262. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9263. if p not in commands:
  9264. return "Unknown command: %s" % p
  9265. return commands[p]["help"]
  9266. # --- Migrated to new architecture ---
  9267. # def options(name):
  9268. # ops = self.collection.get_by_name(str(name)).options
  9269. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9270. def h(*args):
  9271. """
  9272. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9273. and standalone parameters into list.
  9274. """
  9275. kwa = {}
  9276. a = []
  9277. n = len(args)
  9278. name = None
  9279. for i in range(n):
  9280. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9281. if match:
  9282. assert name is None
  9283. name = match.group(1)
  9284. continue
  9285. if name is None:
  9286. a.append(args[i])
  9287. else:
  9288. kwa[name] = args[i]
  9289. name = None
  9290. return a, kwa
  9291. @contextmanager
  9292. def wait_signal(signal, timeout=10000):
  9293. """
  9294. Block loop until signal emitted, timeout (ms) elapses
  9295. or unhandled exception happens in a thread.
  9296. :param timeout: time after which the loop is exited
  9297. :param signal: Signal to wait for.
  9298. """
  9299. loop = QtCore.QEventLoop()
  9300. # Normal termination
  9301. signal.connect(loop.quit)
  9302. # Termination by exception in thread
  9303. self.thread_exception.connect(loop.quit)
  9304. status = {'timed_out': False}
  9305. def report_quit():
  9306. status['timed_out'] = True
  9307. loop.quit()
  9308. yield
  9309. # Temporarily change how exceptions are managed.
  9310. oeh = sys.excepthook
  9311. ex = []
  9312. def except_hook(type_, value, traceback_):
  9313. ex.append(value)
  9314. oeh(type_, value, traceback_)
  9315. sys.excepthook = except_hook
  9316. # Terminate on timeout
  9317. if timeout is not None:
  9318. QtCore.QTimer.singleShot(timeout, report_quit)
  9319. # # ## Block ## ##
  9320. loop.exec_()
  9321. # Restore exception management
  9322. sys.excepthook = oeh
  9323. if ex:
  9324. self.raiseTclError(str(ex[0]))
  9325. if status['timed_out']:
  9326. raise Exception('Timed out!')
  9327. def make_docs():
  9328. output = ''
  9329. import collections
  9330. od = collections.OrderedDict(sorted(commands.items()))
  9331. for cmd_, val in od.items():
  9332. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9333. t = val['help']
  9334. usage_i = t.find('>')
  9335. if usage_i < 0:
  9336. expl = t
  9337. output += expl + '\n\n'
  9338. continue
  9339. expl = t[:usage_i - 1]
  9340. output += expl + '\n\n'
  9341. end_usage_i = t[usage_i:].find('\n')
  9342. if end_usage_i < 0:
  9343. end_usage_i = len(t[usage_i:])
  9344. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9345. else:
  9346. extras = t[usage_i+end_usage_i+1:]
  9347. parts = [s.strip() for s in extras.split('\n')]
  9348. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9349. for p in parts:
  9350. output += ' ' + p + '\n\n'
  9351. return output
  9352. '''
  9353. Howto implement TCL shell commands:
  9354. All parameters passed to command should be possible to set as None and test it afterwards.
  9355. This is because we need to see error caused in tcl,
  9356. if None value as default parameter is not allowed TCL will return empty error.
  9357. Use:
  9358. def mycommand(name=None,...):
  9359. Test it like this:
  9360. if name is None:
  9361. self.raise_tcl_error('Argument name is missing.')
  9362. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9363. otherwise we will miss it and processing will silently continue.
  9364. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9365. which is catched in exec_command and displayed in TCL shell console with red background.
  9366. Error in console is displayed with TCL trace.
  9367. This behavior works only within main thread,
  9368. errors with promissed tasks can be catched and detected only with log.
  9369. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9370. TCL shell.
  9371. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9372. '''
  9373. commands = {
  9374. 'help': {
  9375. 'fcn': shelp,
  9376. 'help': _("Shows list of commands.")
  9377. },
  9378. }
  9379. # Import/overwrite tcl commands as objects of TclCommand descendants
  9380. # This modifies the variable 'commands'.
  9381. tclCommands.register_all_commands(self, commands)
  9382. # Add commands to the tcl interpreter
  9383. for cmd in commands:
  9384. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9385. # Make the tcl puts function return instead of print to stdout
  9386. self.tcl.eval('''
  9387. rename puts original_puts
  9388. proc puts {args} {
  9389. if {[llength $args] == 1} {
  9390. return "[lindex $args 0]"
  9391. } else {
  9392. eval original_puts $args
  9393. }
  9394. }
  9395. ''')
  9396. def setup_recent_items(self):
  9397. # TODO: Move this to constructor
  9398. icons = {
  9399. "gerber": "share/flatcam_icon16.png",
  9400. "excellon": "share/drill16.png",
  9401. 'geometry': "share/geometry16.png",
  9402. "cncjob": "share/cnc16.png",
  9403. "script": "share/script_new24.png",
  9404. "document": "share/notes16_1.png",
  9405. "project": "share/project16.png",
  9406. "svg": "share/geometry16.png",
  9407. "dxf": "share/dxf16.png",
  9408. "pdf": "share/pdf32.png",
  9409. "image": "share/image16.png"
  9410. }
  9411. openers = {
  9412. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9413. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9414. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9415. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9416. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9417. "document": None,
  9418. 'project': self.open_project,
  9419. 'svg': self.import_svg,
  9420. 'dxf': self.import_dxf,
  9421. 'image': self.image_tool.import_image,
  9422. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9423. }
  9424. # Open recent file for files
  9425. try:
  9426. f = open(self.data_path + '/recent.json')
  9427. except IOError:
  9428. App.log.error("Failed to load recent item list.")
  9429. self.inform.emit('[ERROR_NOTCL] %s' %
  9430. _("Failed to load recent item list."))
  9431. return
  9432. try:
  9433. self.recent = json.load(f)
  9434. except json.scanner.JSONDecodeError:
  9435. App.log.error("Failed to parse recent item list.")
  9436. self.inform.emit('[ERROR_NOTCL] %s' %
  9437. _("Failed to parse recent item list."))
  9438. f.close()
  9439. return
  9440. f.close()
  9441. # Open recent file for projects
  9442. try:
  9443. fp = open(self.data_path + '/recent_projects.json')
  9444. except IOError:
  9445. App.log.error("Failed to load recent project item list.")
  9446. self.inform.emit('[ERROR_NOTCL] %s' %
  9447. _("Failed to load recent projects item list."))
  9448. return
  9449. try:
  9450. self.recent_projects = json.load(fp)
  9451. except json.scanner.JSONDecodeError:
  9452. App.log.error("Failed to parse recent project item list.")
  9453. self.inform.emit('[ERROR_NOTCL] %s' %
  9454. _("Failed to parse recent project item list."))
  9455. fp.close()
  9456. return
  9457. fp.close()
  9458. # Closure needed to create callbacks in a loop.
  9459. # Otherwise late binding occurs.
  9460. def make_callback(func, fname):
  9461. def opener():
  9462. func(fname)
  9463. return opener
  9464. def reset_recent_files():
  9465. # Reset menu
  9466. self.ui.recent.clear()
  9467. self.recent = []
  9468. try:
  9469. ff = open(self.data_path + '/recent.json', 'w')
  9470. except IOError:
  9471. App.log.error("Failed to open recent items file for writing.")
  9472. return
  9473. json.dump(self.recent, ff)
  9474. def reset_recent_projects():
  9475. # Reset menu
  9476. self.ui.recent_projects.clear()
  9477. self.recent_projects = []
  9478. try:
  9479. fp = open(self.data_path + '/recent_projects.json', 'w')
  9480. except IOError:
  9481. App.log.error("Failed to open recent projects items file for writing.")
  9482. return
  9483. json.dump(self.recent, fp)
  9484. # Reset menu
  9485. self.ui.recent.clear()
  9486. self.ui.recent_projects.clear()
  9487. # Create menu items for projects
  9488. for recent in self.recent_projects:
  9489. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9490. if recent['kind'] == 'project':
  9491. try:
  9492. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9493. # Attach callback
  9494. o = make_callback(openers[recent["kind"]], recent['filename'])
  9495. action.triggered.connect(o)
  9496. self.ui.recent_projects.addAction(action)
  9497. except KeyError:
  9498. App.log.error("Unsupported file type: %s" % recent["kind"])
  9499. # Last action in Recent Files menu is one that Clear the content
  9500. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9501. clear_action_proj.triggered.connect(reset_recent_projects)
  9502. self.ui.recent_projects.addSeparator()
  9503. self.ui.recent_projects.addAction(clear_action_proj)
  9504. # Create menu items for files
  9505. for recent in self.recent:
  9506. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9507. if recent['kind'] != 'project':
  9508. try:
  9509. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9510. # Attach callback
  9511. o = make_callback(openers[recent["kind"]], recent['filename'])
  9512. action.triggered.connect(o)
  9513. self.ui.recent.addAction(action)
  9514. except KeyError:
  9515. App.log.error("Unsupported file type: %s" % recent["kind"])
  9516. # Last action in Recent Files menu is one that Clear the content
  9517. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9518. clear_action.triggered.connect(reset_recent_files)
  9519. self.ui.recent.addSeparator()
  9520. self.ui.recent.addAction(clear_action)
  9521. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9522. # self.ui.menufilerecent.set_submenu(recent_menu)
  9523. # recent_menu.show_all()
  9524. # self.ui.recent.show()
  9525. self.log.debug("Recent items list has been populated.")
  9526. def setup_component_editor(self):
  9527. # label = QtWidgets.QLabel("Choose an item from Project")
  9528. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9529. sel_title = QtWidgets.QTextEdit(
  9530. _('<b>Shortcut Key List</b>'))
  9531. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9532. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9533. settings = QSettings("Open Source", "FlatCAM")
  9534. if settings.contains("notebook_font_size"):
  9535. fsize = settings.value('notebook_font_size', type=int)
  9536. else:
  9537. fsize = 12
  9538. tsize = fsize + int(fsize / 2)
  9539. # selected_text = (_('''
  9540. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9541. #
  9542. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9543. # The normal flow when working in FlatCAM is the following:</span></p>
  9544. #
  9545. # <ol>
  9546. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9547. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9548. # even dragging and dropping the files on the GUI.<br />
  9549. # <br />
  9550. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9551. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9552. # &nbsp;</li>
  9553. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9554. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9555. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9556. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9557. # <br />
  9558. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9559. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9560. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9561. # it even if it was out of focus.<br />
  9562. # <br />
  9563. # You can change the parameters in this screen and the flow direction is like this:<br />
  9564. # <br />
  9565. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9566. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9567. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9568. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9569. # </ol>
  9570. #
  9571. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9572. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9573. # <strong>F3</strong>.</span></p>
  9574. #
  9575. # ''').format(fsize=fsize, tsize=tsize))
  9576. selected_text = '''
  9577. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9578. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9579. {s1}</span></p>
  9580. <ol>
  9581. <li><span style="font-size:{fsize}px">{s2}<br />
  9582. <br />
  9583. {s3}</span><br />
  9584. &nbsp;</li>
  9585. <li><span style="font-size:{fsize}px">{s4}<br />
  9586. &nbsp;</li>
  9587. <br />
  9588. <li><span style="font-size:{fsize}px">{s5}<br />
  9589. &nbsp;</li>
  9590. <br />
  9591. <li><span style="font-size:{fsize}px">{s6}<br />
  9592. <br />
  9593. {s7}</span></li>
  9594. </ol>
  9595. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9596. '''.format(
  9597. title=_("Selected Tab - Choose an Item from Project Tab"),
  9598. subtitle=_("Details"),
  9599. s1=_("The normal flow when working in FlatCAM is the following:"),
  9600. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9601. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9602. "files on the GUI."),
  9603. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9604. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9605. "actions offered within the app."),
  9606. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9607. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9608. "SELECTED TAB will be updated with the object properties according to its kind: "
  9609. "Gerber, Excellon, Geometry or CNCJob object."),
  9610. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9611. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9612. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9613. "the SELECTED TAB and populate it even if it was out of focus."),
  9614. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9615. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9616. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9617. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9618. "(again, done in SELECTED TAB) --> Save GCode."),
  9619. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9620. "or through its own key shortcut: <b>F3</b>."),
  9621. tsize=tsize,
  9622. fsize=fsize
  9623. )
  9624. sel_title.setText(selected_text)
  9625. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9626. self.ui.selected_scroll_area.setWidget(sel_title)
  9627. def setup_obj_classes(self):
  9628. """
  9629. Sets up application specifics on the FlatCAMObj class.
  9630. :return: None
  9631. """
  9632. FlatCAMObj.app = self
  9633. ObjectCollection.app = self
  9634. Gerber.app = self
  9635. Excellon.app = self
  9636. Geometry.app = self
  9637. CNCjob.app = self
  9638. FCProcess.app = self
  9639. FCProcessContainer.app = self
  9640. def version_check(self):
  9641. """
  9642. Checks for the latest version of the program. Alerts the
  9643. user if theirs is outdated. This method is meant to be run
  9644. in a separate thread.
  9645. :return: None
  9646. """
  9647. self.log.debug("version_check()")
  9648. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9649. full_url = App.version_url + \
  9650. "?s=" + str(self.defaults['global_serial']) + \
  9651. "&v=" + str(self.version) + \
  9652. "&os=" + str(self.os) + \
  9653. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9654. else:
  9655. # no_stats dict; just so it won't break things on website
  9656. no_ststs_dict = {}
  9657. no_ststs_dict["global_ststs"] = {}
  9658. full_url = App.version_url + \
  9659. "?s=" + str(self.defaults['global_serial']) + \
  9660. "&v=" + str(self.version) + \
  9661. "&os=" + str(self.os) + \
  9662. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9663. App.log.debug("Checking for updates @ %s" % full_url)
  9664. # ## Get the data
  9665. try:
  9666. f = urllib.request.urlopen(full_url)
  9667. except Exception:
  9668. # App.log.warning("Failed checking for latest version. Could not connect.")
  9669. self.log.warning("Failed checking for latest version. Could not connect.")
  9670. self.inform.emit('[WARNING_NOTCL] %s' %
  9671. _("Failed checking for latest version. Could not connect."))
  9672. return
  9673. try:
  9674. data = json.load(f)
  9675. except Exception as e:
  9676. App.log.error("Could not parse information about latest version.")
  9677. self.inform.emit('[ERROR_NOTCL] %s' %
  9678. _("Could not parse information about latest version."))
  9679. App.log.debug("json.load(): %s" % str(e))
  9680. f.close()
  9681. return
  9682. f.close()
  9683. # ## Latest version?
  9684. if self.version >= data["version"]:
  9685. App.log.debug("FlatCAM is up to date!")
  9686. self.inform.emit('[success] %s' %
  9687. _("FlatCAM is up to date!"))
  9688. return
  9689. App.log.debug("Newer version available.")
  9690. self.message.emit(
  9691. _("Newer Version Available"),
  9692. _("There is a newer version of FlatCAM available for download:\n\n") +
  9693. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9694. _("info")
  9695. )
  9696. def on_plotcanvas_setup(self, container=None):
  9697. """
  9698. This is doing the setup for the plot area (VisPy canvas)
  9699. :param container: widget where to install the canvas
  9700. :return: None
  9701. """
  9702. if container:
  9703. plot_container = container
  9704. else:
  9705. plot_container = self.ui.right_layout
  9706. if self.is_legacy is False:
  9707. self.plotcanvas = PlotCanvas(plot_container, self)
  9708. else:
  9709. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9710. # So it can receive key presses
  9711. self.plotcanvas.native.setFocus()
  9712. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9713. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9714. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9715. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9716. # Keys over plot enabled
  9717. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9718. if self.defaults['global_cursor_type'] == 'small':
  9719. self.app_cursor = self.plotcanvas.new_cursor()
  9720. else:
  9721. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9722. if self.ui.grid_snap_btn.isChecked():
  9723. self.app_cursor.enabled = True
  9724. else:
  9725. self.app_cursor.enabled = False
  9726. if self.is_legacy is False:
  9727. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9728. else:
  9729. # will use the default Matplotlib axes
  9730. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9731. def on_zoom_fit(self, event):
  9732. """
  9733. Callback for zoom-out request. This can be either from the corresponding
  9734. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9735. with axes limits from the geometry bounds of all objects.
  9736. :param event: Ignored.
  9737. :return: None
  9738. """
  9739. if self.is_legacy is False:
  9740. self.plotcanvas.fit_view()
  9741. else:
  9742. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9743. width = xmax - xmin
  9744. height = ymax - ymin
  9745. xmin -= 0.05 * width
  9746. xmax += 0.05 * width
  9747. ymin -= 0.05 * height
  9748. ymax += 0.05 * height
  9749. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9750. def on_zoom_in(self):
  9751. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9752. def on_zoom_out(self):
  9753. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9754. def disable_all_plots(self):
  9755. self.report_usage("disable_all_plots()")
  9756. self.disable_plots(self.collection.get_list())
  9757. self.inform.emit('[success] %s' %
  9758. _("All plots disabled."))
  9759. def disable_other_plots(self):
  9760. self.report_usage("disable_other_plots()")
  9761. self.disable_plots(self.collection.get_non_selected())
  9762. self.inform.emit('[success] %s' %
  9763. _("All non selected plots disabled."))
  9764. def enable_all_plots(self):
  9765. self.report_usage("enable_all_plots()")
  9766. self.enable_plots(self.collection.get_list())
  9767. self.inform.emit('[success] %s' %
  9768. _("All plots enabled."))
  9769. def on_enable_sel_plots(self):
  9770. log.debug("App.on_enable_sel_plot()")
  9771. object_list = self.collection.get_selected()
  9772. self.enable_plots(objects=object_list)
  9773. self.inform.emit('[success] %s' %
  9774. _("Selected plots enabled..."))
  9775. def on_disable_sel_plots(self):
  9776. log.debug("App.on_disable_sel_plot()")
  9777. # self.inform.emit(_("Disabling plots ..."))
  9778. object_list = self.collection.get_selected()
  9779. self.disable_plots(objects=object_list)
  9780. self.inform.emit('[success] %s' %
  9781. _("Selected plots disabled..."))
  9782. def enable_plots(self, objects):
  9783. """
  9784. Disables plots
  9785. :param objects: list of Objects to be enabled
  9786. :return:
  9787. """
  9788. log.debug("Enabling plots ...")
  9789. # self.inform.emit(_("Working ..."))
  9790. for obj in objects:
  9791. if obj.options['plot'] is False:
  9792. obj.options.set_change_callback(lambda x: None)
  9793. obj.options['plot'] = True
  9794. obj.options.set_change_callback(obj.on_options_change)
  9795. def worker_task(objs):
  9796. with self.proc_container.new(_("Enabling plots ...")):
  9797. for obj in objs:
  9798. # obj.options['plot'] = True
  9799. if isinstance(obj, FlatCAMCNCjob):
  9800. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9801. else:
  9802. obj.plot(visible=True)
  9803. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9804. # self.plots_updated.emit()
  9805. def disable_plots(self, objects):
  9806. """
  9807. Disables plots
  9808. :param objects: list of Objects to be disabled
  9809. :return:
  9810. """
  9811. # if no objects selected then do nothing
  9812. if not self.collection.get_selected():
  9813. return
  9814. log.debug("Disabling plots ...")
  9815. # self.inform.emit(_("Working ..."))
  9816. for obj in objects:
  9817. if obj.options['plot'] is True:
  9818. obj.options.set_change_callback(lambda x: None)
  9819. obj.options['plot'] = False
  9820. obj.options.set_change_callback(obj.on_options_change)
  9821. try:
  9822. self.delete_selection_shape()
  9823. except Exception as e:
  9824. log.debug("App.disable_plots() --> %s" % str(e))
  9825. # self.plots_updated.emit()
  9826. def worker_task(objs):
  9827. with self.proc_container.new(_("Disabling plots ...")):
  9828. for obj in objs:
  9829. # obj.options['plot'] = True
  9830. if isinstance(obj, FlatCAMCNCjob):
  9831. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9832. else:
  9833. obj.plot(visible=False)
  9834. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9835. def toggle_plots(self, objects):
  9836. """
  9837. Toggle plots visibility
  9838. :param objects: list of Objects for which to be toggled the visibility
  9839. :return:
  9840. """
  9841. # if no objects selected then do nothing
  9842. if not self.collection.get_selected():
  9843. return
  9844. log.debug("Toggling plots ...")
  9845. self.inform.emit(_("Working ..."))
  9846. for obj in objects:
  9847. if obj.options['plot'] is False:
  9848. obj.options['plot'] = True
  9849. else:
  9850. obj.options['plot'] = False
  9851. self.plots_updated.emit()
  9852. def clear_plots(self):
  9853. objects = self.collection.get_list()
  9854. for obj in objects:
  9855. obj.clear(obj == objects[-1])
  9856. # Clear pool to free memory
  9857. self.clear_pool()
  9858. def generate_cnc_job(self, objects):
  9859. self.report_usage("generate_cnc_job()")
  9860. # for obj in objects:
  9861. # obj.generatecncjob()
  9862. for obj in objects:
  9863. obj.on_generatecnc_button_click()
  9864. def save_project(self, filename, quit_action=False, silent=False):
  9865. """
  9866. Saves the current project to the specified file.
  9867. :param filename: Name of the file in which to save.
  9868. :type filename: str
  9869. :param quit_action: if the project saving will be followed by an app quit; boolean
  9870. :param silent: if True will not display status messages
  9871. :return: None
  9872. """
  9873. self.log.debug("save_project()")
  9874. self.save_in_progress = True
  9875. with self.proc_container.new(_("Saving FlatCAM Project")):
  9876. # Capture the latest changes
  9877. # Current object
  9878. try:
  9879. self.collection.get_active().read_form()
  9880. except Exception as e:
  9881. self.log.debug("There was no active object. %s" % str(e))
  9882. pass
  9883. # Serialize the whole project
  9884. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9885. "options": self.options,
  9886. "version": self.version}
  9887. if self.defaults["global_save_compressed"] is True:
  9888. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9889. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9890. # # Write
  9891. f.write(g)
  9892. self.inform.emit('[success] %s: %s' %
  9893. (_("Project saved to"), filename))
  9894. else:
  9895. # Open file
  9896. try:
  9897. f = open(filename, 'w')
  9898. except IOError:
  9899. App.log.error("Failed to open file for saving: %s", filename)
  9900. return
  9901. # Write
  9902. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9903. f.close()
  9904. # verification of the saved project
  9905. # Open and parse
  9906. try:
  9907. saved_f = open(filename, 'r')
  9908. except IOError:
  9909. if silent is False:
  9910. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9911. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9912. )
  9913. return
  9914. try:
  9915. saved_d = json.load(saved_f, object_hook=dict2obj)
  9916. except Exception:
  9917. if silent is False:
  9918. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9919. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9920. )
  9921. f.close()
  9922. return
  9923. saved_f.close()
  9924. if silent is False:
  9925. if 'version' in saved_d:
  9926. self.inform.emit('[success] %s: %s' %
  9927. (_("Project saved to"), filename))
  9928. else:
  9929. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9930. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9931. )
  9932. tb_settings = QSettings("Open Source", "FlatCAM")
  9933. lock_state = self.ui.lock_action.isChecked()
  9934. tb_settings.setValue('toolbar_lock', lock_state)
  9935. # This will write the setting to the platform specific storage.
  9936. del tb_settings
  9937. # if quit:
  9938. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9939. # t.start()
  9940. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9941. def start_delayed_quit(self, delay, filename, should_quit=None):
  9942. """
  9943. :param delay: period of checking if project file size is more than zero; in seconds
  9944. :param filename: the name of the project file to be checked periodically for size more than zero
  9945. :param should_quit: if the task finished will be followed by an app quit; boolean
  9946. :return:
  9947. """
  9948. to_quit = should_quit
  9949. self.save_timer = QtCore.QTimer()
  9950. self.save_timer.setInterval(delay)
  9951. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9952. self.save_timer.start()
  9953. def check_project_file_size(self, filename, should_quit=None):
  9954. """
  9955. :param filename: the name of the project file to be checked periodically for size more than zero
  9956. :param should_quit: will quit the app if True; boolean
  9957. :return:
  9958. """
  9959. try:
  9960. if os.stat(filename).st_size > 0:
  9961. self.save_in_progress = False
  9962. self.save_timer.stop()
  9963. if should_quit:
  9964. self.app_quit.emit()
  9965. except Exception:
  9966. traceback.print_exc()
  9967. def on_plotarea_tab_closed(self, tab_idx):
  9968. widget = self.ui.plot_tab_area.widget(tab_idx)
  9969. if widget is not None:
  9970. widget.deleteLater()
  9971. self.ui.plot_tab_area.removeTab(tab_idx)
  9972. def on_options_app2project(self):
  9973. """
  9974. Callback for Options->Transfer Options->App=>Project. Copies options
  9975. from application defaults to project defaults.
  9976. :return: None
  9977. """
  9978. self.report_usage("on_options_app2project")
  9979. self.defaults_read_form()
  9980. self.options.update(self.defaults)
  9981. # self.options_write_form()
  9982. class ArgsThread(QtCore.QObject):
  9983. open_signal = pyqtSignal(list)
  9984. start = pyqtSignal()
  9985. if sys.platform == 'win32':
  9986. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9987. else:
  9988. address = ('/tmp/testipc', 'AF_UNIX')
  9989. def __init__(self):
  9990. super(ArgsThread, self).__init__()
  9991. self.start.connect(self.run)
  9992. def my_loop(self, address):
  9993. try:
  9994. listener = Listener(*address)
  9995. while True:
  9996. conn = listener.accept()
  9997. self.serve(conn)
  9998. except socket.error:
  9999. conn = Client(*address)
  10000. conn.send(sys.argv)
  10001. conn.send('close')
  10002. # close the current instance only if there are args
  10003. if len(sys.argv) > 1:
  10004. sys.exit()
  10005. def serve(self, conn):
  10006. while True:
  10007. msg = conn.recv()
  10008. if msg == 'close':
  10009. break
  10010. self.open_signal.emit(msg)
  10011. conn.close()
  10012. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10013. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10014. @pyqtSlot()
  10015. def run(self):
  10016. self.my_loop(self.address)
  10017. class GracefulException(Exception):
  10018. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10019. def __init__(self):
  10020. super().__init__()
  10021. def __str__(self):
  10022. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10023. # end of file