FlatCAMApp.py 455 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import winreg
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool
  28. import socket
  29. from array import array
  30. # #######################################
  31. # # Imports part of FlatCAM ##
  32. # #######################################
  33. from ObjectCollection import *
  34. from FlatCAMObj import *
  35. from flatcamGUI.PlotCanvas import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. fcTranslate.apply_language('strings')
  53. if '_' not in builtins.__dict__:
  54. _ = gettext.gettext
  55. # ########################################
  56. # # App ###
  57. # ########################################
  58. class App(QtCore.QObject):
  59. """
  60. The main application class. The constructor starts the GUI.
  61. """
  62. # Get Cmd Line Options
  63. cmd_line_shellfile = ''
  64. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  65. try:
  66. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  67. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  68. except getopt.GetoptError:
  69. print(cmd_line_help)
  70. sys.exit(2)
  71. for opt, arg in cmd_line_options:
  72. if opt == '-h':
  73. print(cmd_line_help)
  74. sys.exit()
  75. elif opt == '--shellfile':
  76. cmd_line_shellfile = arg
  77. # ## Logging ###
  78. log = logging.getLogger('base')
  79. log.setLevel(logging.DEBUG)
  80. # log.setLevel(logging.WARNING)
  81. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  82. handler = logging.StreamHandler()
  83. handler.setFormatter(formatter)
  84. log.addHandler(handler)
  85. # ##########################################################################
  86. # ################## Version and VERSION DATE ##############################
  87. # ##########################################################################
  88. version = 8.97
  89. version_date = "2019/09/15"
  90. beta = True
  91. # current date now
  92. date = str(datetime.today()).rpartition('.')[0]
  93. date = ''.join(c for c in date if c not in ':-')
  94. date = date.replace(' ', '_')
  95. # URL for update checks and statistics
  96. version_url = "http://flatcam.org/version"
  97. # App URL
  98. app_url = "http://flatcam.org"
  99. # Manual URL
  100. manual_url = "http://flatcam.org/manual/index.html"
  101. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  102. # this variable will hold the project status
  103. # if True it will mean that the project was modified and not saved
  104. should_we_save = False
  105. # flag is True if saving action has been triggered
  106. save_in_progress = False
  107. # ###########################################################################
  108. # ############################# Signals ################################
  109. # ###########################################################################
  110. # Inform the user
  111. # Handled by:
  112. # * App.info() --> Print on the status bar
  113. inform = QtCore.pyqtSignal(str)
  114. app_quit = QtCore.pyqtSignal()
  115. # General purpose background task
  116. worker_task = QtCore.pyqtSignal(dict)
  117. # File opened
  118. # Handled by:
  119. # * register_folder()
  120. # * register_recent()
  121. # Note: Setting the parameters to unicode does not seem
  122. # to have an effect. Then are received as Qstring
  123. # anyway.
  124. # File type and filename
  125. file_opened = QtCore.pyqtSignal(str, str)
  126. # File type and filename
  127. file_saved = QtCore.pyqtSignal(str, str)
  128. # Percentage of progress
  129. progress = QtCore.pyqtSignal(int)
  130. plots_updated = QtCore.pyqtSignal()
  131. # Emitted by new_object() and passes the new object as argument, plot flag.
  132. # on_object_created() adds the object to the collection, plots on appropriate flag
  133. # and emits new_object_available.
  134. object_created = QtCore.pyqtSignal(object, bool, bool)
  135. # Emitted when a object has been changed (like scaled, mirrored)
  136. object_changed = QtCore.pyqtSignal(object)
  137. # Emitted after object has been plotted.
  138. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  139. object_plotted = QtCore.pyqtSignal(object)
  140. # Emitted when a new object has been added or deleted from/to the collection
  141. object_status_changed = QtCore.pyqtSignal(object, str)
  142. message = QtCore.pyqtSignal(str, str, str)
  143. # Emmited when shell command is finished(one command only)
  144. shell_command_finished = QtCore.pyqtSignal(object)
  145. # Emitted when multiprocess pool has been recreated
  146. pool_recreated = QtCore.pyqtSignal(object)
  147. # Emitted when an unhandled exception happens
  148. # in the worker task.
  149. thread_exception = QtCore.pyqtSignal(object)
  150. # used to signal that there are arguments for the app
  151. args_at_startup = QtCore.pyqtSignal(list)
  152. # a reusable signal to replot a list of objects
  153. # should be disconnected after use so it can be reused
  154. replot_signal = pyqtSignal(list)
  155. def __init__(self, user_defaults=True, post_gui=None):
  156. """
  157. Starts the application.
  158. :return: app
  159. :rtype: App
  160. """
  161. App.log.info("FlatCAM Starting...")
  162. self.main_thread = QtWidgets.QApplication.instance().thread()
  163. # ############################################################################
  164. # # ################# OS-specific ############################################
  165. # ############################################################################
  166. portable = False
  167. # Folder for user settings.
  168. if sys.platform == 'win32':
  169. # #########################################################################
  170. # Setup the listening thread for another instance launching with args #####
  171. # #########################################################################
  172. # make sure the thread is stored by using a self. otherwise it's garbage collected
  173. self.th = QtCore.QThread()
  174. self.th.start(priority=QtCore.QThread.LowestPriority)
  175. self.new_launch = ArgsThread()
  176. self.new_launch.open_signal[list].connect(self.on_startup_args)
  177. self.new_launch.moveToThread(self.th)
  178. self.new_launch.start.emit()
  179. from win32com.shell import shell, shellcon
  180. if platform.architecture()[0] == '32bit':
  181. App.log.debug("Win32!")
  182. else:
  183. App.log.debug("Win64!")
  184. # #########################################################################
  185. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  186. # #########################################################################
  187. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  188. try:
  189. with open(config_file, 'r') as f:
  190. try:
  191. for line in f:
  192. param = str(line).rpartition('=')
  193. if param[0] == 'portable':
  194. try:
  195. portable = eval(param[2])
  196. except NameError:
  197. portable = False
  198. except Exception as e:
  199. log.debug('App.__init__() -->%s' % str(e))
  200. return
  201. except FileNotFoundError:
  202. pass
  203. if portable is False:
  204. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  205. else:
  206. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  207. self.os = 'windows'
  208. else: # Linux/Unix/MacOS
  209. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  210. self.os = 'unix'
  211. # ##########################################################################
  212. # ################## Setup folders and files ###############################
  213. # ##########################################################################
  214. if not os.path.exists(self.data_path):
  215. os.makedirs(self.data_path)
  216. App.log.debug('Created data folder: ' + self.data_path)
  217. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  218. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  219. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  220. if not os.path.exists(self.postprocessorpaths):
  221. os.makedirs(self.postprocessorpaths)
  222. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  223. # create current_defaults.FlatConfig file if there is none
  224. try:
  225. f = open(self.data_path + '/current_defaults.FlatConfig')
  226. f.close()
  227. except IOError:
  228. App.log.debug('Creating empty current_defaults.FlatConfig')
  229. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  230. json.dump({}, f)
  231. f.close()
  232. # create factory_defaults.FlatConfig file if there is none
  233. try:
  234. f = open(self.data_path + '/factory_defaults.FlatConfig')
  235. f.close()
  236. except IOError:
  237. App.log.debug('Creating empty factory_defaults.FlatConfig')
  238. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  239. json.dump({}, f)
  240. f.close()
  241. try:
  242. f = open(self.data_path + '/recent.json')
  243. f.close()
  244. except IOError:
  245. App.log.debug('Creating empty recent.json')
  246. f = open(self.data_path + '/recent.json', 'w')
  247. json.dump([], f)
  248. f.close()
  249. try:
  250. fp = open(self.data_path + '/recent_projects.json')
  251. fp.close()
  252. except IOError:
  253. App.log.debug('Creating empty recent_projects.json')
  254. fp = open(self.data_path + '/recent_projects.json', 'w')
  255. json.dump([], fp)
  256. fp.close()
  257. # Application directory. CHDIR to it. Otherwise, trying to load
  258. # GUI icons will fail as their path is relative.
  259. # This will fail under cx_freeze ...
  260. self.app_home = os.path.dirname(os.path.realpath(__file__))
  261. App.log.debug("Application path is " + self.app_home)
  262. App.log.debug("Started in " + os.getcwd())
  263. # cx_freeze workaround
  264. if os.path.isfile(self.app_home):
  265. self.app_home = os.path.dirname(self.app_home)
  266. os.chdir(self.app_home)
  267. # #############################################################################
  268. # ##################### CREATE MULTIPROCESSING POOL ###########################
  269. # #############################################################################
  270. self.pool = Pool()
  271. # #############################################################################
  272. # ##################### Initialize GUI ########################################
  273. # #############################################################################
  274. # FlatCAM colors used in plotting
  275. self.FC_light_green = '#BBF268BF'
  276. self.FC_dark_green = '#006E20BF'
  277. self.FC_light_blue = '#a5a5ffbf'
  278. self.FC_dark_blue = '#0000ffbf'
  279. QtCore.QObject.__init__(self)
  280. self.ui = FlatCAMGUI(self.version, self.beta, self)
  281. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  282. self.ui.final_save.connect(self.final_save)
  283. # #############################################################################
  284. # ############################## Data #########################################
  285. # #############################################################################
  286. self.recent = []
  287. self.recent_projects = []
  288. self.clipboard = QtWidgets.QApplication.clipboard()
  289. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  290. self.project_filename = None
  291. self.toggle_units_ignore = False
  292. # self.defaults_form = PreferencesUI()
  293. # when adding entries here read the comments in the method found bellow named:
  294. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  295. self.defaults_form_fields = {
  296. # General App
  297. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  298. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  299. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  300. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  301. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  302. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  303. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  304. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  305. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  306. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  307. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  308. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  309. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  310. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  311. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  312. "global_delete_confirmation": self.ui.general_defaults_form.general_app_group.delete_conf_cb,
  313. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  314. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  315. # General GUI Preferences
  316. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  317. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  318. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  319. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  320. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  321. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  322. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  323. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  324. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  325. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  326. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  327. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  328. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  329. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  330. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  331. # General GUI Settings
  332. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  333. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  334. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  335. # Gerber General
  336. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  337. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  338. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  339. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  340. "gerber_buffering": self.ui.gerber_defaults_form.gerber_gen_group.buffering_radio,
  341. # Gerber Options
  342. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  343. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  344. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  345. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  346. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  347. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  348. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  349. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  350. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  351. # Gerber Advanced Options
  352. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  353. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  354. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  355. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  356. # Gerber Export
  357. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  358. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  359. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  360. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  361. # Gerber Editor
  362. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  363. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  364. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  365. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  366. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  367. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  368. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  369. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  370. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  371. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  372. "gerber_editor_circ_angle":
  373. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  374. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  375. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  376. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  377. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  378. # Excellon General
  379. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  380. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  381. "excellon_format_upper_in":
  382. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  383. "excellon_format_lower_in":
  384. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  385. "excellon_format_upper_mm":
  386. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  387. "excellon_format_lower_mm":
  388. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  389. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  390. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  391. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  392. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  393. # Excellon Options
  394. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  395. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  396. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  397. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  398. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  399. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  400. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  401. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  402. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  403. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  404. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  405. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  406. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  407. # Excellon Advanced Options
  408. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  409. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  410. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  411. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  412. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  413. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  414. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  415. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  416. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  417. # Excellon Export
  418. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  419. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  420. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  421. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  422. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  423. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  424. # Excellon Editor
  425. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  426. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  427. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  428. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  429. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  430. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  431. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  432. "excellon_editor_circ_angle":
  433. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  434. # Excellon Slots
  435. "excellon_editor_slot_direction":
  436. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  437. "excellon_editor_slot_angle":
  438. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  439. "excellon_editor_slot_length":
  440. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  441. # Excellon Slots
  442. "excellon_editor_slot_array_size":
  443. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  444. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  445. "excellon_editor_slot_lin_pitch":
  446. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  447. "excellon_editor_slot_lin_angle":
  448. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  449. "excellon_editor_slot_circ_dir":
  450. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  451. "excellon_editor_slot_circ_angle":
  452. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  453. # Geometry General
  454. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  455. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  456. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  457. # Geometry Options
  458. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  459. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  460. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  461. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  462. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  463. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  464. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  465. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  466. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  467. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  468. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  469. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  470. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  471. # Geometry Advanced Options
  472. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  473. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  474. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  475. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  476. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  477. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  478. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  479. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  480. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  481. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  482. # Geometry Editor
  483. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  484. # CNCJob General
  485. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  486. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  487. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  488. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  489. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  490. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  491. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  492. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  493. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  494. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  495. # CNC Job Options
  496. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  497. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  498. # CNC Job Advanced Options
  499. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  500. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  501. # NCC Tool
  502. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  503. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  504. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  505. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  506. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  507. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  508. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  509. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  510. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  511. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  512. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  513. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  514. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  515. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  516. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  517. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  518. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  519. # CutOut Tool
  520. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  521. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  522. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  523. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  524. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  525. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  526. # Paint Area Tool
  527. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  528. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  529. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  530. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  531. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  532. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  533. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  534. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  535. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  536. # 2-sided Tool
  537. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  538. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  539. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  540. # Film Tool
  541. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  542. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  543. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  544. # Panelize Tool
  545. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  546. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  547. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  548. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  549. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  550. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  551. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  552. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  553. # Calculators Tool
  554. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  555. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  556. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  557. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  558. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  559. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  560. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  561. # Transformations Tool
  562. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  563. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  564. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  565. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  566. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  567. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  568. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  569. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  570. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  571. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  572. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  573. # SolderPaste Dispensing Tool
  574. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  575. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  576. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  577. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  578. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  579. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  580. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  581. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  582. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  583. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  584. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  585. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  586. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  587. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  588. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  589. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  590. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  591. # file associations
  592. "fa_excellon": self.ui.fa_defaults_form.fa_excellon_group.exc_list_text,
  593. "fa_gcode": self.ui.fa_defaults_form.fa_gcode_group.gco_list_text,
  594. # "fa_geometry": self.ui.fa_defaults_form.fa_geometry_group.close_paths_cb,
  595. "fa_gerber": self.ui.fa_defaults_form.fa_gerber_group.grb_list_text,
  596. }
  597. # ############################
  598. # ### LOAD POSTPROCESSORS ####
  599. # ############################
  600. self.postprocessors = load_postprocessors(self)
  601. for name in list(self.postprocessors.keys()):
  602. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  603. if name.partition('_')[0] == 'Paste':
  604. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  605. continue
  606. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  607. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  608. if name == 'hpgl':
  609. continue
  610. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  611. # ############################
  612. # ### LOAD LANGUAGES ####
  613. # ############################
  614. self.languages = fcTranslate.load_languages()
  615. for name in sorted(self.languages.values()):
  616. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  617. self.defaults = LoudDict()
  618. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  619. self.defaults.update({
  620. # Global APP Preferences
  621. "first_run": True,
  622. "units": "IN",
  623. "global_serial": 0,
  624. "global_stats": {},
  625. "global_tabs_detachable": True,
  626. "global_app_level": 'b',
  627. "global_portable": False,
  628. "global_language": 'English',
  629. "global_version_check": True,
  630. "global_send_stats": True,
  631. "global_pan_button": '2',
  632. "global_mselect_key": 'Control',
  633. "global_project_at_startup": False,
  634. "global_project_autohide": True,
  635. "global_toggle_tooltips": True,
  636. "global_worker_number": 2,
  637. "global_tolerance": 0.01,
  638. "global_open_style": True,
  639. "global_delete_confirmation": True,
  640. "global_compression_level": 3,
  641. "global_save_compressed": True,
  642. # Global GUI Preferences
  643. "global_gridx": 0.0393701,
  644. "global_gridy": 0.0393701,
  645. "global_snap_max": 0.001968504,
  646. "global_workspace": False,
  647. "global_workspaceT": "A4P",
  648. "global_grid_context_menu": {
  649. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  650. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  651. },
  652. "global_plot_fill": '#BBF268BF',
  653. "global_plot_line": '#006E20BF',
  654. "global_sel_fill": '#a5a5ffbf',
  655. "global_sel_line": '#0000ffbf',
  656. "global_alt_sel_fill": '#BBF268BF',
  657. "global_alt_sel_line": '#006E20BF',
  658. "global_draw_color": '#FF0000',
  659. "global_sel_draw_color": '#0000FF',
  660. "global_proj_item_color": '#000000',
  661. "global_proj_item_dis_color": '#b7b7cb',
  662. "global_toolbar_view": 511,
  663. "global_background_timeout": 300000, # Default value is 5 minutes
  664. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  665. # (python trace only for unknown errors),
  666. # 1 = show trace(show trace always),
  667. # 2 = (For the future).
  668. # Persistence
  669. "global_last_folder": None,
  670. "global_last_save_folder": None,
  671. # Default window geometry
  672. "global_def_win_x": 100,
  673. "global_def_win_y": 100,
  674. "global_def_win_w": 1024,
  675. "global_def_win_h": 650,
  676. "global_def_notebook_width": 1,
  677. # Constants...
  678. "global_defaults_save_period_ms": 20000, # Time between default saves.
  679. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  680. "global_shell_at_startup": False, # Show the shell at startup.
  681. "global_recent_limit": 10, # Max. items in recent list.
  682. "fit_key": 'V',
  683. "zoom_out_key": '-',
  684. "zoom_in_key": '=',
  685. "grid_toggle_key": 'G',
  686. "global_zoom_ratio": 1.5,
  687. "global_point_clipboard_format": "(%.4f, %.4f)",
  688. "global_zdownrate": None,
  689. # General GUI Settings
  690. "global_hover": False,
  691. "global_selection_shape": True,
  692. "global_layout": "compact",
  693. # Gerber General
  694. "gerber_plot": True,
  695. "gerber_solid": True,
  696. "gerber_multicolored": False,
  697. "gerber_circle_steps": 128,
  698. "gerber_use_buffer_for_union": True,
  699. "gerber_buffering": "full",
  700. # Gerber Options
  701. "gerber_isotooldia": 0.00787402,
  702. "gerber_isopasses": 1,
  703. "gerber_isooverlap": 0.00393701,
  704. "gerber_milling_type": "cl",
  705. "gerber_combine_passes": False,
  706. "gerber_noncoppermargin": 0.00393701,
  707. "gerber_noncopperrounded": False,
  708. "gerber_bboxmargin": 0.00393701,
  709. "gerber_bboxrounded": False,
  710. # Gerber Advanced Options
  711. "gerber_aperture_display": False,
  712. "gerber_aperture_scale_factor": 1.0,
  713. "gerber_aperture_buffer_factor": 0.0,
  714. "gerber_follow": False,
  715. # Gerber Export
  716. "gerber_exp_units": 'IN',
  717. "gerber_exp_integer": 2,
  718. "gerber_exp_decimals": 4,
  719. "gerber_exp_zeros": 'L',
  720. # Gerber Editor
  721. "gerber_editor_sel_limit": 30,
  722. "gerber_editor_newcode": 10,
  723. "gerber_editor_newsize": 0.8,
  724. "gerber_editor_newtype": 'C',
  725. "gerber_editor_newdim": "0.5, 0.5",
  726. "gerber_editor_array_size": 5,
  727. "gerber_editor_lin_axis": 'X',
  728. "gerber_editor_lin_pitch": 1,
  729. "gerber_editor_lin_angle": 0.0,
  730. "gerber_editor_circ_dir": 'CW',
  731. "gerber_editor_circ_angle": 0.0,
  732. "gerber_editor_scale_f": 1.0,
  733. "gerber_editor_buff_f": 0.1,
  734. "gerber_editor_ma_low": 0.0,
  735. "gerber_editor_ma_high": 1.0,
  736. # Excellon General
  737. "excellon_plot": True,
  738. "excellon_solid": True,
  739. "excellon_format_upper_in": 2,
  740. "excellon_format_lower_in": 4,
  741. "excellon_format_upper_mm": 3,
  742. "excellon_format_lower_mm": 3,
  743. "excellon_zeros": "L",
  744. "excellon_units": "INCH",
  745. "excellon_optimization_type": 'B',
  746. "excellon_search_time": 3,
  747. # Excellon Options
  748. "excellon_drillz": -0.0590551,
  749. "excellon_travelz": 0.0787402,
  750. "excellon_feedrate": 3.14961,
  751. "excellon_spindlespeed": None,
  752. "excellon_spindledir": 'CW',
  753. "excellon_dwell": False,
  754. "excellon_dwelltime": 1,
  755. "excellon_toolchange": False,
  756. "excellon_toolchangez": 0.5,
  757. "excellon_ppname_e": 'default',
  758. "excellon_tooldia": 0.0314961,
  759. "excellon_slot_tooldia": 0.0708661,
  760. "excellon_gcode_type": "drills",
  761. # Excellon Advanced Options
  762. "excellon_offset": 0.0,
  763. "excellon_toolchangexy": "0.0, 0.0",
  764. "excellon_startz": None,
  765. "excellon_endz": 0.5,
  766. "excellon_feedrate_rapid": 31.4961,
  767. "excellon_z_pdepth": -0.02,
  768. "excellon_feedrate_probe": 3.14961,
  769. "excellon_f_plunge": False,
  770. "excellon_f_retract": False,
  771. # Excellon Export
  772. "excellon_exp_units": 'INCH',
  773. "excellon_exp_format": 'ndec',
  774. "excellon_exp_integer": 2,
  775. "excellon_exp_decimals": 4,
  776. "excellon_exp_zeros": 'LZ',
  777. "excellon_exp_slot_type": 'routing',
  778. # Excellon Editor
  779. "excellon_editor_sel_limit": 30,
  780. "excellon_editor_newdia": 0.039,
  781. "excellon_editor_array_size": 5,
  782. "excellon_editor_lin_dir": 'X',
  783. "excellon_editor_lin_pitch": 0.1,
  784. "excellon_editor_lin_angle": 0.0,
  785. "excellon_editor_circ_dir": 'CW',
  786. "excellon_editor_circ_angle": 12,
  787. # Excellon Slots
  788. "excellon_editor_slot_direction": 'X',
  789. "excellon_editor_slot_angle": 0.0,
  790. "excellon_editor_slot_length": 5.0,
  791. # Excellon Slot Array
  792. "excellon_editor_slot_array_size": 5,
  793. "excellon_editor_slot_lin_dir": 'X',
  794. "excellon_editor_slot_lin_pitch": 0.1,
  795. "excellon_editor_slot_lin_angle": 0.0,
  796. "excellon_editor_slot_circ_dir": 'CW',
  797. "excellon_editor_slot_circ_angle": 0.0,
  798. # Geometry General
  799. "geometry_plot": True,
  800. "geometry_circle_steps": 128,
  801. "geometry_cnctooldia": "0.0944882",
  802. # Geometry Options
  803. "geometry_cutz": -0.0944882,
  804. "geometry_vtipdia": 0.1,
  805. "geometry_vtipangle": 30,
  806. "geometry_multidepth": False,
  807. "geometry_depthperpass": 0.0314961,
  808. "geometry_travelz": 0.0787402,
  809. "geometry_toolchange": False,
  810. "geometry_toolchangez": 0.5,
  811. "geometry_feedrate": 3.14961,
  812. "geometry_feedrate_z": 3.14961,
  813. "geometry_spindlespeed": None,
  814. "geometry_spindledir": 'CW',
  815. "geometry_dwell": False,
  816. "geometry_dwelltime": 1,
  817. "geometry_ppname_g": 'default',
  818. # Geometry Advanced Options
  819. "geometry_toolchangexy": "0.0, 0.0",
  820. "geometry_startz": None,
  821. "geometry_endz": 0.5,
  822. "geometry_feedrate_rapid": 3.14961,
  823. "geometry_extracut": False,
  824. "geometry_z_pdepth": -0.02,
  825. "geometry_f_plunge": False,
  826. "geometry_feedrate_probe": 3.14961,
  827. "geometry_segx": 0.0,
  828. "geometry_segy": 0.0,
  829. # Geometry Editor
  830. "geometry_editor_sel_limit": 30,
  831. # CNC Job General
  832. "cncjob_plot": True,
  833. "cncjob_plot_kind": 'all',
  834. "cncjob_annotation": True,
  835. "cncjob_annotation_fontsize": 9,
  836. "cncjob_annotation_fontcolor": '#990000',
  837. "cncjob_tooldia": 0.0393701,
  838. "cncjob_coords_type": "G90",
  839. "cncjob_coords_decimals": 4,
  840. "cncjob_fr_decimals": 2,
  841. "cncjob_steps_per_circle": 128,
  842. # CNC Job Options
  843. "cncjob_prepend": "",
  844. "cncjob_append": "",
  845. # CNC Job Advanced Options
  846. "cncjob_toolchange_macro": "",
  847. "cncjob_toolchange_macro_enable": False,
  848. "tools_ncctools": "0.0393701, 0.019685",
  849. "tools_nccorder": 'rev',
  850. "tools_nccoverlap": 0.015748,
  851. "tools_nccmargin": 0.0393701,
  852. "tools_nccmethod": "seed",
  853. "tools_nccconnect": True,
  854. "tools_ncccontour": True,
  855. "tools_nccrest": False,
  856. "tools_ncc_offset_choice": False,
  857. "tools_ncc_offset_value": 0.0000,
  858. "tools_nccref": 'itself',
  859. "tools_ncc_plotting": 'normal',
  860. "tools_nccmilling_type": 'cl',
  861. "tools_ncctool_type": 'V',
  862. "tools_ncccutz": -0.001968504,
  863. "tools_ncctipdia": 0.00393701,
  864. "tools_ncctipangle": 30,
  865. "tools_cutouttooldia": 0.0944882,
  866. "tools_cutoutkind": "single",
  867. "tools_cutoutmargin": 0.00393701,
  868. "tools_cutoutgapsize": 0.15748,
  869. "tools_gaps_ff": "4",
  870. "tools_cutout_convexshape": False,
  871. "tools_painttooldia": 0.023622,
  872. "tools_paintorder": 'rev',
  873. "tools_paintoverlap": 0.015748,
  874. "tools_paintmargin": 0.0,
  875. "tools_paintmethod": "seed",
  876. "tools_selectmethod": "single",
  877. "tools_pathconnect": True,
  878. "tools_paintcontour": True,
  879. "tools_paint_plotting": 'normal',
  880. "tools_2sided_mirror_axis": "X",
  881. "tools_2sided_axis_loc": "point",
  882. "tools_2sided_drilldia": 0.0393701,
  883. "tools_film_type": 'neg',
  884. "tools_film_boundary": 0.0393701,
  885. "tools_film_scale": 0,
  886. "tools_panelize_spacing_columns": 0,
  887. "tools_panelize_spacing_rows": 0,
  888. "tools_panelize_columns": 1,
  889. "tools_panelize_rows": 1,
  890. "tools_panelize_constrain": False,
  891. "tools_panelize_constrainx": 0.0,
  892. "tools_panelize_constrainy": 0.0,
  893. "tools_panelize_panel_type": 'gerber',
  894. "tools_calc_vshape_tip_dia": 0.007874,
  895. "tools_calc_vshape_tip_angle": 30,
  896. "tools_calc_vshape_cut_z": 0.000787,
  897. "tools_calc_electro_length": 10.0,
  898. "tools_calc_electro_width": 10.0,
  899. "tools_calc_electro_cdensity": 13.0,
  900. "tools_calc_electro_growth": 10.0,
  901. "tools_transform_rotate": 90,
  902. "tools_transform_skew_x": 0.0,
  903. "tools_transform_skew_y": 0.0,
  904. "tools_transform_scale_x": 1.0,
  905. "tools_transform_scale_y": 1.0,
  906. "tools_transform_scale_link": True,
  907. "tools_transform_scale_reference": True,
  908. "tools_transform_offset_x": 0.0,
  909. "tools_transform_offset_y": 0.0,
  910. "tools_transform_mirror_reference": False,
  911. "tools_transform_mirror_point": (0, 0),
  912. "tools_solderpaste_tools": "0.0393701, 0.011811",
  913. "tools_solderpaste_new": 0.011811,
  914. "tools_solderpaste_z_start": 0.00019685039,
  915. "tools_solderpaste_z_dispense": 0.00393701,
  916. "tools_solderpaste_z_stop": 0.00019685039,
  917. "tools_solderpaste_z_travel": 0.00393701,
  918. "tools_solderpaste_z_toolchange": 0.0393701,
  919. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  920. "tools_solderpaste_frxy": 3.0,
  921. "tools_solderpaste_frz": 3.0,
  922. "tools_solderpaste_frz_dispense": 0.0393701,
  923. "tools_solderpaste_speedfwd": 20,
  924. "tools_solderpaste_dwellfwd": 1,
  925. "tools_solderpaste_speedrev": 10,
  926. "tools_solderpaste_dwellrev": 1,
  927. "tools_solderpaste_pp": 'Paste_1',
  928. "tools_sub_close_paths": True,
  929. # file associations
  930. "fa_excellon": ".drl, .xln, .drd, .tap, .exc, .ncd",
  931. "fa_gcode": ".nc, .ncc, .tap, .gcode, .cnc, .ecs, .fnc, .dnc, .ncg, .gc, .fan, .fgc, .din, .xpi,"
  932. " .hnc, .h, .i, .ncp, .min, .gcd, .rol, .mpr, .ply, .out, .eia, .plt, .sbp, .mpf",
  933. "fa_gerber": ".gbr, .ger, .gtl, .gbl, .gts, .gbs, .gtp, .gbp, .gto, .gbo, .gm1, .gml, .gm3, .gko, .cmp, "
  934. ".sol, .stc, .sts, .plc, .pls, .crc, .crs, .tsm, .bsm, .ly2, .ly15, .dim, .mil, .grb, .top, "
  935. ".bot, .smt, .smb, .sst, .ssb, .spt, .spb, .pho, .gdo, .art, .gbd",
  936. })
  937. # ############################################################
  938. # ############### Load defaults from file ####################
  939. # ############################################################
  940. if user_defaults:
  941. self.load_defaults(filename='current_defaults')
  942. # #############################################################
  943. # ############## APPLY APP LANGUAGE ###########################
  944. # #############################################################
  945. ret_val = fcTranslate.apply_language('strings')
  946. if ret_val == "no language":
  947. self.inform.emit('[ERROR] %s' %
  948. _("Could not find the Language files. The App strings are missing."))
  949. log.debug("Could not find the Language files. The App strings are missing.")
  950. else:
  951. # make the current language the current selection on the language combobox
  952. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  953. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  954. # ##############################################################
  955. # ################# CREATE UNIQUE SERIAL NUMBER ################
  956. # ##############################################################
  957. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  958. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  959. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  960. self.save_defaults(silent=True)
  961. self.propagate_defaults(silent=True)
  962. self.restore_main_win_geom()
  963. def auto_save_defaults():
  964. try:
  965. self.save_defaults(silent=True)
  966. self.propagate_defaults(silent=True)
  967. finally:
  968. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  969. # the following lines activates automatic defaults save
  970. # if user_defaults:
  971. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  972. # self.options_form = PreferencesUI()
  973. self.options_form_fields = {
  974. "units": self.ui.general_options_form.general_app_group.units_radio,
  975. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  976. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  977. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  978. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  979. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  980. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  981. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  982. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  983. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  984. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  985. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  986. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  987. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  988. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  989. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  990. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  991. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  992. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  993. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  994. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  995. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  996. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  997. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  998. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  999. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1000. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1001. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1002. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  1003. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1004. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1005. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1006. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1007. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1008. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1009. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1010. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1011. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1012. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1013. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  1014. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1015. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1016. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1017. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1018. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1019. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1020. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1021. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  1022. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1023. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1024. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1025. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1026. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1027. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1028. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1029. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1030. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1031. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1032. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1033. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1034. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1035. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  1036. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1037. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1038. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1039. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1040. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1041. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1042. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1043. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1044. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1045. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1046. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1047. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1048. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1049. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1050. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1051. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1052. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1053. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1054. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1055. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1056. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1057. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1058. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1059. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1060. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1061. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1062. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1063. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1064. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1065. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1066. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1067. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1068. }
  1069. for name in list(self.postprocessors.keys()):
  1070. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1071. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1072. self.options = LoudDict()
  1073. self.options.set_change_callback(self.on_options_dict_change)
  1074. self.options.update({
  1075. "units": "IN",
  1076. "global_gridx": 1.0,
  1077. "global_gridy": 1.0,
  1078. "global_snap_max": 0.05,
  1079. "global_background_timeout": 300000, # Default value is 5 minutes
  1080. "global_verbose_error_level": 0, # Shell verbosity:
  1081. # 0 = default(python trace only for unknown errors),
  1082. # 1 = show trace(show trace allways), 2 = (For the future).
  1083. "gerber_plot": True,
  1084. "gerber_solid": True,
  1085. "gerber_multicolored": False,
  1086. "gerber_isotooldia": 0.016,
  1087. "gerber_isopasses": 1,
  1088. "gerber_isooverlap": 0.15,
  1089. "gerber_combine_passes": True,
  1090. "gerber_noncoppermargin": 0.0,
  1091. "gerber_noncopperrounded": False,
  1092. "gerber_bboxmargin": 0.0,
  1093. "gerber_bboxrounded": False,
  1094. "excellon_plot": True,
  1095. "excellon_solid": False,
  1096. "excellon_format_upper_in": 2,
  1097. "excellon_format_lower_in": 4,
  1098. "excellon_format_upper_mm": 3,
  1099. "excellon_format_lower_mm": 3,
  1100. "excellon_units": 'INCH',
  1101. "excellon_optimization_type": 'B',
  1102. "excellon_search_time": 3,
  1103. "excellon_zeros": "L",
  1104. "excellon_drillz": -0.1,
  1105. "excellon_travelz": 0.1,
  1106. "excellon_feedrate": 3.0,
  1107. "excellon_feedrate_rapid": 3.0,
  1108. "excellon_spindlespeed": None,
  1109. "excellon_spindledir": 'CW',
  1110. "excellon_dwell": True,
  1111. "excellon_dwelltime": 1000,
  1112. "excellon_toolchange": False,
  1113. "excellon_toolchangez": 1.0,
  1114. "excellon_toolchangexy": "0.0, 0.0",
  1115. "excellon_tooldia": 0.016,
  1116. "excellon_ppname_e": 'default',
  1117. "excellon_f_plunge": False,
  1118. "excellon_startz": None,
  1119. "excellon_endz": 2.0,
  1120. "geometry_plot": True,
  1121. "geometry_segx": 0.0,
  1122. "geometry_segy": 0.0,
  1123. "geometry_cutz": -0.002,
  1124. "geometry_vtipdia": 0.1,
  1125. "geometry_vtipangle": 30,
  1126. "geometry_travelz": 0.1,
  1127. "geometry_feedrate": 3.0,
  1128. "geometry_feedrate_z": 3.0,
  1129. "geometry_feedrate_rapid": 3.0,
  1130. "geometry_spindlespeed": None,
  1131. "geometry_spindledir": 'CW',
  1132. "geometry_dwell": True,
  1133. "geometry_dwelltime": 1000,
  1134. "geometry_cnctooldia": 0.016,
  1135. "geometry_toolchange": False,
  1136. "geometry_toolchangez": 2.0,
  1137. "geometry_toolchangexy": "0.0, 0.0",
  1138. "geometry_startz": None,
  1139. "geometry_endz": 2.0,
  1140. "geometry_ppname_g": "default",
  1141. "geometry_f_plunge": False,
  1142. "geometry_depthperpass": 0.002,
  1143. "geometry_multidepth": False,
  1144. "geometry_extracut": False,
  1145. "cncjob_plot": True,
  1146. "cncjob_tooldia": 0.016,
  1147. "cncjob_prepend": "",
  1148. "cncjob_append": "",
  1149. "tools_ncctools": "1.0, 0.5",
  1150. "tools_nccoverlap": 0.4,
  1151. "tools_nccmargin": 1,
  1152. "tools_cutouttooldia": 0.07,
  1153. "tools_cutoutmargin": 0.1,
  1154. "tools_cutoutgapsize": 0.15,
  1155. "tools_gaps_ff": "8",
  1156. "tools_painttooldia": 0.07,
  1157. "tools_paintoverlap": 0.15,
  1158. "tools_paintmargin": 0.0,
  1159. "tools_paintmethod": "seed",
  1160. "tools_selectmethod": "single",
  1161. "tools_pathconnect": True,
  1162. "tools_paintcontour": True,
  1163. "tools_2sided_mirror_axis": "X",
  1164. "tools_2sided_axis_loc": 'point',
  1165. "tools_2sided_drilldia": 1,
  1166. "tools_film_type": 'neg',
  1167. "tools_film_boundary": 1,
  1168. "tools_film_scale": 0,
  1169. "tools_panelize_spacing_columns": 0,
  1170. "tools_panelize_spacing_rows": 0,
  1171. "tools_panelize_columns": 1,
  1172. "tools_panelize_rows": 1,
  1173. "tools_panelize_constrain": False,
  1174. "tools_panelize_constrainx": 0.0,
  1175. "tools_panelize_constrainy": 0.0
  1176. })
  1177. self.options.update(self.defaults) # Copy app defaults to project options
  1178. self.gen_form = None
  1179. self.ger_form = None
  1180. self.exc_form = None
  1181. self.geo_form = None
  1182. self.cnc_form = None
  1183. self.tools_form = None
  1184. self.fa_form = None
  1185. self.on_options_combo_change(0) # Will show the initial form
  1186. # ################################
  1187. # ### Initialize the color box's color in Preferences -> Global -> Color
  1188. # Init Plot Colors
  1189. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1190. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1191. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1192. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1193. int(self.defaults['global_plot_fill'][7:9], 16))
  1194. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1195. int(self.defaults['global_plot_fill'][7:9], 16))
  1196. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1197. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1198. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1199. # Init Left-Right Selection colors
  1200. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1201. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1202. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1203. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1204. int(self.defaults['global_sel_fill'][7:9], 16))
  1205. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1206. int(self.defaults['global_sel_fill'][7:9], 16))
  1207. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1208. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1209. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1210. # Init Right-Left Selection colors
  1211. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1212. self.defaults['global_alt_sel_fill'])
  1213. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1214. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1215. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1216. int(self.defaults['global_sel_fill'][7:9], 16))
  1217. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1218. int(self.defaults['global_sel_fill'][7:9], 16))
  1219. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1220. self.defaults['global_alt_sel_line'])
  1221. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1222. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1223. # Init Draw color and Selection Draw Color
  1224. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1225. self.defaults['global_draw_color'])
  1226. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1227. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1228. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1229. self.defaults['global_sel_draw_color'])
  1230. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1231. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1232. # Init Project Items color
  1233. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1234. self.defaults['global_proj_item_color'])
  1235. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1236. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1237. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1238. self.defaults['global_proj_item_dis_color'])
  1239. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1240. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1241. # Init the Annotation CNC Job color
  1242. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1243. self.defaults['cncjob_annotation_fontcolor'])
  1244. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1245. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1246. # ### End of Data ####
  1247. # ###############################################
  1248. # ############# SETUP Plot Area #################
  1249. # ###############################################
  1250. start_plot_time = time.time() # debug
  1251. self.plotcanvas = None
  1252. self.app_cursor = None
  1253. self.hover_shapes = None
  1254. self.on_plotcanvas_setup()
  1255. end_plot_time = time.time()
  1256. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1257. self.ui.splitter.setStretchFactor(1, 2)
  1258. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1259. # depending on from where those tools are called different actions can be done
  1260. self.call_source = 'app'
  1261. # ##############################################
  1262. # ######### SETUP OBJECT COLLECTION ############
  1263. # ##############################################
  1264. self.collection = ObjectCollection(self)
  1265. self.ui.project_tab_layout.addWidget(self.collection.view)
  1266. # ### Adjust tabs width ## ##
  1267. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1268. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1269. self.collection.view.setMinimumWidth(290)
  1270. self.log.debug("Finished creating Object Collection.")
  1271. # ###############################################
  1272. # ############# Worker SETUP ####################
  1273. # ###############################################
  1274. if self.defaults["global_worker_number"]:
  1275. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1276. else:
  1277. self.workers = WorkerStack(workers_number=2)
  1278. self.worker_task.connect(self.workers.add_task)
  1279. self.log.debug("Finished creating Workers crew.")
  1280. # ################################################
  1281. # ############### Signal handling ################
  1282. # ################################################
  1283. # ############# Custom signals ##################
  1284. # signal for displaying messages in status bar
  1285. self.inform.connect(self.info)
  1286. # signal to be called when the app is quiting
  1287. self.app_quit.connect(self.quit_application)
  1288. self.message.connect(self.message_dialog)
  1289. self.progress.connect(self.set_progress_bar)
  1290. # signals that are emitted when object state changes
  1291. self.object_created.connect(self.on_object_created)
  1292. self.object_changed.connect(self.on_object_changed)
  1293. self.object_plotted.connect(self.on_object_plotted)
  1294. self.plots_updated.connect(self.on_plots_updated)
  1295. # signals emitted when file state change
  1296. self.file_opened.connect(self.register_recent)
  1297. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1298. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1299. # ############# Standard signals ###################
  1300. # ### Menu
  1301. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1302. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1303. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1304. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1305. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1306. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1307. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1308. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1309. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1310. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1311. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1312. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1313. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1314. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1315. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1316. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1317. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1318. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1319. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1320. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1321. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1322. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1323. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1324. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1325. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1326. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1327. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1328. self.ui.menufile_exit.triggered.connect(self.final_save)
  1329. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1330. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1331. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1332. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1333. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1334. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1335. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1336. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1337. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1338. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1339. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1340. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1341. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1342. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1343. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1344. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1345. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1346. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1347. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1348. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1349. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1350. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1351. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1352. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1353. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1354. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1355. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1356. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1357. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1358. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1359. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1360. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1361. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1362. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1363. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1364. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1365. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1366. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1367. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1368. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1369. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1370. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1371. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1372. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1373. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1374. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1375. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1376. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1377. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1378. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1379. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1380. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1381. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1382. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1383. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1384. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1385. # ToolBar signals
  1386. self.connect_toolbar_signals()
  1387. # Notebook signals
  1388. # make the right click on the notebook tab connect to a function
  1389. self.ui.notebook.setupContextMenu()
  1390. self.ui.notebook.addContextMenu(
  1391. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1392. initial_checked=self.defaults["global_tabs_detachable"])
  1393. # activate initial state
  1394. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1395. # Context Menu
  1396. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1397. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1398. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1399. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1400. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1401. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1402. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1403. self.ui.clearplot.triggered.connect(self.clear_plots)
  1404. self.ui.replot.triggered.connect(self.plot_all)
  1405. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1406. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1407. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1408. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1409. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1410. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1411. # Preferences Plot Area TAB
  1412. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1413. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1414. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1415. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1416. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1417. # ##############################
  1418. # ### GUI PREFERENCES SIGNALS ##
  1419. # ##############################
  1420. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1421. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1422. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1423. )
  1424. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1425. lambda: self.on_toggle_units(no_pref=False))
  1426. # ###############################################################
  1427. # ################### GUI COLORS SIGNALS ########################
  1428. # ###############################################################
  1429. # Setting plot colors signals
  1430. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1431. self.on_pf_color_entry)
  1432. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1433. self.on_pf_color_button)
  1434. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1435. self.on_pf_color_spinner)
  1436. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1437. self.on_pf_color_slider)
  1438. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1439. self.on_pl_color_entry)
  1440. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1441. self.on_pl_color_button)
  1442. # Setting selection (left - right) colors signals
  1443. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1444. self.on_sf_color_entry)
  1445. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1446. self.on_sf_color_button)
  1447. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1448. self.on_sf_color_spinner)
  1449. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1450. self.on_sf_color_slider)
  1451. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1452. self.on_sl_color_entry)
  1453. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1454. self.on_sl_color_button)
  1455. # Setting selection (right - left) colors signals
  1456. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1457. self.on_alt_sf_color_entry)
  1458. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1459. self.on_alt_sf_color_button)
  1460. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1461. self.on_alt_sf_color_spinner)
  1462. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1463. self.on_alt_sf_color_slider)
  1464. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1465. self.on_alt_sl_color_entry)
  1466. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1467. self.on_alt_sl_color_button)
  1468. # Setting Editor Draw colors signals
  1469. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1470. self.on_draw_color_entry)
  1471. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1472. self.on_draw_color_button)
  1473. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1474. self.on_sel_draw_color_entry)
  1475. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1476. self.on_sel_draw_color_button)
  1477. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1478. self.on_proj_color_entry)
  1479. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1480. self.on_proj_color_button)
  1481. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1482. self.on_proj_color_dis_entry)
  1483. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1484. self.on_proj_color_dis_button)
  1485. # ########## workspace setting signals ###########
  1486. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1487. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1488. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1489. # ########## CNC Job related signals #############
  1490. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1491. self.on_cnc_custom_parameters)
  1492. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1493. self.on_annotation_fontcolor_entry)
  1494. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1495. self.on_annotation_fontcolor_button)
  1496. # ########## Modify G-CODE Plot Area TAB ###########
  1497. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1498. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1499. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1500. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1501. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1502. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1503. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1504. # portability changed signal
  1505. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1506. # Object list
  1507. self.collection.view.activated.connect(self.on_row_activated)
  1508. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1509. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1510. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1511. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1512. self.on_excellon_defaults_button)
  1513. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1514. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1515. self.on_excellon_options_button)
  1516. # when there are arguments at application startup this get launched
  1517. self.args_at_startup[list].connect(lambda: self.on_startup_args())
  1518. # connect the 'Apply' buttons from the Preferences/File Associations
  1519. self.ui.fa_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1520. lambda: self.on_register_files(obj_type='excellon'))
  1521. self.ui.fa_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1522. lambda: self.on_register_files(obj_type='gcode'))
  1523. self.ui.fa_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1524. lambda: self.on_register_files(obj_type='gerber'))
  1525. # connect the abort_all_tasks related slots to the related signals
  1526. self.proc_container.idle_flag.connect(self.app_is_idle)
  1527. # #####################################################################################
  1528. # ########### FINISHED CONNECTING SIGNALS #############################################
  1529. # #####################################################################################
  1530. self.log.debug("Finished connecting Signals.")
  1531. # #####################################################################################
  1532. # ########################## Other setups #############################################
  1533. # #####################################################################################
  1534. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1535. self.tool_tab_locked = False
  1536. # decide if to show or hide the Notebook side of the screen at startup
  1537. if self.defaults["global_project_at_startup"] is True:
  1538. self.ui.splitter.setSizes([1, 1])
  1539. else:
  1540. self.ui.splitter.setSizes([0, 1])
  1541. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1542. self.setup_obj_classes()
  1543. self.setup_recent_items()
  1544. self.setup_component_editor()
  1545. # #####################################################################################
  1546. # ######################### Auto-complete KEYWORDS ####################################
  1547. # #####################################################################################
  1548. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1549. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1550. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1551. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1552. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1553. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1554. 'mirror', 'ncc',
  1555. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1556. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1557. 'pan', 'panel', 'panelize', 'plot', 'save', 'save_project', 'save_sys', 'scale',
  1558. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1559. 'version', 'write_gcode'
  1560. ]
  1561. self.ordinary_keywords = ['all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  1562. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'dist', 'drillz',
  1563. 'endz', 'extracut', 'factor', 'False', 'false', 'feedrate', 'feedrate_rapid',
  1564. 'filename', 'follow', 'gaps', 'gapsize', 'grid', 'gridoffset', 'gridoffsetx',
  1565. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  1566. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  1567. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  1568. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  1569. 'toolchange', 'toolchangez', 'tooldia', 'tools', 'travelz', 'True', 'true', 'type',
  1570. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1571. ]
  1572. self.tcl_keywords = [
  1573. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1574. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1575. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1576. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1577. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1578. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1579. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1580. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1581. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1582. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1583. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1584. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1585. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1586. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1587. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1588. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1589. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1590. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1591. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1592. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1593. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1594. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1595. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1596. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1597. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1598. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1599. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1600. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1601. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1602. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1603. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1604. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1605. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1606. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1607. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1608. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1609. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1610. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1611. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1612. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1613. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1614. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1615. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1616. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1617. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1618. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1619. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1620. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1621. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1622. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1623. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1624. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1625. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1626. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1627. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1628. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1629. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1630. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1631. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1632. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1633. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1634. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1635. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1636. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1637. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1638. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1639. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1640. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1641. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1642. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1643. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1644. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1645. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1646. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1647. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1648. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1649. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1650. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1651. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1652. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1653. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1654. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1655. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1656. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1657. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1658. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1659. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1660. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1661. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1662. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1663. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1664. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1665. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1666. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1667. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1668. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1669. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1670. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1671. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1672. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1673. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1674. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1675. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1676. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1677. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1678. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1679. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1680. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1681. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1682. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1683. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1684. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1685. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1686. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1687. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1688. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1689. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1690. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1691. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1692. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1693. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1694. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1695. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1696. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1697. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1698. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1699. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1700. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1701. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1702. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1703. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1704. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1705. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1706. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1707. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1708. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1709. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1710. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1711. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1712. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1713. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1714. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1715. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1716. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1717. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1718. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1719. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1720. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1721. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1722. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1723. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1724. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1725. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1726. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1727. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1728. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1729. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1730. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1731. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1732. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1733. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1734. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1735. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1736. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1737. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1738. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1739. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1740. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1741. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1742. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1743. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1744. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1745. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1746. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1747. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1748. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1749. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1750. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1751. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1752. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1753. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1754. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1755. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1756. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1757. ]
  1758. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1759. # ####################################################################################
  1760. # ####################### Shell SETUP ################################################
  1761. # ####################################################################################
  1762. self.shell = FCShell(self, version=self.version)
  1763. self.shell._edit.set_model_data(self.myKeywords)
  1764. self.ui.code_editor.set_model_data(self.myKeywords)
  1765. self.shell.setWindowIcon(self.ui.app_icon)
  1766. self.shell.setWindowTitle("FlatCAM Shell")
  1767. self.shell.resize(*self.defaults["global_shell_shape"])
  1768. self.shell.append_output("FlatCAM %s - " % self.version)
  1769. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1770. self.init_tcl()
  1771. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1772. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1773. self.ui.shell_dock.setWidget(self.shell)
  1774. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1775. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1776. QtWidgets.QDockWidget.DockWidgetFloatable |
  1777. QtWidgets.QDockWidget.DockWidgetClosable)
  1778. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1779. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1780. if self.defaults["global_shell_at_startup"]:
  1781. self.ui.shell_dock.show()
  1782. else:
  1783. self.ui.shell_dock.hide()
  1784. # ##################################################################################
  1785. # ###################### Tools and Plugins #########################################
  1786. # ##################################################################################
  1787. self.dblsidedtool = None
  1788. self.measurement_tool = None
  1789. self.panelize_tool = None
  1790. self.film_tool = None
  1791. self.paste_tool = None
  1792. self.calculator_tool = None
  1793. self.sub_tool = None
  1794. self.move_tool = None
  1795. self.cutout_tool = None
  1796. self.ncclear_tool = None
  1797. self.paint_tool = None
  1798. self.transform_tool = None
  1799. self.properties_tool = None
  1800. self.pdf_tool = None
  1801. self.image_tool = None
  1802. self.pcb_wizard_tool = None
  1803. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1804. self.install_tools()
  1805. # ### System Font Parsing ###
  1806. # self.f_parse = ParseFont(self)
  1807. # self.parse_system_fonts()
  1808. # #####################################################################################
  1809. # ########################## START-UP ARGUMENTS #######################################
  1810. # #####################################################################################
  1811. # test if the program was started with a script as parameter
  1812. if self.cmd_line_shellfile:
  1813. try:
  1814. with open(self.cmd_line_shellfile, "r") as myfile:
  1815. cmd_line_shellfile_text = myfile.read()
  1816. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1817. except Exception as ext:
  1818. print("ERROR: ", ext)
  1819. sys.exit(2)
  1820. # #####################################################################################
  1821. # ######################## Check for updates ##########################################
  1822. # #####################################################################################
  1823. # Separate thread (Not worker)
  1824. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1825. if (self.beta is False or self.beta is None) and \
  1826. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1827. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1828. self.thr2 = QtCore.QThread()
  1829. self.worker_task.emit({'fcn': self.version_check,
  1830. 'params': []})
  1831. self.thr2.start(QtCore.QThread.LowPriority)
  1832. # #####################################################################################
  1833. # ###################### Variables for global usage ###################################
  1834. # #####################################################################################
  1835. # register files with FlatCAM; it works only for Windows for now
  1836. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1837. self.on_register_files()
  1838. # coordinates for relative position display
  1839. self.rel_point1 = (0, 0)
  1840. self.rel_point2 = (0, 0)
  1841. # variable to store coordinates
  1842. self.pos = (0, 0)
  1843. self.pos_jump = (0, 0)
  1844. # variable to store mouse coordinates
  1845. self.mouse = [0, 0]
  1846. # decide if we have a double click or single click
  1847. self.doubleclick = False
  1848. # variable to store if a command is active (then the var is not None) and which one it is
  1849. self.command_active = None
  1850. # variable to store the status of moving selection action
  1851. # None value means that it's not an selection action
  1852. # True value = a selection from left to right
  1853. # False value = a selection from right to left
  1854. self.selection_type = None
  1855. # List to store the objects that are currently loaded in FlatCAM
  1856. # This list is updated on each object creation or object delete
  1857. self.all_objects_list = []
  1858. # List to store the objects that are selected
  1859. self.sel_objects_list = []
  1860. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1861. self.key_modifiers = None
  1862. # Variable to hold the status of the axis
  1863. self.toggle_axis = True
  1864. # Variable to store the status of the fullscreen event
  1865. self.toggle_fscreen = False
  1866. # Variable to store the status of the code editor
  1867. self.toggle_codeeditor = False
  1868. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1869. self.click_noproject = False
  1870. self.cursor = None
  1871. # Variable to store the GCODE that was edited
  1872. self.gcode_edited = ""
  1873. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1874. self.preferences_changed_flag = False
  1875. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1876. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1877. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1878. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1879. ]
  1880. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1881. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1882. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1883. 'mpf'
  1884. ]
  1885. self.svg_list = ['svg']
  1886. self.dxf_list = ['dxf']
  1887. self.pdf_list = ['pdf']
  1888. self.prj_list = ['flatprj']
  1889. self.conf_list = ['flatconfig']
  1890. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1891. # flag for polygons not cleared
  1892. self.poly_not_cleared = False
  1893. # VisPy visuals
  1894. self.isHovering = False
  1895. self.notHovering = True
  1896. # when True, the app has to return from any thread
  1897. self.abort_flag = False
  1898. # ###############################################################################
  1899. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  1900. # ############# It's done only once after install ###############
  1901. # ###############################################################################
  1902. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1903. fac_def_from_file = factory_file.read()
  1904. factory_defaults = json.loads(fac_def_from_file)
  1905. # if the file contain an empty dictionary then save the factory defaults into the file
  1906. if not factory_defaults:
  1907. self.save_factory_defaults(silent=False)
  1908. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1909. initial_lay = 'compact'
  1910. self.on_layout(lay=initial_lay)
  1911. # Set the combobox in Preferences to the current layout
  1912. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1913. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1914. factory_file.close()
  1915. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1916. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1917. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1918. # after the first run, this object should be False
  1919. self.defaults["first_run"] = False
  1920. # ###############################################################################
  1921. # ################# ADDING FlatCAM EDITORS section ##############################
  1922. # ###############################################################################
  1923. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1924. # at the first launch of the App , the editors will not be functional.
  1925. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1926. self.exc_editor = FlatCAMExcEditor(self)
  1927. self.grb_editor = FlatCAMGrbEditor(self)
  1928. self.log.debug("Finished adding FlatCAM Editor's.")
  1929. self.set_ui_title(name=_("New Project - Not saved"))
  1930. # ###############################################################################
  1931. # ####################### Finished the CONSTRUCTOR ##############################
  1932. # ###############################################################################
  1933. App.log.debug("END of constructor. Releasing control.")
  1934. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1935. # the path/file_name must be enclosed in quotes if it contain spaces
  1936. if App.args:
  1937. self.args_at_startup.emit(App.args)
  1938. @staticmethod
  1939. def copy_and_overwrite(from_path, to_path):
  1940. """
  1941. From here:
  1942. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1943. :param from_path: source path
  1944. :param to_path: destination path
  1945. :return: None
  1946. """
  1947. if os.path.exists(to_path):
  1948. shutil.rmtree(to_path)
  1949. try:
  1950. shutil.copytree(from_path, to_path)
  1951. except FileNotFoundError:
  1952. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1953. shutil.copytree(from_new_path, to_path)
  1954. def on_startup_args(self, args=None):
  1955. """
  1956. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1957. :param args: a list containing the application args at startup
  1958. :return: None
  1959. """
  1960. if args:
  1961. args_to_process = args
  1962. else:
  1963. args_to_process = App.args
  1964. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1965. for argument in args_to_process:
  1966. if '.FlatPrj' in argument:
  1967. try:
  1968. project_name = str(argument)
  1969. if project_name == "":
  1970. self.inform.emit(_("Open cancelled."))
  1971. else:
  1972. # self.open_project(project_name)
  1973. run_from_arg = True
  1974. # self.worker_task.emit({'fcn': self.open_project,
  1975. # 'params': [project_name, run_from_arg]})
  1976. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1977. except Exception as e:
  1978. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1979. elif '.FlatConfig' in argument:
  1980. try:
  1981. file_name = str(argument)
  1982. if file_name == "":
  1983. self.inform.emit(_("Open Config file failed."))
  1984. else:
  1985. # run_from_arg = True
  1986. # self.worker_task.emit({'fcn': self.open_config_file,
  1987. # 'params': [file_name, run_from_arg]})
  1988. self.open_config_file(file_name, run_from_arg=True)
  1989. except Exception as e:
  1990. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1991. elif '.FlatScript' in argument:
  1992. try:
  1993. file_name = str(argument)
  1994. if file_name == "":
  1995. self.inform.emit(_("Open Script file failed."))
  1996. else:
  1997. # run_from_arg = True
  1998. # self.worker_task.emit({'fcn': self.open_script_file,
  1999. # 'params': [file_name, run_from_arg]})
  2000. self.on_filerunscript(name=file_name)
  2001. except Exception as e:
  2002. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2003. else:
  2004. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2005. proc_arg = argument.lower()
  2006. for ext in exc_list:
  2007. proc_ext = ext.replace(' ', '')
  2008. if proc_ext.lower() in proc_arg and proc_ext != '':
  2009. file_name = str(argument)
  2010. if file_name == "":
  2011. self.inform.emit(_("Open Excellon file failed."))
  2012. else:
  2013. self.on_fileopenexcellon(name=file_name)
  2014. return
  2015. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2016. for ext in gco_list:
  2017. proc_ext = ext.replace(' ', '')
  2018. if proc_ext.lower() in proc_arg and proc_ext != '':
  2019. file_name = str(argument)
  2020. if file_name == "":
  2021. self.inform.emit(_("Open GCode file failed."))
  2022. else:
  2023. self.on_fileopengcode(name=file_name)
  2024. return
  2025. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2026. for ext in grb_list:
  2027. proc_ext = ext.replace(' ', '')
  2028. if proc_ext.lower() in proc_arg and proc_ext != '':
  2029. file_name = str(argument)
  2030. if file_name == "":
  2031. self.inform.emit(_("Open Gerber file failed."))
  2032. else:
  2033. self.on_fileopengerber(name=file_name)
  2034. return
  2035. def set_ui_title(self, name):
  2036. """
  2037. Sets the title of the main window.
  2038. :param name: String that store the project path and project name
  2039. :return: None
  2040. """
  2041. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2042. (self.version,
  2043. ('BETA' if self.beta else ''),
  2044. platform.architecture()[0],
  2045. name)
  2046. )
  2047. def defaults_read_form(self):
  2048. """
  2049. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2050. :return: None
  2051. """
  2052. for option in self.defaults_form_fields:
  2053. try:
  2054. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2055. except Exception as e:
  2056. log.debug("App.defaults_read_form() --> %s" % str(e))
  2057. def defaults_write_form(self, factor=None, fl_units=None):
  2058. """
  2059. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2060. self.defaults dictionary.
  2061. :param factor: will apply a factor to the values that written in the GUI elements
  2062. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2063. :return: None
  2064. """
  2065. for option in self.defaults:
  2066. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2067. # try:
  2068. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2069. # except KeyError:
  2070. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2071. # # TODO: Rethink this?
  2072. # pass
  2073. def defaults_write_form_field(self, field, factor=None, units=None):
  2074. """
  2075. Basically it is the worker in the self.defaults_write_form()
  2076. :param field: the GUI element in Preferences GUI to be updated
  2077. :param factor: factor to be applied to the field parameter
  2078. :param units: current FLatCAM measuring units
  2079. :return: None, it updates GUI elements
  2080. """
  2081. try:
  2082. if factor is None:
  2083. if units is None:
  2084. self.defaults_form_fields[field].set_value(self.defaults[field])
  2085. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2086. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2087. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2088. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2089. else:
  2090. if units is None:
  2091. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2092. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2093. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2094. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2095. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2096. except KeyError:
  2097. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2098. # TODO: Rethink this?
  2099. pass
  2100. except AttributeError:
  2101. log.debug(field)
  2102. def clear_pool(self):
  2103. """
  2104. Clear the multiprocessing pool and calls garbage collector.
  2105. :return: None
  2106. """
  2107. self.pool.close()
  2108. self.pool = Pool()
  2109. self.pool_recreated.emit(self.pool)
  2110. gc.collect()
  2111. def install_tools(self):
  2112. """
  2113. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2114. Instantiation of the Tools classes.
  2115. The order that the tools are installed is important as they can depend on each other install position.
  2116. :return: None
  2117. """
  2118. self.dblsidedtool = DblSidedTool(self)
  2119. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2120. self.measurement_tool = Measurement(self)
  2121. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2122. self.panelize_tool = Panelize(self)
  2123. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2124. self.film_tool = Film(self)
  2125. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2126. self.paste_tool = SolderPaste(self)
  2127. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2128. self.calculator_tool = ToolCalculator(self)
  2129. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2130. self.sub_tool = ToolSub(self)
  2131. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2132. self.move_tool = ToolMove(self)
  2133. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2134. before=self.ui.menueditorigin)
  2135. self.cutout_tool = CutOut(self)
  2136. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2137. before=self.measurement_tool.menuAction)
  2138. self.ncclear_tool = NonCopperClear(self)
  2139. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2140. before=self.measurement_tool.menuAction, separator=True)
  2141. self.paint_tool = ToolPaint(self)
  2142. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2143. before=self.measurement_tool.menuAction, separator=True)
  2144. self.transform_tool = ToolTransform(self)
  2145. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2146. self.properties_tool = Properties(self)
  2147. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2148. self.pdf_tool = ToolPDF(self)
  2149. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2150. separator=True)
  2151. self.image_tool = ToolImage(self)
  2152. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2153. separator=True)
  2154. self.pcb_wizard_tool = PcbWizard(self)
  2155. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2156. self.log.debug("Tools are installed.")
  2157. def remove_tools(self):
  2158. """
  2159. Will remove all the actions in the Tool menu.
  2160. :return: None
  2161. """
  2162. for act in self.ui.menutool.actions():
  2163. self.ui.menutool.removeAction(act)
  2164. def init_tools(self):
  2165. """
  2166. Initialize the Tool tab in the notebook side of the central widget.
  2167. Remove the actions in the Tools menu.
  2168. Instantiate again the FlatCAM tools (plugins).
  2169. All this is required when changing the layout: standard, compact etc.
  2170. :return: None
  2171. """
  2172. log.debug("init_tools()")
  2173. # delete the data currently in the Tools Tab and the Tab itself
  2174. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2175. if widget is not None:
  2176. widget.deleteLater()
  2177. self.ui.notebook.removeTab(2)
  2178. # rebuild the Tools Tab
  2179. self.ui.tool_tab = QtWidgets.QWidget()
  2180. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2181. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2182. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2183. self.ui.tool_scroll_area = VerticalScrollArea()
  2184. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2185. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2186. # first remove all of them
  2187. self.remove_tools()
  2188. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2189. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2190. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2191. # third install all of them
  2192. self.install_tools()
  2193. self.log.debug("Tools are initialized.")
  2194. # def parse_system_fonts(self):
  2195. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2196. # 'params': []})
  2197. def connect_toolbar_signals(self):
  2198. """
  2199. Reconnect the signals to the actions in the toolbar.
  2200. This has to be done each time after the FlatCAM tools are removed/installed.
  2201. :return: None
  2202. """
  2203. # Toolbar
  2204. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2205. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2206. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2207. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2208. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2209. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2210. self.ui.replot_btn.triggered.connect(self.plot_all)
  2211. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2212. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2213. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2214. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2215. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2216. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2217. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2218. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2219. self.ui.delete_btn.triggered.connect(self.on_delete)
  2220. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2221. # Tools Toolbar Signals
  2222. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2223. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2224. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2225. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2226. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2227. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2228. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2229. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2230. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2231. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2232. def object2editor(self):
  2233. """
  2234. Send the current Geometry or Excellon object (if any) into the it's editor.
  2235. :return: None
  2236. """
  2237. self.report_usage("object2editor()")
  2238. edited_object = self.collection.get_active()
  2239. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2240. isinstance(edited_object, FlatCAMExcellon):
  2241. pass
  2242. else:
  2243. self.inform.emit('[WARNING_NOTCL] %s' %
  2244. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2245. return
  2246. if isinstance(edited_object, FlatCAMGeometry):
  2247. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2248. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2249. # we set the notebook to hidden
  2250. self.ui.splitter.setSizes([0, 1])
  2251. if edited_object.multigeo is True:
  2252. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2253. if len(edited_tools) > 1:
  2254. self.inform.emit('[WARNING_NOTCL] %s' %
  2255. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2256. "is not possible.\n"
  2257. "Edit only one geometry at a time."))
  2258. # determine the tool dia of the selected tool
  2259. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2260. # now find the key in the edited_object.tools that has this tooldia
  2261. multi_tool = 1
  2262. for tool in edited_object.tools:
  2263. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2264. multi_tool = tool
  2265. break
  2266. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2267. else:
  2268. self.geo_editor.edit_fcgeometry(edited_object)
  2269. # set call source to the Editor we go into
  2270. self.call_source = 'geo_editor'
  2271. elif isinstance(edited_object, FlatCAMExcellon):
  2272. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2273. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2274. if self.ui.splitter.sizes()[0] == 0:
  2275. self.ui.splitter.setSizes([1, 1])
  2276. self.exc_editor.edit_fcexcellon(edited_object)
  2277. # set call source to the Editor we go into
  2278. self.call_source = 'exc_editor'
  2279. elif isinstance(edited_object, FlatCAMGerber):
  2280. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2281. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2282. if self.ui.splitter.sizes()[0] == 0:
  2283. self.ui.splitter.setSizes([1, 1])
  2284. self.grb_editor.edit_fcgerber(edited_object)
  2285. # set call source to the Editor we go into
  2286. self.call_source = 'grb_editor'
  2287. # make sure that we can't select another object while in Editor Mode:
  2288. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2289. self.ui.project_frame.setDisabled(True)
  2290. # delete any selection shape that might be active as they are not relevant in Editor
  2291. self.delete_selection_shape()
  2292. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2293. self.ui.plot_tab_area.protectTab(0)
  2294. self.inform.emit('[WARNING_NOTCL] %s' %
  2295. _("Editor is activated ..."))
  2296. self.should_we_save = True
  2297. def editor2object(self, cleanup=None):
  2298. """
  2299. Transfers the Geometry or Excellon from it's editor to the current object.
  2300. :return: None
  2301. """
  2302. self.report_usage("editor2object()")
  2303. # do not update a geometry or excellon object unless it comes out of an editor
  2304. if self.call_source != 'app':
  2305. edited_obj = self.collection.get_active()
  2306. if cleanup is None:
  2307. msgbox = QtWidgets.QMessageBox()
  2308. msgbox.setText(_("Do you want to save the edited object?"))
  2309. msgbox.setWindowTitle(_("Close Editor"))
  2310. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2311. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2312. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2313. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2314. msgbox.setDefaultButton(bt_yes)
  2315. msgbox.exec_()
  2316. response = msgbox.clickedButton()
  2317. if response == bt_yes:
  2318. # clean the Tools Tab
  2319. self.ui.tool_scroll_area.takeWidget()
  2320. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2321. self.ui.notebook.setTabText(2, "Tool")
  2322. if isinstance(edited_obj, FlatCAMGeometry):
  2323. obj_type = "Geometry"
  2324. if cleanup is None:
  2325. self.geo_editor.update_fcgeometry(edited_obj)
  2326. self.geo_editor.update_options(edited_obj)
  2327. self.geo_editor.deactivate()
  2328. # update the geo object options so it is including the bounding box values
  2329. try:
  2330. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2331. edited_obj.options['xmin'] = xmin
  2332. edited_obj.options['ymin'] = ymin
  2333. edited_obj.options['xmax'] = xmax
  2334. edited_obj.options['ymax'] = ymax
  2335. except AttributeError as e:
  2336. self.inform.emit('[WARNING] %s' %
  2337. _("Object empty after edit."))
  2338. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2339. elif isinstance(edited_obj, FlatCAMGerber):
  2340. obj_type = "Gerber"
  2341. if cleanup is None:
  2342. self.grb_editor.update_fcgerber()
  2343. self.grb_editor.update_options(edited_obj)
  2344. self.grb_editor.deactivate_grb_editor()
  2345. # delete the old object (the source object) if it was an empty one
  2346. if len(edited_obj.solid_geometry) == 0:
  2347. old_name = edited_obj.options['name']
  2348. self.collection.set_active(old_name)
  2349. self.collection.delete_active()
  2350. elif isinstance(edited_obj, FlatCAMExcellon):
  2351. obj_type = "Excellon"
  2352. if cleanup is None:
  2353. self.exc_editor.update_fcexcellon(edited_obj)
  2354. self.exc_editor.update_options(edited_obj)
  2355. self.exc_editor.deactivate()
  2356. else:
  2357. self.inform.emit('[WARNING_NOTCL] %s' %
  2358. _("Select a Gerber, Geometry or Excellon Object to update."))
  2359. return
  2360. self.inform.emit('[selected] %s %s' %
  2361. (obj_type, _("is updated, returning to App...")))
  2362. elif response == bt_no:
  2363. # clean the Tools Tab
  2364. self.ui.tool_scroll_area.takeWidget()
  2365. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2366. self.ui.notebook.setTabText(2, "Tool")
  2367. if isinstance(edited_obj, FlatCAMGeometry):
  2368. self.geo_editor.deactivate()
  2369. elif isinstance(edited_obj, FlatCAMGerber):
  2370. self.grb_editor.deactivate_grb_editor()
  2371. elif isinstance(edited_obj, FlatCAMExcellon):
  2372. self.exc_editor.deactivate()
  2373. # set focus on the project tab
  2374. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2375. else:
  2376. self.inform.emit('[WARNING_NOTCL] %s' %
  2377. _("Select a Gerber, Geometry or Excellon Object to update."))
  2378. return
  2379. elif response == bt_cancel:
  2380. return
  2381. else:
  2382. if isinstance(edited_obj, FlatCAMGeometry):
  2383. self.geo_editor.deactivate()
  2384. elif isinstance(edited_obj, FlatCAMGerber):
  2385. self.grb_editor.deactivate_grb_editor()
  2386. elif isinstance(edited_obj, FlatCAMExcellon):
  2387. self.exc_editor.deactivate()
  2388. else:
  2389. self.inform.emit('[WARNING_NOTCL] %s' %
  2390. _("Select a Gerber, Geometry or Excellon Object to update."))
  2391. return
  2392. # if notebook is hidden we show it
  2393. if self.ui.splitter.sizes()[0] == 0:
  2394. self.ui.splitter.setSizes([1, 1])
  2395. # restore the call_source to app
  2396. self.call_source = 'app'
  2397. edited_obj.plot()
  2398. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2399. self.ui.plot_tab_area.protectTab(0)
  2400. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2401. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2402. self.ui.project_frame.setDisabled(False)
  2403. def get_last_folder(self):
  2404. """
  2405. Get the folder path from where the last file was opened.
  2406. :return: String, last opened folder path
  2407. """
  2408. return self.defaults["global_last_folder"]
  2409. def get_last_save_folder(self):
  2410. """
  2411. Get the folder path from where the last file was saved.
  2412. :return: String, last saved folder path
  2413. """
  2414. loc = self.defaults["global_last_save_folder"]
  2415. if loc is None:
  2416. loc = self.defaults["global_last_folder"]
  2417. if loc is None:
  2418. loc = os.path.dirname(__file__)
  2419. return loc
  2420. def report_usage(self, resource):
  2421. """
  2422. Increments usage counter for the given resource
  2423. in self.defaults['global_stats'].
  2424. :param resource: Name of the resource.
  2425. :return: None
  2426. """
  2427. if resource in self.defaults['global_stats']:
  2428. self.defaults['global_stats'][resource] += 1
  2429. else:
  2430. self.defaults['global_stats'][resource] = 1
  2431. def init_tcl(self):
  2432. """
  2433. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2434. :return: None
  2435. """
  2436. if hasattr(self, 'tcl'):
  2437. # self.tcl = None
  2438. # TODO we need to clean non default variables and procedures here
  2439. # new object cannot be used here as it will not remember values created for next passes,
  2440. # because tcl was execudted in old instance of TCL
  2441. pass
  2442. else:
  2443. self.tcl = tk.Tcl()
  2444. self.setup_shell()
  2445. self.log.debug("TCL Shell has been initialized.")
  2446. # TODO: This shouldn't be here.
  2447. class TclErrorException(Exception):
  2448. """
  2449. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2450. """
  2451. pass
  2452. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2453. """
  2454. Shows a message on the FlatCAM Shell
  2455. :param msg: Message to display.
  2456. :param show: Opens the shell.
  2457. :param error: Shows the message as an error.
  2458. :param warning: Shows the message as an warning.
  2459. :param success: Shows the message as an success.
  2460. :param selected: Indicate that something was selected on canvas
  2461. :return: None
  2462. """
  2463. if show:
  2464. self.ui.shell_dock.show()
  2465. try:
  2466. if error:
  2467. self.shell.append_error(msg + "\n")
  2468. elif warning:
  2469. self.shell.append_warning(msg + "\n")
  2470. elif success:
  2471. self.shell.append_success(msg + "\n")
  2472. elif selected:
  2473. self.shell.append_selected(msg + "\n")
  2474. else:
  2475. self.shell.append_output(msg + "\n")
  2476. except AttributeError:
  2477. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2478. def raise_tcl_unknown_error(self, unknownException):
  2479. """
  2480. Raise exception if is different type than TclErrorException
  2481. this is here mainly to show unknown errors inside TCL shell console.
  2482. :param unknownException:
  2483. :return:
  2484. """
  2485. if not isinstance(unknownException, self.TclErrorException):
  2486. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2487. else:
  2488. raise unknownException
  2489. def display_tcl_error(self, error, error_info=None):
  2490. """
  2491. Escape bracket [ with '\' otherwise there is error
  2492. "ERROR: missing close-bracket" instead of real error
  2493. :param error: it may be text or exception
  2494. :param error_info: Some informations about the error
  2495. :return: None
  2496. """
  2497. if isinstance(error, Exception):
  2498. exc_type, exc_value, exc_traceback = error_info
  2499. if not isinstance(error, self.TclErrorException):
  2500. show_trace = 1
  2501. else:
  2502. show_trace = int(self.defaults['global_verbose_error_level'])
  2503. if show_trace > 0:
  2504. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2505. trc_formated = []
  2506. for a in reversed(trc):
  2507. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2508. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2509. else:
  2510. text = "%s" % error
  2511. else:
  2512. text = error
  2513. text = text.replace('[', '\\[').replace('"', '\\"')
  2514. self.tcl.eval('return -code error "%s"' % text)
  2515. def raise_tcl_error(self, text):
  2516. """
  2517. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2518. :param text: text of error
  2519. :return: raise exception
  2520. """
  2521. self.display_tcl_error(text)
  2522. raise self.TclErrorException(text)
  2523. def exec_command(self, text):
  2524. """
  2525. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2526. Also handles execution in separated threads
  2527. :param text: FlatCAM TclCommand with parameters
  2528. :return: output if there was any
  2529. """
  2530. self.report_usage('exec_command')
  2531. result = self.exec_command_test(text, False)
  2532. # MS: added this method call so the geometry is updated once the TCL command is executed
  2533. self.plot_all()
  2534. return result
  2535. def exec_command_test(self, text, reraise=True):
  2536. """
  2537. Same as exec_command(...) with additional control over exceptions.
  2538. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2539. :param text: Input command
  2540. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2541. :return: Output from the command
  2542. """
  2543. text = str(text)
  2544. try:
  2545. self.shell.open_proccessing() # Disables input box.
  2546. result = self.tcl.eval(str(text))
  2547. if result != 'None':
  2548. self.shell.append_output(result + '\n')
  2549. except tk.TclError as e:
  2550. # This will display more precise answer if something in TCL shell fails
  2551. result = self.tcl.eval("set errorInfo")
  2552. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2553. self.shell.append_error('ERROR: ' + result + '\n')
  2554. # Show error in console and just return or in test raise exception
  2555. if reraise:
  2556. raise e
  2557. finally:
  2558. self.shell.close_proccessing()
  2559. pass
  2560. return result
  2561. # """
  2562. # Code below is unsused. Saved for later.
  2563. # """
  2564. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2565. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2566. # self.log.debug(parts)
  2567. # try:
  2568. # if parts[0] not in commands:
  2569. # self.shell.append_error("Unknown command\n")
  2570. # return
  2571. #
  2572. # #import inspect
  2573. # #inspect.getargspec(someMethod)
  2574. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2575. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2576. # self.shell.append_error(
  2577. # "Command %s takes %d arguments. %d given.\n" %
  2578. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2579. # )
  2580. # return
  2581. #
  2582. # cmdfcn = commands[parts[0]]["fcn"]
  2583. # cmdconv = commands[parts[0]]["converters"]
  2584. # if len(parts) - 1 > 0:
  2585. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2586. # else:
  2587. # retval = cmdfcn()
  2588. # retfcn = commands[parts[0]]["retfcn"]
  2589. # if retval and retfcn(retval):
  2590. # self.shell.append_output(retfcn(retval) + "\n")
  2591. #
  2592. # except Exception as e:
  2593. # #self.shell.append_error(''.join(traceback.format_exc()))
  2594. # #self.shell.append_error("?\n")
  2595. # self.shell.append_error(str(e) + "\n")
  2596. def info(self, msg):
  2597. """
  2598. Informs the user. Normally on the status bar, optionally
  2599. also on the shell.
  2600. :param msg: Text to write.
  2601. :return: None
  2602. """
  2603. # Type of message in brackets at the beginning of the message.
  2604. match = re.search("\[([^\]]+)\](.*)", msg)
  2605. if match:
  2606. level = match.group(1)
  2607. msg_ = match.group(2)
  2608. self.ui.fcinfo.set_status(str(msg_), level=level)
  2609. if level.lower() == "error":
  2610. self.shell_message(msg, error=True, show=True)
  2611. elif level.lower() == "warning":
  2612. self.shell_message(msg, warning=True, show=True)
  2613. elif level.lower() == "error_notcl":
  2614. self.shell_message(msg, error=True, show=False)
  2615. elif level.lower() == "warning_notcl":
  2616. self.shell_message(msg, warning=True, show=False)
  2617. elif level.lower() == "success":
  2618. self.shell_message(msg, success=True, show=False)
  2619. elif level.lower() == "selected":
  2620. self.shell_message(msg, selected=True, show=False)
  2621. else:
  2622. self.shell_message(msg, show=False)
  2623. else:
  2624. self.ui.fcinfo.set_status(str(msg), level="info")
  2625. # make sure that if the message is to clear the infobar with a space
  2626. # is not printed over and over on the shell
  2627. if msg != '':
  2628. self.shell_message(msg)
  2629. def restore_toolbar_view(self):
  2630. """
  2631. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2632. was saved in the defaults dictionary.
  2633. :return: None
  2634. """
  2635. tb = self.defaults["global_toolbar_view"]
  2636. if tb & 1:
  2637. self.ui.toolbarfile.setVisible(True)
  2638. else:
  2639. self.ui.toolbarfile.setVisible(False)
  2640. if tb & 2:
  2641. self.ui.toolbargeo.setVisible(True)
  2642. else:
  2643. self.ui.toolbargeo.setVisible(False)
  2644. if tb & 4:
  2645. self.ui.toolbarview.setVisible(True)
  2646. else:
  2647. self.ui.toolbarview.setVisible(False)
  2648. if tb & 8:
  2649. self.ui.toolbartools.setVisible(True)
  2650. else:
  2651. self.ui.toolbartools.setVisible(False)
  2652. if tb & 16:
  2653. self.ui.exc_edit_toolbar.setVisible(True)
  2654. else:
  2655. self.ui.exc_edit_toolbar.setVisible(False)
  2656. if tb & 32:
  2657. self.ui.geo_edit_toolbar.setVisible(True)
  2658. else:
  2659. self.ui.geo_edit_toolbar.setVisible(False)
  2660. if tb & 64:
  2661. self.ui.grb_edit_toolbar.setVisible(True)
  2662. else:
  2663. self.ui.grb_edit_toolbar.setVisible(False)
  2664. if tb & 128:
  2665. self.ui.snap_toolbar.setVisible(True)
  2666. else:
  2667. self.ui.snap_toolbar.setVisible(False)
  2668. if tb & 256:
  2669. self.ui.toolbarshell.setVisible(True)
  2670. else:
  2671. self.ui.toolbarshell.setVisible(False)
  2672. def load_defaults(self, filename):
  2673. """
  2674. Loads the aplication's default settings from current_defaults.FlatConfig into
  2675. ``self.defaults``.
  2676. :return: None
  2677. """
  2678. try:
  2679. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2680. options = f.read()
  2681. f.close()
  2682. except IOError:
  2683. self.log.error("Could not load defaults file.")
  2684. self.inform.emit('[ERROR] %s' %
  2685. _("Could not load defaults file."))
  2686. # in case the defaults file can't be loaded, show all toolbars
  2687. self.defaults["global_toolbar_view"] = 511
  2688. return
  2689. try:
  2690. defaults = json.loads(options)
  2691. except:
  2692. # in case the defaults file can't be loaded, show all toolbars
  2693. self.defaults["global_toolbar_view"] = 511
  2694. e = sys.exc_info()[0]
  2695. App.log.error(str(e))
  2696. self.inform.emit('[ERROR] %s' %
  2697. _("Failed to parse defaults file."))
  2698. return
  2699. self.defaults.update(defaults)
  2700. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2701. # restore the toolbar view
  2702. self.restore_toolbar_view()
  2703. def on_import_preferences(self):
  2704. """
  2705. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2706. ``self.defaults``.
  2707. :return: None
  2708. """
  2709. self.report_usage("on_import_preferences")
  2710. App.log.debug("on_import_preferences()")
  2711. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2712. try:
  2713. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2714. directory=self.data_path,
  2715. filter=filter_)
  2716. except TypeError:
  2717. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2718. filter=filter_)
  2719. filename = str(filename)
  2720. if filename == "":
  2721. self.inform.emit('[WARNING_NOTCL] %s' %
  2722. _("FlatCAM preferences import cancelled."))
  2723. else:
  2724. try:
  2725. f = open(filename)
  2726. options = f.read()
  2727. f.close()
  2728. except IOError:
  2729. self.log.error("Could not load defaults file.")
  2730. self.inform.emit('[ERROR_NOTCL] %s' %
  2731. _("Could not load defaults file."))
  2732. return
  2733. try:
  2734. defaults_from_file = json.loads(options)
  2735. except Exception as e:
  2736. e = sys.exc_info()[0]
  2737. App.log.error(str(e))
  2738. self.inform.emit('[ERROR_NOTCL] %s' %
  2739. _("Failed to parse defaults file."))
  2740. return
  2741. self.defaults.update(defaults_from_file)
  2742. self.on_preferences_edited()
  2743. self.inform.emit('[success] %s: %s' %
  2744. (_("Imported Defaults from"), filename))
  2745. def on_export_preferences(self):
  2746. """
  2747. Save the defaults dictionary to a file.
  2748. :return: None
  2749. """
  2750. self.report_usage("on_export_preferences")
  2751. App.log.debug("on_export_preferences()")
  2752. defaults_file_content = None
  2753. self.date = str(datetime.today()).rpartition('.')[0]
  2754. self.date = ''.join(c for c in self.date if c not in ':-')
  2755. self.date = self.date.replace(' ', '_')
  2756. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2757. try:
  2758. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2759. caption=_("Export FlatCAM Preferences"),
  2760. directory=self.data_path + '/preferences_' + self.date,
  2761. filter=filter__
  2762. )
  2763. except TypeError:
  2764. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2765. filter=filter__)
  2766. filename = str(filename)
  2767. defaults_from_file = {}
  2768. if filename == "":
  2769. self.inform.emit('[WARNING_NOTCL] %s' %
  2770. _("FlatCAM preferences export cancelled."))
  2771. return
  2772. else:
  2773. try:
  2774. f = open(filename, 'w')
  2775. defaults_file_content = f.read()
  2776. f.close()
  2777. except PermissionError:
  2778. self.inform.emit('[WARNING] %s' %
  2779. _("Permission denied, saving not possible.\n"
  2780. "Most likely another app is holding the file open and not accessible."))
  2781. return
  2782. except IOError:
  2783. App.log.debug('Creating a new preferences file ...')
  2784. f = open(filename, 'w')
  2785. json.dump({}, f)
  2786. f.close()
  2787. except:
  2788. e = sys.exc_info()[0]
  2789. App.log.error("Could not load defaults file.")
  2790. App.log.error(str(e))
  2791. self.inform.emit('[ERROR_NOTCL] %s' %
  2792. _("Could not load preferences file."))
  2793. return
  2794. try:
  2795. defaults_from_file = json.loads(defaults_file_content)
  2796. except:
  2797. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2798. # Update options
  2799. self.defaults_read_form()
  2800. defaults_from_file.update(self.defaults)
  2801. self.propagate_defaults(silent=True)
  2802. # Save update options
  2803. try:
  2804. f = open(filename, "w")
  2805. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2806. f.close()
  2807. except:
  2808. self.inform.emit('[ERROR_NOTCL] %s' %
  2809. _("Failed to write defaults to file."))
  2810. return
  2811. if self.defaults["global_open_style"] is False:
  2812. self.file_opened.emit("preferences", filename)
  2813. self.file_saved.emit("preferences", filename)
  2814. self.inform.emit('[success] %s: %s' %
  2815. (_("Exported preferences to"), filename))
  2816. def on_preferences_open_folder(self):
  2817. """
  2818. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  2819. :return: None
  2820. """
  2821. self.report_usage("on_preferences_open_folder()")
  2822. if sys.platform == 'win32':
  2823. subprocess.Popen('explorer %s' % self.data_path)
  2824. elif sys.platform == 'darwin':
  2825. os.system('open "%s"' % self.data_path)
  2826. else:
  2827. subprocess.Popen(['xdg-open', self.data_path])
  2828. self.inform.emit('[success] %s' %
  2829. _("FlatCAM Preferences Folder opened."))
  2830. def save_geometry(self, x, y, width, height, notebook_width):
  2831. """
  2832. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2833. launch of the application.
  2834. :param x: X position of the main window
  2835. :param y: Y position of the main window
  2836. :param width: width of the main window
  2837. :param height: height of the main window
  2838. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2839. :return: None
  2840. """
  2841. self.defaults["global_def_win_x"] = x
  2842. self.defaults["global_def_win_y"] = y
  2843. self.defaults["global_def_win_w"] = width
  2844. self.defaults["global_def_win_h"] = height
  2845. self.defaults["global_def_notebook_width"] = notebook_width
  2846. self.save_defaults()
  2847. def message_dialog(self, title, message, kind="info"):
  2848. """
  2849. Builds and show a custom QMessageBox to be used in FlatCAM.
  2850. :param title: title of the QMessageBox
  2851. :param message: message to be displayed
  2852. :param kind: type of QMessageBox; will display a specific icon.
  2853. :return:
  2854. """
  2855. icon = {"info": QtWidgets.QMessageBox.Information,
  2856. "warning": QtWidgets.QMessageBox.Warning,
  2857. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2858. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2859. dlg.setText(message)
  2860. dlg.exec_()
  2861. def register_recent(self, kind, filename):
  2862. """
  2863. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2864. dictionary.
  2865. :param kind: type of file that was opened
  2866. :param filename: the path and file name for the file that was opened
  2867. :return:
  2868. """
  2869. self.log.debug("register_recent()")
  2870. self.log.debug(" %s" % kind)
  2871. self.log.debug(" %s" % filename)
  2872. record = {'kind': str(kind), 'filename': str(filename)}
  2873. if record in self.recent:
  2874. return
  2875. if record in self.recent_projects:
  2876. return
  2877. if record['kind'] == 'project':
  2878. self.recent_projects.insert(0, record)
  2879. else:
  2880. self.recent.insert(0, record)
  2881. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2882. self.recent.pop()
  2883. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2884. self.recent_projects.pop()
  2885. try:
  2886. f = open(self.data_path + '/recent.json', 'w')
  2887. except IOError:
  2888. App.log.error("Failed to open recent items file for writing.")
  2889. self.inform.emit('[ERROR_NOTCL] %s' %
  2890. _('Failed to open recent files file for writing.'))
  2891. return
  2892. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2893. f.close()
  2894. try:
  2895. fp = open(self.data_path + '/recent_projects.json', 'w')
  2896. except IOError:
  2897. App.log.error("Failed to open recent items file for writing.")
  2898. self.inform.emit('[ERROR_NOTCL] %s' %
  2899. _('Failed to open recent projects file for writing.'))
  2900. return
  2901. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2902. fp.close()
  2903. # Re-build the recent items menu
  2904. self.setup_recent_items()
  2905. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2906. """
  2907. Creates a new specialized FlatCAMObj and attaches it to the application,
  2908. this is, updates the GUI accordingly, any other records and plots it.
  2909. This method is thread-safe.
  2910. Notes:
  2911. * If the name is in use, the self.collection will modify it
  2912. when appending it to the collection. There is no need to handle
  2913. name conflicts here.
  2914. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2915. :type kind: str
  2916. :param name: Name for the object.
  2917. :type name: str
  2918. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2919. The function is called with 2 parameters: the new object and the App instance.
  2920. :type initialize: function
  2921. :param active:
  2922. :param fit:
  2923. :param plot: If to plot the resulting object
  2924. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2925. self.colleaction
  2926. :return: None
  2927. :rtype: None
  2928. """
  2929. App.log.debug("new_object()")
  2930. obj_plot = plot
  2931. obj_autoselected = autoselected
  2932. t0 = time.time() # Debug
  2933. # ## Create object
  2934. classdict = {
  2935. "gerber": FlatCAMGerber,
  2936. "excellon": FlatCAMExcellon,
  2937. "cncjob": FlatCAMCNCjob,
  2938. "geometry": FlatCAMGeometry
  2939. }
  2940. App.log.debug("Calling object constructor...")
  2941. obj = classdict[kind](name)
  2942. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2943. # Set options from "Project options" form
  2944. self.options_read_form()
  2945. # IMPORTANT
  2946. # The key names in defaults and options dictionary's are not random:
  2947. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2948. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2949. # the options from project options form into the self.options. After that, below, depending on the type of
  2950. # object that is created, it will strip the name of the object and the underline (if the original key was
  2951. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2952. # "toolchange"
  2953. for option in self.options:
  2954. if option.find(kind + "_") == 0:
  2955. oname = option[len(kind) + 1:]
  2956. obj.options[oname] = self.options[option]
  2957. obj.isHovering = False
  2958. obj.notHovering = True
  2959. # Initialize as per user request
  2960. # User must take care to implement initialize
  2961. # in a thread-safe way as is is likely that we
  2962. # have been invoked in a separate thread.
  2963. t1 = time.time()
  2964. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2965. try:
  2966. return_value = initialize(obj, self)
  2967. except Exception as e:
  2968. msg = '[ERROR_NOTCL] %s' % \
  2969. _("An internal error has ocurred. See shell.\n")
  2970. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2971. msg += traceback.format_exc()
  2972. self.inform.emit(msg)
  2973. # if str(e) == "Empty Geometry":
  2974. # self.inform.emit("[ERROR_NOTCL] )
  2975. # else:
  2976. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2977. return "fail"
  2978. t2 = time.time()
  2979. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2980. if return_value == 'fail':
  2981. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2982. return "fail"
  2983. # Check units and convert if necessary
  2984. # This condition CAN be true because initialize() can change obj.units
  2985. if self.options["units"].upper() != obj.units.upper():
  2986. self.inform.emit('%s: %s' %
  2987. (_("Converting units to "), self.options["units"]))
  2988. obj.convert_units(self.options["units"])
  2989. t3 = time.time()
  2990. self.log.debug("%f seconds converting units." % (t3 - t2))
  2991. # Create the bounding box for the object and then add the results to the obj.options
  2992. try:
  2993. xmin, ymin, xmax, ymax = obj.bounds()
  2994. obj.options['xmin'] = xmin
  2995. obj.options['ymin'] = ymin
  2996. obj.options['xmax'] = xmax
  2997. obj.options['ymax'] = ymax
  2998. except Exception as e:
  2999. log.warning("The object has no bounds properties. %s" % str(e))
  3000. return "fail"
  3001. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3002. # Move the object to the main thread and let the app know that it is available.
  3003. obj.moveToThread(self.main_thread)
  3004. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3005. return obj
  3006. def new_excellon_object(self):
  3007. """
  3008. Creates a new, blank Excellon object.
  3009. :return: None
  3010. """
  3011. self.report_usage("new_excellon_object()")
  3012. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3013. def new_geometry_object(self):
  3014. """
  3015. Creates a new, blank and single-tool Geometry object.
  3016. :return: None
  3017. """
  3018. self.report_usage("new_geometry_object()")
  3019. def initialize(obj, self):
  3020. obj.multitool = False
  3021. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3022. def new_gerber_object(self):
  3023. """
  3024. Creates a new, blank Gerber object.
  3025. :return: None
  3026. """
  3027. self.report_usage("new_gerber_object()")
  3028. def initialize(grb_obj, self):
  3029. grb_obj.multitool = False
  3030. grb_obj.source_file = []
  3031. grb_obj.multigeo = False
  3032. grb_obj.follow = False
  3033. grb_obj.apertures = {}
  3034. grb_obj.solid_geometry = []
  3035. try:
  3036. grb_obj.options['xmin'] = 0
  3037. grb_obj.options['ymin'] = 0
  3038. grb_obj.options['xmax'] = 0
  3039. grb_obj.options['ymax'] = 0
  3040. except KeyError:
  3041. pass
  3042. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3043. def on_object_created(self, obj, plot, autoselect):
  3044. """
  3045. Event callback for object creation.
  3046. It will add the new object to the collection. After that it will plot the object in a threaded way
  3047. :param obj: The newly created FlatCAM object.
  3048. :param plot: if the newly create object t obe plotted
  3049. :param autoselect: if the newly created object to be autoselected after creation
  3050. :return: None
  3051. """
  3052. t0 = time.time() # DEBUG
  3053. self.log.debug("on_object_created()")
  3054. # The Collection might change the name if there is a collision
  3055. self.collection.append(obj)
  3056. # after adding the object to the collection always update the list of objects that are in the collection
  3057. self.all_objects_list = self.collection.get_list()
  3058. # self.inform.emit('[selected] %s created & selected: %s' %
  3059. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3060. if obj.kind == 'gerber':
  3061. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3062. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3063. elif obj.kind == 'excellon':
  3064. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3065. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3066. elif obj.kind == 'cncjob':
  3067. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3068. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3069. elif obj.kind == 'geometry':
  3070. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3071. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3072. # update the SHELL auto-completer model with the name of the new object
  3073. self.myKeywords.append(obj.options['name'])
  3074. self.shell._edit.set_model_data(self.myKeywords)
  3075. self.ui.code_editor.set_model_data(self.myKeywords)
  3076. if autoselect:
  3077. # select the just opened object but deselect the previous ones
  3078. self.collection.set_all_inactive()
  3079. self.collection.set_active(obj.options["name"])
  3080. else:
  3081. self.collection.set_all_inactive()
  3082. # here it is done the object plotting
  3083. def worker_task(t_obj):
  3084. with self.proc_container.new(_("Plotting")):
  3085. if isinstance(t_obj, FlatCAMCNCjob):
  3086. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3087. else:
  3088. t_obj.plot()
  3089. t1 = time.time() # DEBUG
  3090. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3091. self.object_plotted.emit(t_obj)
  3092. # Send to worker
  3093. # self.worker.add_task(worker_task, [self])
  3094. if plot is True:
  3095. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3096. def on_object_changed(self, obj):
  3097. """
  3098. Called whenever the geometry of the object was changed in some way.
  3099. This require the update of it's bounding values so it can be the selected on canvas.
  3100. Update the bounding box data from obj.options
  3101. :param obj: the object that was changed
  3102. :return: None
  3103. """
  3104. xmin, ymin, xmax, ymax = obj.bounds()
  3105. obj.options['xmin'] = xmin
  3106. obj.options['ymin'] = ymin
  3107. obj.options['xmax'] = xmax
  3108. obj.options['ymax'] = ymax
  3109. log.debug("Object changed, updating the bounding box data on self.options")
  3110. # delete the old selection shape
  3111. self.delete_selection_shape()
  3112. self.should_we_save = True
  3113. def on_object_plotted(self, obj):
  3114. """
  3115. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3116. :param obj: object to be fit into view
  3117. :return: None
  3118. """
  3119. self.on_zoom_fit(None)
  3120. def options_read_form(self):
  3121. """
  3122. Same as it's equivalent from the defaults.
  3123. self.options use to store the preferences per project. No longer used.
  3124. :return: None
  3125. """
  3126. for option in self.options_form_fields:
  3127. self.options[option] = self.options_form_fields[option].get_value()
  3128. def options_write_form(self):
  3129. """
  3130. Same as it's equivalent from the defaults.
  3131. self.options use to store the preferences per project. No longer used.
  3132. :return: None
  3133. """
  3134. for option in self.options:
  3135. self.options_write_form_field(option)
  3136. def options_write_form_field(self, field):
  3137. """
  3138. Same as it's equivalent from the defaults.
  3139. self.options use to store the preferences per project. No longer used.
  3140. :return: None
  3141. """
  3142. try:
  3143. self.options_form_fields[field].set_value(self.options[field])
  3144. except KeyError:
  3145. # Changed from error to debug. This allows to have data stored
  3146. # which is not user-editable.
  3147. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3148. pass
  3149. def on_about(self):
  3150. """
  3151. Displays the "about" dialog found in the Menu --> Help.
  3152. :return: None
  3153. """
  3154. self.report_usage("on_about")
  3155. version = self.version
  3156. version_date = self.version_date
  3157. beta = self.beta
  3158. class AboutDialog(QtWidgets.QDialog):
  3159. def __init__(self, parent=None):
  3160. QtWidgets.QDialog.__init__(self, parent)
  3161. # Icon and title
  3162. self.setWindowIcon(parent.app_icon)
  3163. self.setWindowTitle("FlatCAM")
  3164. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3165. # self.setStyleSheet(
  3166. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3167. # "background-attachment: fixed"
  3168. # )
  3169. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3170. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3171. # palette = QtGui.QPalette()
  3172. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3173. # self.setPalette(palette)
  3174. layout1 = QtWidgets.QVBoxLayout()
  3175. self.setLayout(layout1)
  3176. layout2 = QtWidgets.QHBoxLayout()
  3177. layout1.addLayout(layout2)
  3178. logo = QtWidgets.QLabel()
  3179. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3180. layout2.addWidget(logo, stretch=0)
  3181. title = QtWidgets.QLabel(
  3182. _(
  3183. "<font size=8><B>FlatCAM</B></font><BR>"
  3184. "Version {version} {beta} ({date}) - {arch} <BR>"
  3185. "<BR>"
  3186. "2D Computer-Aided Printed Circuit Board<BR>"
  3187. "Manufacturing.<BR>"
  3188. "<BR>"
  3189. "<B> License: </B><BR>"
  3190. "Licensed under MIT license (2014 - 2019)"
  3191. "<BR>"
  3192. "by (c)Juan Pablo Caram <BR>"
  3193. "<BR>"
  3194. "<B> Programmers:</B><BR>"
  3195. "Denis Hayrullin<BR>"
  3196. "Kamil Sopko<BR>"
  3197. "Marius Stanciu<BR>"
  3198. "Matthieu Berthomé<BR>"
  3199. "and many others found "
  3200. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  3201. "<BR>"
  3202. "<B>Development</B> is done "
  3203. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  3204. "<b>DOWNLOAD</B> area "
  3205. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  3206. ""
  3207. ).format(version=version,
  3208. beta=('BETA' if beta else ''),
  3209. date=version_date,
  3210. arch=platform.architecture()[0])
  3211. )
  3212. title.setOpenExternalLinks(True)
  3213. layout2.addWidget(title, stretch=1)
  3214. layout3 = QtWidgets.QHBoxLayout()
  3215. layout1.addLayout(layout3)
  3216. layout3.addStretch()
  3217. okbtn = QtWidgets.QPushButton(_("Close"))
  3218. layout3.addWidget(okbtn)
  3219. okbtn.clicked.connect(self.accept)
  3220. AboutDialog(self.ui).exec_()
  3221. def on_file_savedefaults(self):
  3222. """
  3223. Callback for menu item File->Save Defaults. Saves application default options
  3224. ``self.defaults`` to current_defaults.FlatConfig.
  3225. :return: None
  3226. """
  3227. self.save_defaults()
  3228. # def on_app_exit(self):
  3229. # self.report_usage("on_app_exit()")
  3230. #
  3231. # if self.collection.get_list():
  3232. # msgbox = QtWidgets.QMessageBox()
  3233. # # msgbox.setText("<B>Save changes ...</B>")
  3234. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3235. # "\n"
  3236. # "Do you want to Save the project?")
  3237. # msgbox.setWindowTitle("Save changes")
  3238. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3239. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3240. # QtWidgets.QMessageBox.Cancel)
  3241. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3242. #
  3243. # response = msgbox.exec_()
  3244. #
  3245. # if response == QtWidgets.QMessageBox.Yes:
  3246. # self.on_file_saveprojectas(thread=False)
  3247. # elif response == QtWidgets.QMessageBox.Cancel:
  3248. # return
  3249. # self.save_defaults()
  3250. # else:
  3251. # self.save_defaults()
  3252. # log.debug("Application defaults saved ... Exit event.")
  3253. # QtWidgets.qApp.quit()
  3254. def save_defaults(self, silent=False, data_path=None):
  3255. """
  3256. Saves application default options
  3257. ``self.defaults`` to current_defaults.FlatConfig file.
  3258. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3259. used at the next launch of the application.
  3260. :param silent: whether to display a message in status bar or not; boolean
  3261. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3262. When the application is portable it should be a mobile location.
  3263. :return: None
  3264. """
  3265. self.report_usage("save_defaults")
  3266. if data_path is None:
  3267. data_path = self.data_path
  3268. # Read options from file
  3269. try:
  3270. f = open(data_path + "/current_defaults.FlatConfig")
  3271. defaults_file_content = f.read()
  3272. f.close()
  3273. except:
  3274. e = sys.exc_info()[0]
  3275. App.log.error("Could not load defaults file.")
  3276. App.log.error(str(e))
  3277. self.inform.emit('[ERROR_NOTCL] %s' %
  3278. _("Could not load defaults file."))
  3279. return
  3280. try:
  3281. defaults = json.loads(defaults_file_content)
  3282. except:
  3283. e = sys.exc_info()[0]
  3284. App.log.error("Failed to parse defaults file.")
  3285. App.log.error(str(e))
  3286. self.inform.emit('[ERROR_NOTCL] %s' %
  3287. _("Failed to parse defaults file."))
  3288. return
  3289. # Update options
  3290. self.defaults_read_form()
  3291. defaults.update(self.defaults)
  3292. self.propagate_defaults(silent=True)
  3293. # Save the toolbar view
  3294. tb_status = 0
  3295. if self.ui.toolbarfile.isVisible():
  3296. tb_status += 1
  3297. if self.ui.toolbargeo.isVisible():
  3298. tb_status += 2
  3299. if self.ui.toolbarview.isVisible():
  3300. tb_status += 4
  3301. if self.ui.toolbartools.isVisible():
  3302. tb_status += 8
  3303. if self.ui.exc_edit_toolbar.isVisible():
  3304. tb_status += 16
  3305. if self.ui.geo_edit_toolbar.isVisible():
  3306. tb_status += 32
  3307. if self.ui.grb_edit_toolbar.isVisible():
  3308. tb_status += 64
  3309. if self.ui.snap_toolbar.isVisible():
  3310. tb_status += 128
  3311. if self.ui.toolbarshell.isVisible():
  3312. tb_status += 256
  3313. self.defaults["global_toolbar_view"] = tb_status
  3314. # Save update options
  3315. try:
  3316. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3317. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3318. f.close()
  3319. except:
  3320. self.inform.emit('[ERROR_NOTCL] %s' %
  3321. _("Failed to write defaults to file."))
  3322. return
  3323. if not silent:
  3324. self.inform.emit('[success] %s' %
  3325. _("Preferences saved."))
  3326. def save_factory_defaults(self, silent=False, data_path=None):
  3327. """
  3328. Saves application factory default options
  3329. ``self.defaults`` to factory_defaults.FlatConfig.
  3330. It's a one time job done just after the first install.
  3331. :param silent: whether to display a message in status bar or not; boolean
  3332. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3333. When the application is portable it should be a mobile location.
  3334. :return: None
  3335. """
  3336. self.report_usage("save_factory_defaults")
  3337. if data_path is None:
  3338. data_path = self.data_path
  3339. # Read options from file
  3340. try:
  3341. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3342. factory_defaults_file_content = f_f_def.read()
  3343. f_f_def.close()
  3344. except:
  3345. e = sys.exc_info()[0]
  3346. App.log.error("Could not load factory defaults file.")
  3347. App.log.error(str(e))
  3348. self.inform.emit('[ERROR_NOTCL] %s' %
  3349. _("Could not load factory defaults file."))
  3350. return
  3351. try:
  3352. factory_defaults = json.loads(factory_defaults_file_content)
  3353. except:
  3354. e = sys.exc_info()[0]
  3355. App.log.error("Failed to parse factory defaults file.")
  3356. App.log.error(str(e))
  3357. self.inform.emit('[ERROR_NOTCL] %s' %
  3358. _("Failed to parse factory defaults file."))
  3359. return
  3360. # Update options
  3361. self.defaults_read_form()
  3362. factory_defaults.update(self.defaults)
  3363. self.propagate_defaults(silent=True)
  3364. # Save update options
  3365. try:
  3366. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3367. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3368. f_f_def_s.close()
  3369. except:
  3370. self.inform.emit('[ERROR_NOTCL] %s' %
  3371. _("Failed to write factory defaults to file."))
  3372. return
  3373. if silent is False:
  3374. self.inform.emit(_("Factory defaults saved."))
  3375. def final_save(self):
  3376. """
  3377. Callback for doing a preferences save to file whenever the application is about to quit.
  3378. If the project has changes, it will ask the user to save the project.
  3379. :return: None
  3380. """
  3381. if self.save_in_progress:
  3382. self.inform.emit('[WARNING_NOTCL] %s' %
  3383. _("Application is saving the project. Please wait ..."))
  3384. return
  3385. if self.should_we_save and self.collection.get_list():
  3386. msgbox = QtWidgets.QMessageBox()
  3387. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3388. "\n"
  3389. "Do you want to Save the project?"))
  3390. msgbox.setWindowTitle(_("Save changes"))
  3391. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3392. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3393. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3394. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3395. msgbox.setDefaultButton(bt_yes)
  3396. msgbox.exec_()
  3397. response = msgbox.clickedButton()
  3398. if response == bt_yes:
  3399. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3400. elif response == bt_no:
  3401. self.quit_application()
  3402. elif response == bt_cancel:
  3403. return
  3404. else:
  3405. self.quit_application()
  3406. def quit_application(self):
  3407. """
  3408. Called (as a pyslot or not) when the application is quit.
  3409. :return: None
  3410. """
  3411. self.save_defaults()
  3412. log.debug("App.final_save() --> App Defaults saved.")
  3413. # save toolbar state to file
  3414. settings = QSettings("Open Source", "FlatCAM")
  3415. settings.setValue('saved_gui_state', self.ui.saveState())
  3416. settings.setValue('maximized_gui', self.ui.isMaximized())
  3417. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3418. settings.setValue('notebook_font_size',
  3419. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3420. settings.setValue('axis_font_size',
  3421. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3422. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3423. # This will write the setting to the platform specific storage.
  3424. del settings
  3425. log.debug("App.final_save() --> App UI state saved.")
  3426. QtWidgets.qApp.quit()
  3427. def on_portable_checked(self, state):
  3428. """
  3429. Callback called when the checkbox in Preferences GUI is checked.
  3430. It will set the application as portable by creating the preferences and recent files in the
  3431. 'config' folder found in the FlatCAM installation folder.
  3432. :param state: boolean, the state of the checkbox when clicked/checked
  3433. :return:
  3434. """
  3435. line_no = 0
  3436. data = None
  3437. if sys.platform != 'win32':
  3438. # this won't work in Linux or MacOS
  3439. return
  3440. # test if the app was frozen and choose the path for the configuration file
  3441. if getattr(sys, "frozen", False) is True:
  3442. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3443. else:
  3444. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3445. config_file = current_data_path + '\\configuration.txt'
  3446. try:
  3447. with open(config_file, 'r') as f:
  3448. try:
  3449. data = f.readlines()
  3450. except Exception as e:
  3451. log.debug('App.__init__() -->%s' % str(e))
  3452. return
  3453. except FileNotFoundError:
  3454. pass
  3455. for line in data:
  3456. line = line.strip('\n')
  3457. param = str(line).rpartition('=')
  3458. if param[0] == 'portable':
  3459. break
  3460. line_no += 1
  3461. if state:
  3462. data[line_no] = 'portable=True\n'
  3463. # create the new defauults files
  3464. # create current_defaults.FlatConfig file if there is none
  3465. try:
  3466. f = open(current_data_path + '/current_defaults.FlatConfig')
  3467. f.close()
  3468. except IOError:
  3469. App.log.debug('Creating empty current_defaults.FlatConfig')
  3470. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3471. json.dump({}, f)
  3472. f.close()
  3473. # create factory_defaults.FlatConfig file if there is none
  3474. try:
  3475. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3476. f.close()
  3477. except IOError:
  3478. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3479. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3480. json.dump({}, f)
  3481. f.close()
  3482. try:
  3483. f = open(current_data_path + '/recent.json')
  3484. f.close()
  3485. except IOError:
  3486. App.log.debug('Creating empty recent.json')
  3487. f = open(current_data_path + '/recent.json', 'w')
  3488. json.dump([], f)
  3489. f.close()
  3490. try:
  3491. fp = open(current_data_path + '/recent_projects.json')
  3492. fp.close()
  3493. except IOError:
  3494. App.log.debug('Creating empty recent_projects.json')
  3495. fp = open(current_data_path + '/recent_projects.json', 'w')
  3496. json.dump([], fp)
  3497. fp.close()
  3498. # save the current defaults to the new defaults file
  3499. self.save_defaults(silent=True, data_path=current_data_path)
  3500. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3501. else:
  3502. data[line_no] = 'portable=False\n'
  3503. with open(config_file, 'w') as f:
  3504. f.writelines(data)
  3505. def on_toggle_shell(self):
  3506. """
  3507. Toggle shell: if is visible close it, if it is closed then open it
  3508. :return:
  3509. """
  3510. self.report_usage("on_toggle_shell()")
  3511. if self.ui.shell_dock.isVisible():
  3512. self.ui.shell_dock.hide()
  3513. else:
  3514. self.ui.shell_dock.show()
  3515. def on_register_files(self, obj_type=None):
  3516. """
  3517. Called whenever there is a need to register file extensions with FlatCAM.
  3518. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3519. :param obj_type: the type of object to be register for.
  3520. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3521. :return: None
  3522. """
  3523. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3524. new_reg_path = 'Software\\Classes\\'
  3525. # find if the current user is admin
  3526. try:
  3527. is_admin = os.getuid() == 0
  3528. except AttributeError:
  3529. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3530. if is_admin is True:
  3531. root_path = winreg.HKEY_CLASSES_ROOT
  3532. else:
  3533. root_path = winreg.HKEY_CURRENT_USER
  3534. # create the keys
  3535. def set_reg(name, root_path, new_reg_path, value):
  3536. try:
  3537. winreg.CreateKey(root_path, new_reg_path)
  3538. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3539. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3540. return True
  3541. except WindowsError:
  3542. return False
  3543. # delete key in registry
  3544. def delete_reg(root_path, reg_path, key_to_del):
  3545. key_to_del_path = reg_path + key_to_del
  3546. try:
  3547. winreg.DeleteKey(root_path, key_to_del_path)
  3548. return True
  3549. except WindowsError:
  3550. return False
  3551. if obj_type is None or obj_type == 'excellon':
  3552. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3553. exc_list = [x for x in exc_list if x != '']
  3554. # register all keys in the Preferences window
  3555. for ext in exc_list:
  3556. new_k = new_reg_path + ext
  3557. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3558. # and unregister those that are no longer in the Preferences windows but are in the file
  3559. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3560. if ext not in exc_list:
  3561. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3562. # now write the updated extensions to the self.defaults
  3563. new_ext = ''
  3564. for ext in exc_list:
  3565. new_ext = new_ext + ext + ', '
  3566. self.defaults["fa_excellon"] = new_ext
  3567. self.inform.emit(_("[success] Selected Excellon file extensions registered with FlatCAM."))
  3568. if obj_type is None or obj_type == 'gcode':
  3569. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3570. gco_list = [x for x in gco_list if x != '']
  3571. # register all keys in the Preferences window
  3572. for ext in gco_list:
  3573. new_k = new_reg_path + ext
  3574. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3575. # and unregister those that are no longer in the Preferences windows but are in the file
  3576. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3577. if ext not in gco_list:
  3578. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3579. # now write the updated extensions to the self.defaults
  3580. new_ext = ''
  3581. for ext in gco_list:
  3582. new_ext = new_ext + ext + ', '
  3583. self.defaults["fa_gcode"] = new_ext
  3584. self.inform.emit('[success] %s' %
  3585. _("Selected GCode file extensions registered with FlatCAM."))
  3586. if obj_type is None or obj_type == 'gerber':
  3587. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3588. grb_list = [x for x in grb_list if x != '']
  3589. # register all keys in the Preferences window
  3590. for ext in grb_list:
  3591. new_k = new_reg_path + ext
  3592. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3593. # and unregister those that are no longer in the Preferences windows but are in the file
  3594. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3595. if ext not in grb_list:
  3596. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3597. # now write the updated extensions to the self.defaults
  3598. new_ext = ''
  3599. for ext in grb_list:
  3600. new_ext = new_ext + ext + ', '
  3601. self.defaults["fa_gerber"] = new_ext
  3602. self.inform.emit('[success] %s' %
  3603. _("Selected Gerber file extensions registered with FlatCAM."))
  3604. def on_edit_join(self, name=None):
  3605. """
  3606. Callback for Edit->Join. Joins the selected geometry objects into
  3607. a new one.
  3608. :return: None
  3609. """
  3610. self.report_usage("on_edit_join()")
  3611. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3612. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3613. tooldias = []
  3614. geo_type_list = set()
  3615. objs = self.collection.get_selected()
  3616. for obj in objs:
  3617. geo_type_list.add(obj.multigeo)
  3618. # if len(geo_type_list) == 1 means that all list elements are the same
  3619. if len(geo_type_list) != 1:
  3620. self.inform.emit('[ERROR] %s' %
  3621. _("Failed join. The Geometry objects are of different types.\n"
  3622. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3623. "convert from one to another and retry joining \n"
  3624. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3625. "the result may not be what was expected. \n"
  3626. "Check the generated GCODE."))
  3627. return
  3628. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3629. if True in geo_type_list:
  3630. def initialize(obj, app):
  3631. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3632. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3633. for v in obj.tools.values():
  3634. v['data']['name'] = obj_name_multi
  3635. self.new_object("geometry", obj_name_multi, initialize)
  3636. else:
  3637. def initialize(obj, app):
  3638. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3639. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3640. for v in obj.tools.values():
  3641. v['data']['name'] = obj_name_single
  3642. self.new_object("geometry", obj_name_single, initialize)
  3643. self.should_we_save = True
  3644. def on_edit_join_exc(self):
  3645. """
  3646. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3647. a new Excellon.
  3648. :return: None
  3649. """
  3650. self.report_usage("on_edit_join_exc()")
  3651. objs = self.collection.get_selected()
  3652. for obj in objs:
  3653. if not isinstance(obj, FlatCAMExcellon):
  3654. self.inform.emit('[ERROR_NOTCL] %s' %
  3655. _("Failed. Excellon joining works only on Excellon objects."))
  3656. return
  3657. def initialize(obj, app):
  3658. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3659. self.new_object("excellon", 'Combo_Excellon', initialize)
  3660. self.should_we_save = True
  3661. def on_edit_join_grb(self):
  3662. """
  3663. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3664. a new Gerber object.
  3665. :return: None
  3666. """
  3667. self.report_usage("on_edit_join_grb()")
  3668. objs = self.collection.get_selected()
  3669. for obj in objs:
  3670. if not isinstance(obj, FlatCAMGerber):
  3671. self.inform.emit('[ERROR_NOTCL] %s' %
  3672. _("Failed. Gerber joining works only on Gerber objects."))
  3673. return
  3674. def initialize(obj, app):
  3675. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3676. self.new_object("gerber", 'Combo_Gerber', initialize)
  3677. self.should_we_save = True
  3678. def on_convert_singlegeo_to_multigeo(self):
  3679. """
  3680. Called for converting a Geometry object from single-geo to multi-geo.
  3681. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3682. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3683. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3684. the solid-geometry of that tool.
  3685. :return: None
  3686. """
  3687. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3688. obj = self.collection.get_active()
  3689. if obj is None:
  3690. self.inform.emit('[ERROR_NOTCL] %s' %
  3691. _("Failed. Select a Geometry Object and try again."))
  3692. return
  3693. if not isinstance(obj, FlatCAMGeometry):
  3694. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3695. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3696. return
  3697. obj.multigeo = True
  3698. for tooluid, dict_value in obj.tools.items():
  3699. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3700. if not isinstance(obj.solid_geometry, list):
  3701. obj.solid_geometry = [obj.solid_geometry]
  3702. obj.solid_geometry[:] = []
  3703. obj.plot()
  3704. self.should_we_save = True
  3705. self.inform.emit('[success] %s' %
  3706. _("A Geometry object was converted to MultiGeo type."))
  3707. def on_convert_multigeo_to_singlegeo(self):
  3708. """
  3709. Called for converting a Geometry object from multi-geo to single-geo.
  3710. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3711. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3712. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3713. the solid-geometry of that tool.
  3714. :return: None
  3715. """
  3716. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3717. obj = self.collection.get_active()
  3718. if obj is None:
  3719. self.inform.emit('[ERROR_NOTCL] %s' %
  3720. _("Failed. Select a Geometry Object and try again."))
  3721. return
  3722. if not isinstance(obj, FlatCAMGeometry):
  3723. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3724. (_("Expected a FlatCAMGeometry, got %s"), type(obj)))
  3725. return
  3726. obj.multigeo = False
  3727. total_solid_geometry = []
  3728. for tooluid, dict_value in obj.tools.items():
  3729. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3730. # clear the original geometry
  3731. dict_value['solid_geometry'][:] = []
  3732. obj.solid_geometry = deepcopy(total_solid_geometry)
  3733. obj.plot()
  3734. self.should_we_save = True
  3735. self.inform.emit('[success] %s' %
  3736. _("A Geometry object was converted to SingleGeo type."))
  3737. def on_options_dict_change(self, field):
  3738. """
  3739. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  3740. current project. This feature is no longer used.
  3741. :param field:
  3742. :return:
  3743. """
  3744. self.options_write_form_field(field)
  3745. if field == "units":
  3746. self.set_screen_units(self.options['units'])
  3747. def on_defaults_dict_change(self, field):
  3748. """
  3749. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3750. Edit -> Preferences tab window.
  3751. :param field: the key of the self.defaults dictionary that was changed.
  3752. :return: None
  3753. """
  3754. self.defaults_write_form_field(field)
  3755. if field == "units":
  3756. self.set_screen_units(self.defaults['units'])
  3757. def set_screen_units(self, units):
  3758. """
  3759. Set the FlatCAM units on the status bar.
  3760. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3761. :return: None
  3762. """
  3763. self.ui.units_label.setText("[" + units.lower() + "]")
  3764. def on_toggle_units(self, no_pref=False):
  3765. """
  3766. Callback for the Units radio-button change in the Preferences tab.
  3767. Changes the application's default units adn for the project too.
  3768. If changing the project's units, the change propagates to all of
  3769. the objects in the project.
  3770. :return: None
  3771. """
  3772. self.report_usage("on_toggle_units")
  3773. if self.toggle_units_ignore:
  3774. return
  3775. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3776. # If option is the same, then ignore
  3777. if new_units == self.defaults["units"].upper():
  3778. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3779. return
  3780. # Options to scale
  3781. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3782. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3783. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3784. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3785. "excellon_z_pdepth",
  3786. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3787. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3788. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3789. "geometry_feedrate_probe",
  3790. 'cncjob_tooldia',
  3791. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3792. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  3793. "tools_2sided_drilldia", "tools_film_boundary",
  3794. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3795. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3796. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3797. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3798. "tools_transform_offset_y",
  3799. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3800. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3801. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3802. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3803. 'global_gridx', 'global_gridy', 'global_snap_max']
  3804. def scale_options(sfactor):
  3805. for dim in dimensions:
  3806. if dim == 'excellon_toolchangexy':
  3807. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3808. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3809. coords_xy[0] *= sfactor
  3810. coords_xy[1] *= sfactor
  3811. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3812. elif dim == 'geometry_toolchangexy':
  3813. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3814. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3815. coords_xy[0] *= sfactor
  3816. coords_xy[1] *= sfactor
  3817. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3818. elif dim == 'geometry_cnctooldia':
  3819. tools_diameters = []
  3820. try:
  3821. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3822. tools_diameters = [eval(a) for a in tools_string if a != '']
  3823. except Exception as e:
  3824. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3825. self.options['geometry_cnctooldia'] = ''
  3826. for t in range(len(tools_diameters)):
  3827. tools_diameters[t] *= sfactor
  3828. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3829. elif dim == 'tools_ncctools':
  3830. ncctools = []
  3831. try:
  3832. tools_string = self.defaults["tools_ncctools"].split(",")
  3833. ncctools = [eval(a) for a in tools_string if a != '']
  3834. except Exception as e:
  3835. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3836. self.options['tools_ncctools'] = ''
  3837. for t in range(len(ncctools)):
  3838. ncctools[t] *= sfactor
  3839. self.options['tools_ncctools'] += "%f," % ncctools[t]
  3840. elif dim == 'tools_solderpaste_tools':
  3841. sptools = []
  3842. try:
  3843. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3844. sptools = [eval(a) for a in tools_string if a != '']
  3845. except Exception as e:
  3846. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3847. self.options['tools_solderpaste_tools'] = ""
  3848. for t in range(len(sptools)):
  3849. sptools[t] *= sfactor
  3850. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  3851. elif dim == 'tools_solderpaste_xy_toolchange':
  3852. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3853. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3854. sp_coords[0] *= sfactor
  3855. sp_coords[1] *= sfactor
  3856. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3857. elif dim == 'global_gridx' or dim == 'global_gridy':
  3858. if new_units == 'IN':
  3859. val = 0.1
  3860. try:
  3861. val = float(self.defaults[dim]) * sfactor
  3862. except Exception as e:
  3863. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3864. self.options[dim] = float('%.6f' % val)
  3865. else:
  3866. val = 0.1
  3867. try:
  3868. val = float(self.defaults[dim]) * sfactor
  3869. except Exception as e:
  3870. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3871. self.options[dim] = float('%.4f' % val)
  3872. else:
  3873. val = 0.1
  3874. try:
  3875. val = float(self.options[dim]) * sfactor
  3876. except Exception as e:
  3877. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3878. self.options[dim] = val
  3879. def scale_defaults(sfactor):
  3880. for dim in dimensions:
  3881. if dim == 'excellon_toolchangexy':
  3882. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3883. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3884. coords_xy[0] *= sfactor
  3885. coords_xy[1] *= sfactor
  3886. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3887. elif dim == 'geometry_toolchangexy':
  3888. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3889. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3890. coords_xy[0] *= sfactor
  3891. coords_xy[1] *= sfactor
  3892. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3893. elif dim == 'geometry_cnctooldia':
  3894. tools_diameters = []
  3895. try:
  3896. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3897. tools_diameters = [eval(a) for a in tools_string if a != '']
  3898. except Exception as e:
  3899. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3900. self.defaults['geometry_cnctooldia'] = ''
  3901. for t in range(len(tools_diameters)):
  3902. tools_diameters[t] *= sfactor
  3903. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  3904. elif dim == 'tools_ncctools':
  3905. ncctools = []
  3906. try:
  3907. tools_string = self.defaults["tools_ncctools"].split(",")
  3908. ncctools = [eval(a) for a in tools_string if a != '']
  3909. except Exception as e:
  3910. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3911. self.defaults['tools_ncctools'] = ''
  3912. for t in range(len(ncctools)):
  3913. ncctools[t] *= sfactor
  3914. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  3915. elif dim == 'tools_solderpaste_tools':
  3916. sptools = []
  3917. try:
  3918. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3919. sptools = [eval(a) for a in tools_string if a != '']
  3920. except Exception as e:
  3921. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3922. self.defaults['tools_solderpaste_tools'] = ""
  3923. for t in range(len(sptools)):
  3924. sptools[t] *= sfactor
  3925. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  3926. elif dim == 'tools_solderpaste_xy_toolchange':
  3927. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3928. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3929. sp_coords[0] *= sfactor
  3930. sp_coords[1] *= sfactor
  3931. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3932. elif dim == 'global_gridx' or dim == 'global_gridy':
  3933. if new_units == 'IN':
  3934. val = 0.1
  3935. try:
  3936. val = float(self.defaults[dim]) * sfactor
  3937. except Exception as e:
  3938. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3939. self.defaults[dim] = float('%.6f' % val)
  3940. else:
  3941. val = 0.1
  3942. try:
  3943. val = float(self.defaults[dim]) * sfactor
  3944. except Exception as e:
  3945. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3946. self.defaults[dim] = float('%.4f' % val)
  3947. else:
  3948. val = 0.1
  3949. try:
  3950. val = float(self.defaults[dim]) * sfactor
  3951. except Exception as e:
  3952. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3953. self.defaults[dim] = val
  3954. # The scaling factor depending on choice of units.
  3955. factor = 1/25.4
  3956. if new_units == 'MM':
  3957. factor = 25.4
  3958. # Changing project units. Warn user.
  3959. msgbox = QtWidgets.QMessageBox()
  3960. msgbox.setWindowTitle(_("Toggle Units"))
  3961. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3962. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3963. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  3964. "properties of all objects to be scaled accordingly.\nContinue?"))
  3965. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3966. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3967. msgbox.setDefaultButton(bt_ok)
  3968. msgbox.exec_()
  3969. response = msgbox.clickedButton()
  3970. if response == bt_ok:
  3971. if no_pref is False:
  3972. self.options_read_form()
  3973. scale_options(factor)
  3974. self.options_write_form()
  3975. self.defaults_read_form()
  3976. scale_defaults(factor)
  3977. self.defaults_write_form(fl_units=new_units)
  3978. # save the defaults to file, some may assume that the conversion is enough and it's not
  3979. self.on_save_button()
  3980. self.should_we_save = True
  3981. # change this only if the workspace is active
  3982. if self.defaults['global_workspace'] is True:
  3983. self.plotcanvas.draw_workspace()
  3984. # adjust the grid values on the main toolbar
  3985. dec = 6 if new_units == 'IN'else 4
  3986. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  3987. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  3988. if not self.ui.grid_gap_link_cb.isChecked():
  3989. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  3990. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  3991. for obj in self.collection.get_list():
  3992. obj.convert_units(new_units)
  3993. # make that the properties stored in the object are also updated
  3994. self.object_changed.emit(obj)
  3995. obj.build_ui()
  3996. current = self.collection.get_active()
  3997. if current is not None:
  3998. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3999. if not isinstance(current, FlatCAMGeometry):
  4000. current.to_form()
  4001. self.plot_all()
  4002. self.inform.emit('[success] %s: %s' %
  4003. (_("Converted units to %s"), new_units))
  4004. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4005. self.set_screen_units(new_units)
  4006. else:
  4007. # Undo toggling
  4008. self.toggle_units_ignore = True
  4009. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4010. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4011. else:
  4012. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4013. self.toggle_units_ignore = False
  4014. self.inform.emit('[WARNING_NOTCL]%s' %
  4015. _(" Units conversion cancelled."))
  4016. self.options_read_form()
  4017. self.defaults_read_form()
  4018. def on_toggle_units_click(self):
  4019. try:
  4020. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4021. except (TypeError, AttributeError):
  4022. pass
  4023. if self.defaults["units"] == 'MM':
  4024. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4025. else:
  4026. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4027. self.on_toggle_units(no_pref=True)
  4028. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4029. lambda: self.on_toggle_units(no_pref=False))
  4030. def on_fullscreen(self):
  4031. self.report_usage("on_fullscreen()")
  4032. if self.toggle_fscreen is False:
  4033. if sys.platform == 'win32':
  4034. self.ui.showFullScreen()
  4035. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4036. tb.setVisible(False)
  4037. self.ui.splitter_left.setVisible(False)
  4038. self.toggle_fscreen = True
  4039. else:
  4040. if sys.platform == 'win32':
  4041. self.ui.showNormal()
  4042. self.restore_toolbar_view()
  4043. self.ui.splitter_left.setVisible(True)
  4044. self.toggle_fscreen = False
  4045. def on_toggle_plotarea(self):
  4046. self.report_usage("on_toggle_plotarea()")
  4047. try:
  4048. name = self.ui.plot_tab_area.widget(0).objectName()
  4049. except AttributeError:
  4050. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4051. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4052. self.ui.plot_tab_area.protectTab(0)
  4053. return
  4054. if name != 'plotarea':
  4055. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4056. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4057. self.ui.plot_tab_area.protectTab(0)
  4058. else:
  4059. self.ui.plot_tab_area.closeTab(0)
  4060. def on_toggle_notebook(self):
  4061. if self.ui.splitter.sizes()[0] == 0:
  4062. self.ui.splitter.setSizes([1, 1])
  4063. else:
  4064. self.ui.splitter.setSizes([0, 1])
  4065. def on_toggle_axis(self):
  4066. self.report_usage("on_toggle_axis()")
  4067. if self.toggle_axis is False:
  4068. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4069. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4070. self.plotcanvas.redraw()
  4071. self.toggle_axis = True
  4072. else:
  4073. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4074. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4075. self.plotcanvas.redraw()
  4076. self.toggle_axis = False
  4077. def on_toggle_grid(self):
  4078. self.report_usage("on_toggle_grid()")
  4079. self.ui.grid_snap_btn.trigger()
  4080. def on_options_combo_change(self, sel):
  4081. """
  4082. Called when the combo box to choose between application defaults and
  4083. project option changes value. The corresponding variables are
  4084. copied to the UI.
  4085. :param sel: The option index that was chosen.
  4086. :return: None
  4087. """
  4088. # combo_sel = self.ui.notebook.combo_options.get_active()
  4089. App.log.debug("Options --> %s" % sel)
  4090. # form = [self.defaults_form, self.options_form][sel]
  4091. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4092. if sel == 0:
  4093. self.gen_form = self.ui.general_defaults_form
  4094. self.ger_form = self.ui.gerber_defaults_form
  4095. self.exc_form = self.ui.excellon_defaults_form
  4096. self.geo_form = self.ui.geometry_defaults_form
  4097. self.cnc_form = self.ui.cncjob_defaults_form
  4098. self.tools_form = self.ui.tools_defaults_form
  4099. self.fa_form = self.ui.fa_defaults_form
  4100. elif sel == 1:
  4101. self.gen_form = self.ui.general_options_form
  4102. self.ger_form = self.ui.gerber_options_form
  4103. self.exc_form = self.ui.excellon_options_form
  4104. self.geo_form = self.ui.geometry_options_form
  4105. self.cnc_form = self.ui.cncjob_options_form
  4106. self.tools_form = self.ui.tools_options_form
  4107. self.fa_form = self.ui.fa_options_form
  4108. else:
  4109. return
  4110. try:
  4111. self.ui.general_scroll_area.takeWidget()
  4112. except:
  4113. self.log.debug("Nothing to remove")
  4114. self.ui.general_scroll_area.setWidget(self.gen_form)
  4115. self.gen_form.show()
  4116. try:
  4117. self.ui.gerber_scroll_area.takeWidget()
  4118. except:
  4119. self.log.debug("Nothing to remove")
  4120. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4121. self.ger_form.show()
  4122. try:
  4123. self.ui.excellon_scroll_area.takeWidget()
  4124. except:
  4125. self.log.debug("Nothing to remove")
  4126. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4127. self.exc_form.show()
  4128. try:
  4129. self.ui.geometry_scroll_area.takeWidget()
  4130. except:
  4131. self.log.debug("Nothing to remove")
  4132. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4133. self.geo_form.show()
  4134. try:
  4135. self.ui.cncjob_scroll_area.takeWidget()
  4136. except:
  4137. self.log.debug("Nothing to remove")
  4138. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4139. self.cnc_form.show()
  4140. try:
  4141. self.ui.tools_scroll_area.takeWidget()
  4142. except:
  4143. self.log.debug("Nothing to remove")
  4144. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4145. self.tools_form.show()
  4146. try:
  4147. self.ui.fa_scroll_area.takeWidget()
  4148. except:
  4149. self.log.debug("Nothing to remove")
  4150. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4151. self.fa_form.show()
  4152. self.log.debug("Finished GUI form initialization.")
  4153. # self.options2form()
  4154. def on_excellon_defaults_button(self):
  4155. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4156. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4157. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4158. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4159. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4160. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4161. log.debug("Excellon app defaults loaded ...")
  4162. def on_excellon_options_button(self):
  4163. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4164. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4165. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4166. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4167. self.options_form_fields["excellon_zeros"].set_value('L')
  4168. self.options_form_fields["excellon_units"].set_value('INCH')
  4169. log.debug("Excellon options defaults loaded ...")
  4170. # Setting plot colors handlers
  4171. def on_pf_color_entry(self):
  4172. self.defaults['global_plot_fill'] = \
  4173. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4174. self.defaults['global_plot_fill'][7:9]
  4175. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4176. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4177. def on_pf_color_button(self):
  4178. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4179. c_dialog = QtWidgets.QColorDialog()
  4180. plot_fill_color = c_dialog.getColor(initial=current_color)
  4181. if plot_fill_color.isValid() is False:
  4182. return
  4183. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4184. "background-color:%s" % str(plot_fill_color.name()))
  4185. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4186. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4187. self.defaults['global_plot_fill'] = new_val
  4188. def on_pf_color_spinner(self):
  4189. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4190. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4191. self.defaults['global_plot_fill'] = \
  4192. self.defaults['global_plot_fill'][:7] + \
  4193. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4194. self.defaults['global_plot_line'] = \
  4195. self.defaults['global_plot_line'][:7] + \
  4196. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4197. def on_pf_color_slider(self):
  4198. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4199. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4200. def on_pl_color_entry(self):
  4201. self.defaults['global_plot_line'] = \
  4202. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4203. self.defaults['global_plot_line'][7:9]
  4204. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4205. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4206. def on_pl_color_button(self):
  4207. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4208. # print(current_color)
  4209. c_dialog = QtWidgets.QColorDialog()
  4210. plot_line_color = c_dialog.getColor(initial=current_color)
  4211. if plot_line_color.isValid() is False:
  4212. return
  4213. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4214. "background-color:%s" % str(plot_line_color.name()))
  4215. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4216. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4217. self.defaults['global_plot_line'] = new_val_line
  4218. # Setting selection colors (left - right) handlers
  4219. def on_sf_color_entry(self):
  4220. self.defaults['global_sel_fill'] = \
  4221. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4222. self.defaults['global_sel_fill'][7:9]
  4223. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4224. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4225. def on_sf_color_button(self):
  4226. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4227. c_dialog = QtWidgets.QColorDialog()
  4228. plot_fill_color = c_dialog.getColor(initial=current_color)
  4229. if plot_fill_color.isValid() is False:
  4230. return
  4231. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4232. "background-color:%s" % str(plot_fill_color.name()))
  4233. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4234. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4235. self.defaults['global_sel_fill'] = new_val
  4236. def on_sf_color_spinner(self):
  4237. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4238. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4239. self.defaults['global_sel_fill'] = \
  4240. self.defaults['global_sel_fill'][:7] + \
  4241. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4242. self.defaults['global_sel_line'] = \
  4243. self.defaults['global_sel_line'][:7] + \
  4244. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4245. def on_sf_color_slider(self):
  4246. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4247. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4248. def on_sl_color_entry(self):
  4249. self.defaults['global_sel_line'] = \
  4250. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4251. self.defaults['global_sel_line'][7:9]
  4252. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4253. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4254. def on_sl_color_button(self):
  4255. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4256. c_dialog = QtWidgets.QColorDialog()
  4257. plot_line_color = c_dialog.getColor(initial=current_color)
  4258. if plot_line_color.isValid() is False:
  4259. return
  4260. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4261. "background-color:%s" % str(plot_line_color.name()))
  4262. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4263. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4264. self.defaults['global_sel_line'] = new_val_line
  4265. # Setting selection colors (right - left) handlers
  4266. def on_alt_sf_color_entry(self):
  4267. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4268. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4269. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4270. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4271. def on_alt_sf_color_button(self):
  4272. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4273. c_dialog = QtWidgets.QColorDialog()
  4274. plot_fill_color = c_dialog.getColor(initial=current_color)
  4275. if plot_fill_color.isValid() is False:
  4276. return
  4277. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4278. "background-color:%s" % str(plot_fill_color.name()))
  4279. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4280. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4281. self.defaults['global_alt_sel_fill'] = new_val
  4282. def on_alt_sf_color_spinner(self):
  4283. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4284. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4285. self.defaults['global_alt_sel_fill'] = \
  4286. self.defaults['global_alt_sel_fill'][:7] + \
  4287. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4288. self.defaults['global_alt_sel_line'] = \
  4289. self.defaults['global_alt_sel_line'][:7] + \
  4290. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4291. def on_alt_sf_color_slider(self):
  4292. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4293. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4294. def on_alt_sl_color_entry(self):
  4295. self.defaults['global_alt_sel_line'] = \
  4296. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4297. self.defaults['global_alt_sel_line'][7:9]
  4298. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4299. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4300. def on_alt_sl_color_button(self):
  4301. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4302. c_dialog = QtWidgets.QColorDialog()
  4303. plot_line_color = c_dialog.getColor(initial=current_color)
  4304. if plot_line_color.isValid() is False:
  4305. return
  4306. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4307. "background-color:%s" % str(plot_line_color.name()))
  4308. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4309. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4310. self.defaults['global_alt_sel_line'] = new_val_line
  4311. # Setting Editor colors
  4312. def on_draw_color_entry(self):
  4313. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4314. .draw_color_entry.get_value()
  4315. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4316. "background-color:%s" % str(self.defaults['global_draw_color']))
  4317. def on_draw_color_button(self):
  4318. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4319. c_dialog = QtWidgets.QColorDialog()
  4320. draw_color = c_dialog.getColor(initial=current_color)
  4321. if draw_color.isValid() is False:
  4322. return
  4323. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4324. "background-color:%s" % str(draw_color.name()))
  4325. new_val = str(draw_color.name())
  4326. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4327. self.defaults['global_draw_color'] = new_val
  4328. def on_sel_draw_color_entry(self):
  4329. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4330. .sel_draw_color_entry.get_value()
  4331. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4332. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4333. def on_sel_draw_color_button(self):
  4334. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4335. c_dialog = QtWidgets.QColorDialog()
  4336. sel_draw_color = c_dialog.getColor(initial=current_color)
  4337. if sel_draw_color.isValid() is False:
  4338. return
  4339. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4340. "background-color:%s" % str(sel_draw_color.name()))
  4341. new_val_sel = str(sel_draw_color.name())
  4342. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4343. self.defaults['global_sel_draw_color'] = new_val_sel
  4344. def on_proj_color_entry(self):
  4345. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4346. .proj_color_entry.get_value()
  4347. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4348. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4349. def on_proj_color_button(self):
  4350. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4351. c_dialog = QtWidgets.QColorDialog()
  4352. proj_color = c_dialog.getColor(initial=current_color)
  4353. if proj_color.isValid() is False:
  4354. return
  4355. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4356. "background-color:%s" % str(proj_color.name()))
  4357. new_val_sel = str(proj_color.name())
  4358. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4359. self.defaults['global_proj_item_color'] = new_val_sel
  4360. def on_proj_color_dis_entry(self):
  4361. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4362. .proj_color_dis_entry.get_value()
  4363. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4364. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4365. def on_proj_color_dis_button(self):
  4366. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  4367. c_dialog = QtWidgets.QColorDialog()
  4368. proj_color = c_dialog.getColor(initial=current_color)
  4369. if proj_color.isValid() is False:
  4370. return
  4371. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4372. "background-color:%s" % str(proj_color.name()))
  4373. new_val_sel = str(proj_color.name())
  4374. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  4375. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4376. def on_annotation_fontcolor_entry(self):
  4377. self.defaults['cncjob_annotation_fontcolor'] = \
  4378. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  4379. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4380. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  4381. def on_annotation_fontcolor_button(self):
  4382. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  4383. c_dialog = QtWidgets.QColorDialog()
  4384. annotation_color = c_dialog.getColor(initial=current_color)
  4385. if annotation_color.isValid() is False:
  4386. return
  4387. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4388. "background-color:%s" % str(annotation_color.name()))
  4389. new_val_sel = str(annotation_color.name())
  4390. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  4391. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4392. def on_notebook_tab_rmb_click(self, checked):
  4393. self.ui.notebook.set_detachable(val=checked)
  4394. self.defaults["global_tabs_detachable"] = checked
  4395. self.ui.plot_tab_area.set_detachable(val=checked)
  4396. self.defaults["global_tabs_detachable"] = checked
  4397. def on_deselect_all(self):
  4398. self.collection.set_all_inactive()
  4399. self.delete_selection_shape()
  4400. def on_workspace_modified(self):
  4401. self.save_defaults(silent=True)
  4402. self.plotcanvas.draw_workspace()
  4403. def on_workspace(self):
  4404. self.report_usage("on_workspace()")
  4405. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4406. self.plotcanvas.restore_workspace()
  4407. else:
  4408. self.plotcanvas.delete_workspace()
  4409. self.save_defaults(silent=True)
  4410. def on_workspace_menu(self):
  4411. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4412. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  4413. else:
  4414. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  4415. self.on_workspace()
  4416. def on_layout(self, index=None, lay=None):
  4417. self.report_usage("on_layout()")
  4418. if lay:
  4419. current_layout = lay
  4420. else:
  4421. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  4422. settings = QSettings("Open Source", "FlatCAM")
  4423. settings.setValue('layout', current_layout)
  4424. # This will write the setting to the platform specific storage.
  4425. del settings
  4426. # first remove the toolbars:
  4427. try:
  4428. self.ui.removeToolBar(self.ui.toolbarfile)
  4429. self.ui.removeToolBar(self.ui.toolbargeo)
  4430. self.ui.removeToolBar(self.ui.toolbarview)
  4431. self.ui.removeToolBar(self.ui.toolbarshell)
  4432. self.ui.removeToolBar(self.ui.toolbartools)
  4433. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  4434. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  4435. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  4436. self.ui.removeToolBar(self.ui.snap_toolbar)
  4437. self.ui.removeToolBar(self.ui.toolbarshell)
  4438. except Exception as e:
  4439. pass
  4440. if current_layout == 'standard':
  4441. # ## TOOLBAR INSTALLATION # ##
  4442. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4443. self.ui.toolbarfile.setObjectName('File_TB')
  4444. self.ui.addToolBar(self.ui.toolbarfile)
  4445. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4446. self.ui.toolbargeo.setObjectName('Edit_TB')
  4447. self.ui.addToolBar(self.ui.toolbargeo)
  4448. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4449. self.ui.toolbarview.setObjectName('View_TB')
  4450. self.ui.addToolBar(self.ui.toolbarview)
  4451. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4452. self.ui.toolbarshell.setObjectName('Shell_TB')
  4453. self.ui.addToolBar(self.ui.toolbarshell)
  4454. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4455. self.ui.toolbartools.setObjectName('Tools_TB')
  4456. self.ui.addToolBar(self.ui.toolbartools)
  4457. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4458. self.ui.exc_edit_toolbar.setVisible(False)
  4459. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4460. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  4461. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4462. self.ui.geo_edit_toolbar.setVisible(False)
  4463. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4464. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  4465. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4466. self.ui.grb_edit_toolbar.setVisible(False)
  4467. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4468. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  4469. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4470. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4471. # self.ui.snap_toolbar.setMaximumHeight(30)
  4472. self.ui.addToolBar(self.ui.snap_toolbar)
  4473. self.ui.corner_snap_btn.setVisible(False)
  4474. self.ui.snap_magnet.setVisible(False)
  4475. elif current_layout == 'compact':
  4476. # ## TOOLBAR INSTALLATION # ##
  4477. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4478. self.ui.toolbarfile.setObjectName('File_TB')
  4479. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4480. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4481. self.ui.toolbargeo.setObjectName('Edit_TB')
  4482. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4483. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4484. self.ui.toolbarview.setObjectName('View_TB')
  4485. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  4486. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4487. self.ui.toolbarshell.setObjectName('Shell_TB')
  4488. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4489. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4490. self.ui.toolbartools.setObjectName('Tools_TB')
  4491. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4492. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4493. # self.ui.geo_edit_toolbar.setVisible(False)
  4494. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4495. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4496. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4497. # self.ui.grb_edit_toolbar.setVisible(False)
  4498. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4499. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4500. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4501. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4502. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4503. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4504. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4505. self.ui.snap_toolbar.setMaximumHeight(30)
  4506. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4507. self.ui.corner_snap_btn.setVisible(True)
  4508. self.ui.snap_magnet.setVisible(True)
  4509. # add all the actions to the toolbars
  4510. self.ui.populate_toolbars()
  4511. # reconnect all the signals to the toolbar actions
  4512. self.connect_toolbar_signals()
  4513. self.ui.grid_snap_btn.setChecked(True)
  4514. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4515. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4516. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4517. self.ui.grid_gap_link_cb.setChecked(True)
  4518. def on_cnc_custom_parameters(self, signal_text):
  4519. if signal_text == 'Parameters':
  4520. return
  4521. else:
  4522. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4523. def on_save_button(self):
  4524. log.debug("App.on_save_button() --> Saving preferences to file.")
  4525. self.preferences_changed_flag = False
  4526. self.save_defaults(silent=False)
  4527. # load the defaults so they are updated into the app
  4528. self.load_defaults(filename='current_defaults')
  4529. # Re-fresh project options
  4530. self.on_options_app2project()
  4531. # save the notebook font size
  4532. settings = QSettings("Open Source", "FlatCAM")
  4533. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4534. settings.setValue('notebook_font_size', fsize)
  4535. # save the axis font size
  4536. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4537. settings.setValue('axis_font_size', g_fsize)
  4538. # This will write the setting to the platform specific storage.
  4539. del settings
  4540. def handlePrint(self):
  4541. self.report_usage("handlePrint()")
  4542. dialog = QtPrintSupport.QPrintDialog()
  4543. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4544. self.ui.code_editor.document().print_(dialog.printer())
  4545. def handlePreview(self):
  4546. self.report_usage("handlePreview()")
  4547. dialog = QtPrintSupport.QPrintPreviewDialog()
  4548. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4549. dialog.exec_()
  4550. def handleTextChanged(self):
  4551. # enable = not self.ui.code_editor.document().isEmpty()
  4552. # self.ui.buttonPrint.setEnabled(enable)
  4553. # self.ui.buttonPreview.setEnabled(enable)
  4554. pass
  4555. def handleOpen(self, filt=None):
  4556. self.report_usage("handleOpen()")
  4557. if filt:
  4558. _filter_ = filt
  4559. else:
  4560. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4561. "All Files (*.*)"
  4562. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4563. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4564. if path:
  4565. file = QtCore.QFile(path)
  4566. if file.open(QtCore.QIODevice.ReadOnly):
  4567. stream = QtCore.QTextStream(file)
  4568. self.gcode_edited = stream.readAll()
  4569. self.ui.code_editor.setPlainText(self.gcode_edited)
  4570. file.close()
  4571. def handleSaveGCode(self, name=None, filt=None):
  4572. self.report_usage("handleSaveGCode()")
  4573. if filt:
  4574. _filter_ = filt
  4575. else:
  4576. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4577. "All Files (*.*)"
  4578. if name:
  4579. obj_name = name
  4580. else:
  4581. try:
  4582. obj_name = self.collection.get_active().options['name']
  4583. except AttributeError:
  4584. obj_name = 'file'
  4585. if filt is None:
  4586. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4587. try:
  4588. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4589. caption=_("Export G-Code ..."),
  4590. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4591. filter=_filter_
  4592. )[0])
  4593. except TypeError:
  4594. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4595. if filename == "":
  4596. self.inform.emit('[WARNING_NOTCL] %s' %
  4597. _("Export Code cancelled."))
  4598. return
  4599. else:
  4600. try:
  4601. my_gcode = self.ui.code_editor.toPlainText()
  4602. with open(filename, 'w') as f:
  4603. for line in my_gcode:
  4604. f.write(line)
  4605. except FileNotFoundError:
  4606. self.inform.emit('[WARNING] %s' %
  4607. _("No such file or directory"))
  4608. return
  4609. except PermissionError:
  4610. self.inform.emit('[WARNING] %s' %
  4611. _("Permission denied, saving not possible.\n"
  4612. "Most likely another app is holding the file open and not accessible."))
  4613. return
  4614. # Just for adding it to the recent files list.
  4615. if self.defaults["global_open_style"] is False:
  4616. self.file_opened.emit("cncjob", filename)
  4617. self.file_saved.emit("cncjob", filename)
  4618. self.inform.emit(_("Saved to: %s") % filename)
  4619. def handleFindGCode(self):
  4620. self.report_usage("handleFindGCode()")
  4621. flags = QtGui.QTextDocument.FindCaseSensitively
  4622. text_to_be_found = self.ui.entryFind.get_value()
  4623. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4624. if r is False:
  4625. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4626. def handleReplaceGCode(self):
  4627. self.report_usage("handleReplaceGCode()")
  4628. old = self.ui.entryFind.get_value()
  4629. new = self.ui.entryReplace.get_value()
  4630. if self.ui.sel_all_cb.isChecked():
  4631. while True:
  4632. cursor = self.ui.code_editor.textCursor()
  4633. cursor.beginEditBlock()
  4634. flags = QtGui.QTextDocument.FindCaseSensitively
  4635. # self.ui.editor is the QPlainTextEdit
  4636. r = self.ui.code_editor.find(str(old), flags)
  4637. if r:
  4638. qc = self.ui.code_editor.textCursor()
  4639. if qc.hasSelection():
  4640. qc.insertText(new)
  4641. else:
  4642. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4643. break
  4644. # Mark end of undo block
  4645. cursor.endEditBlock()
  4646. else:
  4647. cursor = self.ui.code_editor.textCursor()
  4648. cursor.beginEditBlock()
  4649. qc = self.ui.code_editor.textCursor()
  4650. if qc.hasSelection():
  4651. qc.insertText(new)
  4652. # Mark end of undo block
  4653. cursor.endEditBlock()
  4654. def on_tool_add_keypress(self):
  4655. # ## Current application units in Upper Case
  4656. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4657. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4658. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4659. if notebook_widget_name == 'selected_tab':
  4660. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4661. # Tool add works for Geometry only if Advanced is True in Preferences
  4662. if self.defaults["global_app_level"] == 'a':
  4663. tool_add_popup = FCInputDialog(title="New Tool ...",
  4664. text='Enter a Tool Diameter:',
  4665. min=0.0000, max=99.9999, decimals=4)
  4666. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4667. val, ok = tool_add_popup.get_value()
  4668. if ok:
  4669. if float(val) == 0:
  4670. self.inform.emit('[WARNING_NOTCL] %s' %
  4671. _("Please enter a tool diameter with non-zero value, in Float format."))
  4672. return
  4673. self.collection.get_active().on_tool_add(dia=float(val))
  4674. else:
  4675. self.inform.emit('[WARNING_NOTCL] %s...' %
  4676. _("Adding Tool cancelled"))
  4677. else:
  4678. msgbox = QtWidgets.QMessageBox()
  4679. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4680. "Go to Preferences -> General - Show Advanced Options."))
  4681. msgbox.setWindowTitle("Tool adding ...")
  4682. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  4683. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4684. msgbox.setDefaultButton(bt_ok)
  4685. msgbox.exec_()
  4686. # work only if the notebook tab on focus is the Tools_Tab
  4687. if notebook_widget_name == 'tool_tab':
  4688. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4689. tool_add_popup = FCInputDialog(title="New Tool ...",
  4690. text='Enter a Tool Diameter:',
  4691. min=0.0000, max=99.9999, decimals=4)
  4692. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4693. val, ok = tool_add_popup.get_value()
  4694. # and only if the tool is NCC Tool
  4695. if tool_widget == self.ncclear_tool.toolName:
  4696. if ok:
  4697. if float(val) == 0:
  4698. self.inform.emit('[WARNING_NOTCL] %s' %
  4699. _("Please enter a tool diameter with non-zero value, in Float format."))
  4700. return
  4701. self.ncclear_tool.on_tool_add(dia=float(val))
  4702. else:
  4703. self.inform.emit('[WARNING_NOTCL] %s...' %
  4704. _("Adding Tool cancelled"))
  4705. # and only if the tool is Paint Area Tool
  4706. elif tool_widget == self.paint_tool.toolName:
  4707. if ok:
  4708. if float(val) == 0:
  4709. self.inform.emit('[WARNING_NOTCL] %s' %
  4710. _("Please enter a tool diameter with non-zero value, in Float format."))
  4711. return
  4712. self.paint_tool.on_tool_add(dia=float(val))
  4713. else:
  4714. self.inform.emit(
  4715. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4716. # and only if the tool is Solder Paste Dispensing Tool
  4717. elif tool_widget == self.paste_tool.toolName:
  4718. if ok:
  4719. if float(val) == 0:
  4720. self.inform.emit('[WARNING_NOTCL] %s' %
  4721. _("Please enter a tool diameter with non-zero value, in Float format."))
  4722. return
  4723. self.paste_tool.on_tool_add(dia=float(val))
  4724. else:
  4725. self.inform.emit('[WARNING_NOTCL] %s...' %
  4726. _("Adding Tool cancelled"))
  4727. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4728. # See description bellow.
  4729. def on_delete_keypress(self):
  4730. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4731. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4732. if notebook_widget_name == 'selected_tab':
  4733. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4734. self.collection.get_active().on_tool_delete()
  4735. # work only if the notebook tab on focus is the Tools_Tab
  4736. elif notebook_widget_name == 'tool_tab':
  4737. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4738. # and only if the tool is NCC Tool
  4739. if tool_widget == self.ncclear_tool.toolName:
  4740. self.ncclear_tool.on_tool_delete()
  4741. # and only if the tool is Paint Tool
  4742. elif tool_widget == self.paint_tool.toolName:
  4743. self.paint_tool.on_tool_delete()
  4744. # and only if the tool is Solder Paste Dispensing Tool
  4745. elif tool_widget == self.paste_tool.toolName:
  4746. self.paste_tool.on_tool_delete()
  4747. else:
  4748. self.on_delete()
  4749. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4750. # some screens you have to be careful where you hover with your mouse.
  4751. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4752. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4753. # Complicated, I know :)
  4754. def on_delete(self):
  4755. """
  4756. Delete the currently selected FlatCAMObjs.
  4757. :return: None
  4758. """
  4759. self.report_usage("on_delete()")
  4760. response = None
  4761. bt_ok = None
  4762. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4763. # a geometry object before we update it.
  4764. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4765. and self.grb_editor.editor_active is False:
  4766. if self.defaults["global_delete_confirmation"] is True:
  4767. msgbox = QtWidgets.QMessageBox()
  4768. msgbox.setWindowTitle(_("Delete objects"))
  4769. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  4770. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4771. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4772. "the selected objects?"))
  4773. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4774. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4775. msgbox.setDefaultButton(bt_ok)
  4776. msgbox.exec_()
  4777. response = msgbox.clickedButton()
  4778. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  4779. if self.collection.get_active():
  4780. self.log.debug("App.on_delete()")
  4781. while self.collection.get_active():
  4782. obj_active = self.collection.get_active()
  4783. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  4784. if isinstance(obj_active, FlatCAMGerber):
  4785. for el in obj_active.mark_shapes:
  4786. obj_active.mark_shapes[el].clear(update=True)
  4787. obj_active.mark_shapes[el].enabled = False
  4788. # obj_active.mark_shapes[el] = None
  4789. del el
  4790. elif isinstance(obj_active, FlatCAMCNCjob):
  4791. try:
  4792. obj_active.annotation.clear(update=True)
  4793. obj_active.annotation.enabled = False
  4794. except AttributeError:
  4795. pass
  4796. self.delete_first_selected()
  4797. self.inform.emit('%s...' %
  4798. _("Object(s) deleted"))
  4799. # make sure that the selection shape is deleted, too
  4800. self.delete_selection_shape()
  4801. else:
  4802. self.inform.emit(_("Failed. No object(s) selected..."))
  4803. else:
  4804. self.inform.emit(_("Save the work in Editor and try again ..."))
  4805. def delete_first_selected(self):
  4806. # Keep this for later
  4807. try:
  4808. sel_obj = self.collection.get_active()
  4809. name = sel_obj.options["name"]
  4810. except AttributeError:
  4811. self.log.debug("Nothing selected for deletion")
  4812. return
  4813. # Remove from dictionary
  4814. self.collection.delete_active()
  4815. # Clear form
  4816. self.setup_component_editor()
  4817. self.inform.emit('%s: %s' %
  4818. (_("Object deleted"), name))
  4819. def on_set_origin(self):
  4820. """
  4821. Set the origin to the left mouse click position
  4822. :return: None
  4823. """
  4824. # display the message for the user
  4825. # and ask him to click on the desired position
  4826. self.report_usage("on_set_origin()")
  4827. def origin_replot():
  4828. def worker_task():
  4829. with self.proc_container.new('%s...' % _("Plotting")):
  4830. for obj in self.collection.get_list():
  4831. obj.plot()
  4832. self.plotcanvas.fit_view()
  4833. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4834. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4835. self.inform.emit(_('Click to set the origin ...'))
  4836. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  4837. # first disconnect it as it may have been used by something else
  4838. try:
  4839. self.replot_signal.disconnect()
  4840. except TypeError:
  4841. pass
  4842. self.replot_signal[list].connect(origin_replot)
  4843. def on_set_zero_click(self, event):
  4844. # this function will be available only for mouse left click
  4845. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  4846. if event.button == 1:
  4847. if self.grid_status() == True:
  4848. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4849. else:
  4850. pos = pos_canvas
  4851. x = 0 - pos[0]
  4852. y = 0 - pos[1]
  4853. def worker_task():
  4854. with self.proc_container.new(_("Setting Origin...")):
  4855. for obj in self.collection.get_list():
  4856. obj.offset((x, y))
  4857. self.object_changed.emit(obj)
  4858. # Update the object bounding box options
  4859. a, b, c, d = obj.bounds()
  4860. obj.options['xmin'] = a
  4861. obj.options['ymin'] = b
  4862. obj.options['xmax'] = c
  4863. obj.options['ymax'] = d
  4864. self.inform.emit('[success]%s...' %
  4865. _('Origin set'))
  4866. self.replot_signal.emit([])
  4867. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4868. self.should_we_save = True
  4869. def on_jump_to(self, custom_location=None, fit_center=True):
  4870. """
  4871. Jump to a location by setting the mouse cursor location
  4872. :return:
  4873. """
  4874. self.report_usage("on_jump_to()")
  4875. if not custom_location:
  4876. dia_box = Dialog_box(title=_("Jump to ..."),
  4877. label=_("Enter the coordinates in format X,Y:"),
  4878. icon=QtGui.QIcon('share/jump_to16.png'))
  4879. if dia_box.ok is True:
  4880. try:
  4881. location = eval(dia_box.location)
  4882. if not isinstance(location, tuple):
  4883. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4884. return
  4885. except:
  4886. return
  4887. else:
  4888. return
  4889. else:
  4890. location = custom_location
  4891. if fit_center:
  4892. self.plotcanvas.fit_center(loc=location)
  4893. cursor = QtGui.QCursor()
  4894. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4895. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  4896. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  4897. self.inform.emit('[success] %s' %
  4898. _("Done."))
  4899. return location
  4900. def on_copy_object(self):
  4901. self.report_usage("on_copy_object()")
  4902. def initialize(obj_init, app):
  4903. obj_init.solid_geometry = obj.solid_geometry
  4904. try:
  4905. obj_init.follow_geometry = obj.follow_geometry
  4906. except AttributeError:
  4907. pass
  4908. try:
  4909. obj_init.apertures = obj.apertures
  4910. except AttributeError:
  4911. pass
  4912. try:
  4913. if obj.tools:
  4914. obj_init.tools = obj.tools
  4915. except Exception as e:
  4916. log.debug("App.on_copy_object() --> %s" % str(e))
  4917. def initialize_excellon(obj_init, app):
  4918. obj_init.tools = obj.tools
  4919. # drills are offset, so they need to be deep copied
  4920. obj_init.drills = deepcopy(obj.drills)
  4921. # slots are offset, so they need to be deep copied
  4922. obj_init.slots = deepcopy(obj.slots)
  4923. obj_init.create_geometry()
  4924. for obj in self.collection.get_selected():
  4925. obj_name = obj.options["name"]
  4926. try:
  4927. if isinstance(obj, FlatCAMExcellon):
  4928. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4929. elif isinstance(obj, FlatCAMGerber):
  4930. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4931. elif isinstance(obj, FlatCAMGeometry):
  4932. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4933. except Exception as e:
  4934. return "Operation failed: %s" % str(e)
  4935. def on_copy_object2(self, custom_name):
  4936. def initialize_geometry(obj_init, app):
  4937. obj_init.solid_geometry = obj.solid_geometry
  4938. try:
  4939. obj_init.follow_geometry = obj.follow_geometry
  4940. except AttributeError:
  4941. pass
  4942. try:
  4943. obj_init.apertures = obj.apertures
  4944. except AttributeError:
  4945. pass
  4946. try:
  4947. if obj.tools:
  4948. obj_init.tools = obj.tools
  4949. except Exception as e:
  4950. log.debug("on_copy_object2() --> %s" % str(e))
  4951. def initialize_gerber(obj_init, app):
  4952. obj_init.solid_geometry = obj.solid_geometry
  4953. obj_init.apertures = deepcopy(obj.apertures)
  4954. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4955. def initialize_excellon(obj_init, app):
  4956. obj_init.tools = obj.tools
  4957. # drills are offset, so they need to be deep copied
  4958. obj_init.drills = deepcopy(obj.drills)
  4959. # slots are offset, so they need to be deep copied
  4960. obj_init.slots = deepcopy(obj.slots)
  4961. obj_init.create_geometry()
  4962. for obj in self.collection.get_selected():
  4963. obj_name = obj.options["name"]
  4964. try:
  4965. if isinstance(obj, FlatCAMExcellon):
  4966. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4967. elif isinstance(obj, FlatCAMGerber):
  4968. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4969. elif isinstance(obj, FlatCAMGeometry):
  4970. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4971. except Exception as e:
  4972. return "Operation failed: %s" % str(e)
  4973. def on_rename_object(self, text):
  4974. self.report_usage("on_rename_object()")
  4975. named_obj = self.collection.get_active()
  4976. for obj in named_obj:
  4977. if obj is list:
  4978. self.on_rename_object(text)
  4979. else:
  4980. try:
  4981. obj.options['name'] = text
  4982. except Exception as e:
  4983. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4984. def convert_any2geo(self):
  4985. self.report_usage("convert_any2geo()")
  4986. def initialize(obj_init, app):
  4987. obj_init.solid_geometry = obj.solid_geometry
  4988. try:
  4989. obj_init.follow_geometry = obj.follow_geometry
  4990. except AttributeError:
  4991. pass
  4992. try:
  4993. obj_init.apertures = obj.apertures
  4994. except AttributeError:
  4995. pass
  4996. try:
  4997. if obj.tools:
  4998. obj_init.tools = obj.tools
  4999. except AttributeError:
  5000. pass
  5001. def initialize_excellon(obj_init, app):
  5002. # objs = self.collection.get_selected()
  5003. # FlatCAMGeometry.merge(objs, obj)
  5004. solid_geo = []
  5005. for tool in obj.tools:
  5006. for geo in obj.tools[tool]['solid_geometry']:
  5007. solid_geo.append(geo)
  5008. obj_init.solid_geometry = deepcopy(solid_geo)
  5009. if not self.collection.get_selected():
  5010. log.warning("App.convert_any2geo --> No object selected")
  5011. self.inform.emit('[WARNING_NOTCL] %s' %
  5012. _("No object is selected. Select an object and try again."))
  5013. return
  5014. for obj in self.collection.get_selected():
  5015. obj_name = obj.options["name"]
  5016. try:
  5017. if isinstance(obj, FlatCAMExcellon):
  5018. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5019. else:
  5020. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5021. except Exception as e:
  5022. return "Operation failed: %s" % str(e)
  5023. def convert_any2gerber(self):
  5024. self.report_usage("convert_any2gerber()")
  5025. def initialize_geometry(obj_init, app):
  5026. apertures = {}
  5027. apid = 0
  5028. apertures[str(apid)] = {}
  5029. apertures[str(apid)]['geometry'] = []
  5030. for obj_orig in obj.solid_geometry:
  5031. new_elem = dict()
  5032. new_elem['solid'] = obj_orig
  5033. new_elem['follow'] = obj_orig.exterior
  5034. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5035. apertures[str(apid)]['size'] = 0.0
  5036. apertures[str(apid)]['type'] = 'C'
  5037. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5038. obj_init.apertures = deepcopy(apertures)
  5039. def initialize_excellon(obj_init, app):
  5040. apertures = {}
  5041. apid = 10
  5042. for tool in obj.tools:
  5043. apertures[str(apid)] = {}
  5044. apertures[str(apid)]['geometry'] = []
  5045. for geo in obj.tools[tool]['solid_geometry']:
  5046. new_el = dict()
  5047. new_el['solid'] = geo
  5048. new_el['follow'] = geo.exterior
  5049. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5050. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5051. apertures[str(apid)]['type'] = 'C'
  5052. apid += 1
  5053. # create solid_geometry
  5054. solid_geometry = []
  5055. for apid in apertures:
  5056. for geo_el in apertures[apid]['geometry']:
  5057. solid_geometry.append(geo_el['solid'])
  5058. solid_geometry = MultiPolygon(solid_geometry)
  5059. solid_geometry = solid_geometry.buffer(0.0000001)
  5060. obj_init.solid_geometry = deepcopy(solid_geometry)
  5061. obj_init.apertures = deepcopy(apertures)
  5062. # clear the working objects (perhaps not necessary due of Python GC)
  5063. apertures.clear()
  5064. if not self.collection.get_selected():
  5065. log.warning("App.convert_any2gerber --> No object selected")
  5066. self.inform.emit('[WARNING_NOTCL] %s' %
  5067. _("No object is selected. Select an object and try again."))
  5068. return
  5069. for obj in self.collection.get_selected():
  5070. obj_name = obj.options["name"]
  5071. try:
  5072. if isinstance(obj, FlatCAMExcellon):
  5073. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5074. elif isinstance(obj, FlatCAMGeometry):
  5075. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5076. else:
  5077. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5078. except Exception as e:
  5079. return "Operation failed: %s" % str(e)
  5080. def abort_all_tasks(self):
  5081. if self.abort_flag is False:
  5082. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5083. self.abort_flag = True
  5084. def app_is_idle(self):
  5085. if self.abort_flag:
  5086. self.inform.emit('[WARNING_NOTCL] %s' %
  5087. _("The current task was gracefully closed on user request..."))
  5088. self.abort_flag = False
  5089. def on_selectall(self):
  5090. self.report_usage("on_selectall()")
  5091. # delete the possible selection box around a possible selected object
  5092. self.delete_selection_shape()
  5093. for name in self.collection.get_names():
  5094. self.collection.set_active(name)
  5095. curr_sel_obj = self.collection.get_by_name(name)
  5096. # create the selection box around the selected object
  5097. if self.defaults['global_selection_shape'] is True:
  5098. self.draw_selection_shape(curr_sel_obj)
  5099. def on_preferences(self):
  5100. # add the tab if it was closed
  5101. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5102. # delete the absolute and relative position and messages in the infobar
  5103. self.ui.position_label.setText("")
  5104. self.ui.rel_position_label.setText("")
  5105. # Switch plot_area to preferences page
  5106. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5107. self.ui.show()
  5108. # this disconnect() is done so the slot will be connected only once
  5109. try:
  5110. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5111. except (TypeError, AttributeError):
  5112. pass
  5113. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5114. # detect changes in the preferences
  5115. for idx in range(self.ui.pref_tab_area.count()):
  5116. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5117. try:
  5118. try:
  5119. tb.textEdited.disconnect(self.on_preferences_edited)
  5120. except (TypeError, AttributeError):
  5121. pass
  5122. tb.textEdited.connect(self.on_preferences_edited)
  5123. except AttributeError:
  5124. pass
  5125. try:
  5126. try:
  5127. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5128. except (TypeError, AttributeError):
  5129. pass
  5130. tb.modificationChanged.connect(self.on_preferences_edited)
  5131. except AttributeError:
  5132. pass
  5133. try:
  5134. try:
  5135. tb.toggled.disconnect(self.on_preferences_edited)
  5136. except (TypeError, AttributeError):
  5137. pass
  5138. tb.toggled.connect(self.on_preferences_edited)
  5139. except AttributeError:
  5140. pass
  5141. try:
  5142. try:
  5143. tb.valueChanged.disconnect(self.on_preferences_edited)
  5144. except (TypeError, AttributeError):
  5145. pass
  5146. tb.valueChanged.connect(self.on_preferences_edited)
  5147. except AttributeError:
  5148. pass
  5149. try:
  5150. try:
  5151. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5152. except (TypeError, AttributeError):
  5153. pass
  5154. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5155. except AttributeError:
  5156. pass
  5157. def on_preferences_edited(self):
  5158. self.inform.emit('[WARNING_NOTCL] %s' %
  5159. _("Preferences edited but not saved."))
  5160. self.preferences_changed_flag = True
  5161. def on_preferences_closed(self):
  5162. # disconnect
  5163. for idx in range(self.ui.pref_tab_area.count()):
  5164. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5165. try:
  5166. tb.textEdited.disconnect(self.on_preferences_edited)
  5167. except (TypeError, AttributeError):
  5168. pass
  5169. try:
  5170. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5171. except (TypeError, AttributeError):
  5172. pass
  5173. try:
  5174. tb.toggled.disconnect(self.on_preferences_edited)
  5175. except (TypeError, AttributeError):
  5176. pass
  5177. try:
  5178. tb.valueChanged.disconnect(self.on_preferences_edited)
  5179. except (TypeError, AttributeError):
  5180. pass
  5181. try:
  5182. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5183. except (TypeError, AttributeError):
  5184. pass
  5185. if self.preferences_changed_flag is True:
  5186. msgbox = QtWidgets.QMessageBox()
  5187. msgbox.setText(_("One or more values are changed.\n"
  5188. "Do you want to save the Preferences?"))
  5189. msgbox.setWindowTitle(_("Save Preferences"))
  5190. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5191. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5192. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5193. msgbox.setDefaultButton(bt_yes)
  5194. msgbox.exec_()
  5195. response = msgbox.clickedButton()
  5196. if response == bt_yes:
  5197. self.on_save_button()
  5198. self.inform.emit('[success] %s' %
  5199. _("Preferences saved."))
  5200. else:
  5201. self.preferences_changed_flag = False
  5202. return
  5203. def on_flipy(self):
  5204. self.report_usage("on_flipy()")
  5205. obj_list = self.collection.get_selected()
  5206. xminlist = []
  5207. yminlist = []
  5208. xmaxlist = []
  5209. ymaxlist = []
  5210. if not obj_list:
  5211. self.inform.emit('[WARNING_NOTCL] %s' %
  5212. _("No object selected to Flip on Y axis."))
  5213. else:
  5214. try:
  5215. # first get a bounding box to fit all
  5216. for obj in obj_list:
  5217. xmin, ymin, xmax, ymax = obj.bounds()
  5218. xminlist.append(xmin)
  5219. yminlist.append(ymin)
  5220. xmaxlist.append(xmax)
  5221. ymaxlist.append(ymax)
  5222. # get the minimum x,y and maximum x,y for all objects selected
  5223. xminimal = min(xminlist)
  5224. yminimal = min(yminlist)
  5225. xmaximal = max(xmaxlist)
  5226. ymaximal = max(ymaxlist)
  5227. px = 0.5 * (xminimal + xmaximal)
  5228. py = 0.5 * (yminimal + ymaximal)
  5229. # execute mirroring
  5230. for obj in obj_list:
  5231. obj.mirror('X', [px, py])
  5232. obj.plot()
  5233. self.object_changed.emit(obj)
  5234. self.inform.emit('[success] %s' %
  5235. _("Flip on Y axis done."))
  5236. except Exception as e:
  5237. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5238. (_("Flip action was not executed."), str(e)))
  5239. return
  5240. def on_flipx(self):
  5241. self.report_usage("on_flipx()")
  5242. obj_list = self.collection.get_selected()
  5243. xminlist = []
  5244. yminlist = []
  5245. xmaxlist = []
  5246. ymaxlist = []
  5247. if not obj_list:
  5248. self.inform.emit('[WARNING_NOTCL] %s' %
  5249. _("No object selected to Flip on X axis."))
  5250. else:
  5251. try:
  5252. # first get a bounding box to fit all
  5253. for obj in obj_list:
  5254. xmin, ymin, xmax, ymax = obj.bounds()
  5255. xminlist.append(xmin)
  5256. yminlist.append(ymin)
  5257. xmaxlist.append(xmax)
  5258. ymaxlist.append(ymax)
  5259. # get the minimum x,y and maximum x,y for all objects selected
  5260. xminimal = min(xminlist)
  5261. yminimal = min(yminlist)
  5262. xmaximal = max(xmaxlist)
  5263. ymaximal = max(ymaxlist)
  5264. px = 0.5 * (xminimal + xmaximal)
  5265. py = 0.5 * (yminimal + ymaximal)
  5266. # execute mirroring
  5267. for obj in obj_list:
  5268. obj.mirror('Y', [px, py])
  5269. obj.plot()
  5270. self.object_changed.emit(obj)
  5271. self.inform.emit('[success] %s' %
  5272. _("Flip on X axis done."))
  5273. except Exception as e:
  5274. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5275. (_("Flip action was not executed."), str(e)))
  5276. return
  5277. def on_rotate(self, silent=False, preset=None):
  5278. self.report_usage("on_rotate()")
  5279. obj_list = self.collection.get_selected()
  5280. xminlist = []
  5281. yminlist = []
  5282. xmaxlist = []
  5283. ymaxlist = []
  5284. if not obj_list:
  5285. self.inform.emit('[WARNING_NOTCL] %s' %
  5286. _("No object selected to Rotate."))
  5287. else:
  5288. if silent is False:
  5289. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5290. min=-360, max=360, decimals=4,
  5291. init_val=float(self.defaults['tools_transform_rotate']))
  5292. num, ok = rotatebox.get_value()
  5293. else:
  5294. num = preset
  5295. ok = True
  5296. if ok:
  5297. try:
  5298. # first get a bounding box to fit all
  5299. for obj in obj_list:
  5300. xmin, ymin, xmax, ymax = obj.bounds()
  5301. xminlist.append(xmin)
  5302. yminlist.append(ymin)
  5303. xmaxlist.append(xmax)
  5304. ymaxlist.append(ymax)
  5305. # get the minimum x,y and maximum x,y for all objects selected
  5306. xminimal = min(xminlist)
  5307. yminimal = min(yminlist)
  5308. xmaximal = max(xmaxlist)
  5309. ymaximal = max(ymaxlist)
  5310. px = 0.5 * (xminimal + xmaximal)
  5311. py = 0.5 * (yminimal + ymaximal)
  5312. for sel_obj in obj_list:
  5313. sel_obj.rotate(-float(num), point=(px, py))
  5314. sel_obj.plot()
  5315. self.object_changed.emit(sel_obj)
  5316. self.inform.emit('[success] %s' %
  5317. _("Rotation done."))
  5318. except Exception as e:
  5319. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5320. (_("Rotation movement was not executed."), str(e)))
  5321. return
  5322. def on_skewx(self):
  5323. self.report_usage("on_skewx()")
  5324. obj_list = self.collection.get_selected()
  5325. xminlist = []
  5326. yminlist = []
  5327. if not obj_list:
  5328. self.inform.emit('[WARNING_NOTCL] %s' %
  5329. _("No object selected to Skew/Shear on X axis."))
  5330. else:
  5331. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5332. min=-360, max=360, decimals=4,
  5333. init_val=float(self.defaults['tools_transform_skew_x']))
  5334. num, ok = skewxbox.get_value()
  5335. if ok:
  5336. # first get a bounding box to fit all
  5337. for obj in obj_list:
  5338. xmin, ymin, xmax, ymax = obj.bounds()
  5339. xminlist.append(xmin)
  5340. yminlist.append(ymin)
  5341. # get the minimum x,y and maximum x,y for all objects selected
  5342. xminimal = min(xminlist)
  5343. yminimal = min(yminlist)
  5344. for obj in obj_list:
  5345. obj.skew(num, 0, point=(xminimal, yminimal))
  5346. obj.plot()
  5347. self.object_changed.emit(obj)
  5348. self.inform.emit('[success] %s' %
  5349. _("Skew on X axis done."))
  5350. def on_skewy(self):
  5351. self.report_usage("on_skewy()")
  5352. obj_list = self.collection.get_selected()
  5353. xminlist = []
  5354. yminlist = []
  5355. if not obj_list:
  5356. self.inform.emit('[WARNING_NOTCL] %s' %
  5357. _("No object selected to Skew/Shear on Y axis."))
  5358. else:
  5359. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5360. min=-360, max=360, decimals=4,
  5361. init_val=float(self.defaults['tools_transform_skew_y']))
  5362. num, ok = skewybox.get_value()
  5363. if ok:
  5364. # first get a bounding box to fit all
  5365. for obj in obj_list:
  5366. xmin, ymin, xmax, ymax = obj.bounds()
  5367. xminlist.append(xmin)
  5368. yminlist.append(ymin)
  5369. # get the minimum x,y and maximum x,y for all objects selected
  5370. xminimal = min(xminlist)
  5371. yminimal = min(yminlist)
  5372. for obj in obj_list:
  5373. obj.skew(0, num, point=(xminimal, yminimal))
  5374. obj.plot()
  5375. self.object_changed.emit(obj)
  5376. self.inform.emit('[success] %s' %
  5377. _("Skew on Y axis done."))
  5378. def on_plots_updated(self):
  5379. """
  5380. Callback used to report when the plots have changed.
  5381. Adjust axes and zooms to fit.
  5382. :return: None
  5383. """
  5384. self.plotcanvas.update() # TODO: Need update canvas?
  5385. self.on_zoom_fit(None)
  5386. self.collection.update_view()
  5387. # self.inform.emit(_("Plots updated ..."))
  5388. # TODO: Rework toolbar 'clear', 'replot' functions
  5389. def on_toolbar_replot(self):
  5390. """
  5391. Callback for toolbar button. Re-plots all objects.
  5392. :return: None
  5393. """
  5394. self.report_usage("on_toolbar_replot")
  5395. self.log.debug("on_toolbar_replot()")
  5396. try:
  5397. self.collection.get_active().read_form()
  5398. except AttributeError:
  5399. self.log.debug("on_toolbar_replot(): AttributeError")
  5400. pass
  5401. self.plot_all()
  5402. def on_row_activated(self, index):
  5403. if index.isValid():
  5404. if index.internalPointer().parent_item != self.collection.root_item:
  5405. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5406. self.collection.on_item_activated(index)
  5407. def grid_status(self):
  5408. if self.ui.grid_snap_btn.isChecked():
  5409. return True
  5410. else:
  5411. return False
  5412. def populate_cmenu_grids(self):
  5413. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5414. self.ui.cmenu_gridmenu.clear()
  5415. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5416. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  5417. grid_toggle.setCheckable(True)
  5418. if self.grid_status() == True:
  5419. grid_toggle.setChecked(True)
  5420. else:
  5421. grid_toggle.setChecked(False)
  5422. self.ui.cmenu_gridmenu.addSeparator()
  5423. for grid in sorted_list:
  5424. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  5425. action.triggered.connect(self.set_grid)
  5426. self.ui.cmenu_gridmenu.addSeparator()
  5427. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  5428. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  5429. grid_add.triggered.connect(self.on_grid_add)
  5430. grid_delete.triggered.connect(self.on_grid_delete)
  5431. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5432. def set_grid(self):
  5433. self.ui.grid_gap_x_entry.setText(self.sender().text())
  5434. self.ui.grid_gap_y_entry.setText(self.sender().text())
  5435. def on_grid_add(self):
  5436. # ## Current application units in lower Case
  5437. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5438. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5439. text=_('Enter a Grid Value:'),
  5440. min=0.0000, max=99.9999, decimals=4)
  5441. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  5442. val, ok = grid_add_popup.get_value()
  5443. if ok:
  5444. if float(val) == 0:
  5445. self.inform.emit('[WARNING_NOTCL] %s' %
  5446. _("Please enter a grid value with non-zero value, in Float format."))
  5447. return
  5448. else:
  5449. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5450. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5451. self.inform.emit('[success] %s...' %
  5452. _("New Grid added"))
  5453. else:
  5454. self.inform.emit('[WARNING_NOTCL] %s...' %
  5455. _("Grid already exists"))
  5456. else:
  5457. self.inform.emit('[WARNING_NOTCL] %s...' %
  5458. _("Adding New Grid cancelled"))
  5459. def on_grid_delete(self):
  5460. # ## Current application units in lower Case
  5461. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5462. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5463. text='Enter a Grid Value:',
  5464. min=0.0000, max=99.9999, decimals=4)
  5465. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  5466. val, ok = grid_del_popup.get_value()
  5467. if ok:
  5468. if float(val) == 0:
  5469. self.inform.emit('[WARNING_NOTCL] %s' %
  5470. _("Please enter a grid value with non-zero value, in Float format."))
  5471. return
  5472. else:
  5473. try:
  5474. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5475. except ValueError:
  5476. self.inform.emit('[ERROR_NOTCL]%s...' %
  5477. _(" Grid Value does not exist"))
  5478. return
  5479. self.inform.emit('[success] %s...' %
  5480. _("Grid Value deleted"))
  5481. else:
  5482. self.inform.emit('[WARNING_NOTCL] %s...' %
  5483. _("Delete Grid value cancelled"))
  5484. def on_shortcut_list(self):
  5485. self.report_usage("on_shortcut_list()")
  5486. # add the tab if it was closed
  5487. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5488. # delete the absolute and relative position and messages in the infobar
  5489. self.ui.position_label.setText("")
  5490. self.ui.rel_position_label.setText("")
  5491. # Switch plot_area to preferences page
  5492. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5493. self.ui.show()
  5494. def on_select_tab(self, name):
  5495. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5496. if self.ui.splitter.sizes()[0] == 0:
  5497. self.ui.splitter.setSizes([1, 1])
  5498. else:
  5499. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5500. self.ui.splitter.setSizes([0, 1])
  5501. if name == 'project':
  5502. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5503. elif name == 'selected':
  5504. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5505. elif name == 'tool':
  5506. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5507. def on_copy_name(self):
  5508. self.report_usage("on_copy_name()")
  5509. obj = self.collection.get_active()
  5510. try:
  5511. name = obj.options["name"]
  5512. except AttributeError:
  5513. log.debug("on_copy_name() --> No object selected to copy it's name")
  5514. self.inform.emit('[WARNING_NOTCL]%s' %
  5515. _(" No object selected to copy it's name"))
  5516. return
  5517. self.clipboard.setText(name)
  5518. self.inform.emit(_("Name copied on clipboard ..."))
  5519. def on_mouse_click_over_plot(self, event):
  5520. """
  5521. Default actions are:
  5522. :param event: Contains information about the event, like which button
  5523. was clicked, the pixel coordinates and the axes coordinates.
  5524. :return: None
  5525. """
  5526. self.pos = []
  5527. # So it can receive key presses
  5528. self.plotcanvas.native.setFocus()
  5529. # Set the mouse button for panning
  5530. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5531. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5532. if self.grid_status() == True:
  5533. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5534. self.app_cursor.enabled = True
  5535. else:
  5536. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5537. self.app_cursor.enabled = False
  5538. try:
  5539. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5540. if event.button == 1:
  5541. # Reset here the relative coordinates so there is a new reference on the click position
  5542. if self.rel_point1 is None:
  5543. self.rel_point1 = self.pos
  5544. else:
  5545. self.rel_point2 = copy(self.rel_point1)
  5546. self.rel_point1 = self.pos
  5547. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5548. if modifiers == QtCore.Qt.ShiftModifier:
  5549. # do not auto open the Project Tab
  5550. self.click_noproject = True
  5551. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5552. self.inform.emit('[success] %s' %
  5553. _("Coordinates copied to clipboard."))
  5554. return
  5555. self.on_mouse_move_over_plot(event, origin_click=True)
  5556. except Exception as e:
  5557. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5558. def on_double_click_over_plot(self, event):
  5559. self.doubleclick = True
  5560. def on_mouse_move_over_plot(self, event, origin_click=None):
  5561. """
  5562. Callback for the mouse motion event over the plot.
  5563. :param event: Contains information about the event.
  5564. :param origin_click
  5565. :return: None
  5566. """
  5567. # So it can receive key presses
  5568. self.plotcanvas.native.setFocus()
  5569. self.pos_jump = event.pos
  5570. self.ui.popMenu.mouse_is_panning = False
  5571. if not origin_click:
  5572. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5573. if event.button == 2 and event.is_dragging == 1:
  5574. self.ui.popMenu.mouse_is_panning = True
  5575. return
  5576. if self.rel_point1 is not None:
  5577. try: # May fail in case mouse not within axes
  5578. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5579. if self.grid_status() == True:
  5580. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5581. self.app_cursor.enabled = True
  5582. # Update cursor
  5583. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5584. else:
  5585. pos = (pos_canvas[0], pos_canvas[1])
  5586. self.app_cursor.enabled = False
  5587. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5588. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5589. dx = pos[0] - self.rel_point1[0]
  5590. dy = pos[1] - self.rel_point1[1]
  5591. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5592. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5593. self.mouse = [pos[0], pos[1]]
  5594. # if the mouse is moved and the LMB is clicked then the action is a selection
  5595. if event.is_dragging == 1 and event.button == 1:
  5596. self.delete_selection_shape()
  5597. if dx < 0:
  5598. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5599. face_color=self.defaults['global_alt_sel_fill'])
  5600. self.selection_type = False
  5601. else:
  5602. self.draw_moving_selection_shape(self.pos, pos)
  5603. self.selection_type = True
  5604. # hover effect - enabled in Preferences -> General -> GUI Settings
  5605. if self.defaults['global_hover']:
  5606. for obj in self.collection.get_list():
  5607. try:
  5608. # select the object(s) only if it is enabled (plotted)
  5609. if obj.options['plot']:
  5610. if obj not in self.collection.get_selected():
  5611. poly_obj = Polygon(
  5612. [(obj.options['xmin'], obj.options['ymin']),
  5613. (obj.options['xmax'], obj.options['ymin']),
  5614. (obj.options['xmax'], obj.options['ymax']),
  5615. (obj.options['xmin'], obj.options['ymax'])]
  5616. )
  5617. if Point(pos).within(poly_obj):
  5618. if obj.isHovering is False:
  5619. obj.isHovering = True
  5620. obj.notHovering = True
  5621. # create the selection box around the selected object
  5622. self.draw_hover_shape(obj, color='#d1e0e0')
  5623. else:
  5624. if obj.notHovering is True:
  5625. obj.notHovering = False
  5626. obj.isHovering = False
  5627. self.delete_hover_shape()
  5628. except:
  5629. # the Exception here will happen if we try to select on screen and we have an
  5630. # newly (and empty) just created Geometry or Excellon object that do not have the
  5631. # xmin, xmax, ymin, ymax options.
  5632. # In this case poly_obj creation (see above) will fail
  5633. pass
  5634. except:
  5635. self.ui.position_label.setText("")
  5636. self.ui.rel_position_label.setText("")
  5637. self.mouse = None
  5638. def on_mouse_click_release_over_plot(self, event):
  5639. """
  5640. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5641. and has been registered in ''self.__init__()''.
  5642. :param event: contains information about the event.
  5643. :return:
  5644. """
  5645. pos = 0, 0
  5646. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5647. if self.grid_status() == True:
  5648. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5649. else:
  5650. pos = (pos_canvas[0], pos_canvas[1])
  5651. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5652. # canvas menu
  5653. if event.button == 2: # right click
  5654. if self.ui.popMenu.mouse_is_panning is False:
  5655. self.cursor = QtGui.QCursor()
  5656. self.populate_cmenu_grids()
  5657. self.ui.popMenu.popup(self.cursor.pos())
  5658. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5659. # selection and then select a type of selection ("enclosing" or "touching")
  5660. try:
  5661. if event.button == 1: # left click
  5662. if self.doubleclick is True:
  5663. self.doubleclick = False
  5664. if self.collection.get_selected():
  5665. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5666. if self.ui.splitter.sizes()[0] == 0:
  5667. self.ui.splitter.setSizes([1, 1])
  5668. # delete the selection shape(S) as it may be in the way
  5669. self.delete_selection_shape()
  5670. self.delete_hover_shape()
  5671. else:
  5672. if self.selection_type is not None:
  5673. self.selection_area_handler(self.pos, pos, self.selection_type)
  5674. self.selection_type = None
  5675. else:
  5676. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5677. if key_modifier == QtCore.Qt.ShiftModifier:
  5678. mod_key = 'Shift'
  5679. elif key_modifier == QtCore.Qt.ControlModifier:
  5680. mod_key = 'Control'
  5681. else:
  5682. mod_key = None
  5683. if mod_key == self.defaults["global_mselect_key"]:
  5684. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5685. # deselect, and if it's not selected then it will be selected
  5686. # If there is no active command (self.command_active is None) then we check if we clicked
  5687. # on a object by checking the bounding limits against mouse click position
  5688. if self.command_active is None:
  5689. self.select_objects(key='CTRL')
  5690. self.delete_hover_shape()
  5691. else:
  5692. # If there is no active command (self.command_active is None) then we check if we clicked
  5693. # on a object by checking the bounding limits against mouse click position
  5694. if self.command_active is None:
  5695. self.select_objects()
  5696. self.delete_hover_shape()
  5697. except Exception as e:
  5698. log.warning("Error: %s" % str(e))
  5699. return
  5700. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5701. """
  5702. :param start_pos: mouse position when the selection LMB click was done
  5703. :param end_pos: mouse position when the left mouse button is released
  5704. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5705. :return:
  5706. """
  5707. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5708. self.delete_selection_shape()
  5709. for obj in self.collection.get_list():
  5710. try:
  5711. # select the object(s) only if it is enabled (plotted)
  5712. if obj.options['plot']:
  5713. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5714. (obj.options['xmax'], obj.options['ymin']),
  5715. (obj.options['xmax'], obj.options['ymax']),
  5716. (obj.options['xmin'], obj.options['ymax'])])
  5717. if sel_type is True:
  5718. if poly_obj.within(poly_selection):
  5719. # create the selection box around the selected object
  5720. if self.defaults['global_selection_shape'] is True:
  5721. self.draw_selection_shape(obj)
  5722. self.collection.set_active(obj.options['name'])
  5723. else:
  5724. if poly_selection.intersects(poly_obj):
  5725. # create the selection box around the selected object
  5726. if self.defaults['global_selection_shape'] is True:
  5727. self.draw_selection_shape(obj)
  5728. self.collection.set_active(obj.options['name'])
  5729. except Exception as e:
  5730. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5731. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5732. # In this case poly_obj creation (see above) will fail
  5733. log.debug("App.selection_area_handler() --> %s" % str(e))
  5734. def select_objects(self, key=None):
  5735. # list where we store the overlapped objects under our mouse left click position
  5736. objects_under_the_click_list = []
  5737. # Populate the list with the overlapped objects on the click position
  5738. curr_x, curr_y = self.pos
  5739. for obj in self.all_objects_list:
  5740. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5741. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5742. if obj.options['name'] not in objects_under_the_click_list:
  5743. if obj.options['plot']:
  5744. # add objects to the objects_under_the_click list only if the object is plotted
  5745. # (active and not disabled)
  5746. objects_under_the_click_list.append(obj.options['name'])
  5747. try:
  5748. # If there is no element in the overlapped objects list then make everyone inactive
  5749. # because we selected "nothing"
  5750. if not objects_under_the_click_list:
  5751. self.collection.set_all_inactive()
  5752. # delete the possible selection box around a possible selected object
  5753. self.delete_selection_shape()
  5754. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5755. # only when working on App
  5756. if self.call_source == 'app':
  5757. if self.click_noproject is False:
  5758. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5759. else:
  5760. # restore auto open the Project Tab
  5761. self.click_noproject = False
  5762. # delete any text in the status bar, implicitly the last object name that was selected
  5763. self.inform.emit("")
  5764. else:
  5765. self.call_source = 'app'
  5766. else:
  5767. # case when there is only an object under the click and we toggle it
  5768. if len(objects_under_the_click_list) == 1:
  5769. if self.collection.get_active() is None:
  5770. self.collection.set_active(objects_under_the_click_list[0])
  5771. # create the selection box around the selected object
  5772. curr_sel_obj = self.collection.get_active()
  5773. if self.defaults['global_selection_shape'] is True:
  5774. self.draw_selection_shape(curr_sel_obj)
  5775. # self.inform.emit('[selected] %s: %s selected' %
  5776. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5777. if curr_sel_obj.kind == 'gerber':
  5778. self.inform.emit(
  5779. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5780. color='green', name=str(curr_sel_obj.options['name'])))
  5781. elif curr_sel_obj.kind == 'excellon':
  5782. self.inform.emit(
  5783. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5784. color='brown', name=str(curr_sel_obj.options['name'])))
  5785. elif curr_sel_obj.kind == 'cncjob':
  5786. self.inform.emit(
  5787. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5788. color='blue', name=str(curr_sel_obj.options['name'])))
  5789. elif curr_sel_obj.kind == 'geometry':
  5790. self.inform.emit(
  5791. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5792. color='red', name=str(curr_sel_obj.options['name'])))
  5793. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  5794. self.collection.set_all_inactive()
  5795. self.delete_selection_shape()
  5796. self.collection.set_active(objects_under_the_click_list[0])
  5797. # create the selection box around the selected object
  5798. curr_sel_obj = self.collection.get_active()
  5799. if self.defaults['global_selection_shape'] is True:
  5800. self.draw_selection_shape(curr_sel_obj)
  5801. # self.inform.emit('[selected] %s: %s selected' %
  5802. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5803. if curr_sel_obj.kind == 'gerber':
  5804. self.inform.emit(
  5805. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5806. color='green', name=str(curr_sel_obj.options['name'])))
  5807. elif curr_sel_obj.kind == 'excellon':
  5808. self.inform.emit(
  5809. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5810. color='brown', name=str(curr_sel_obj.options['name'])))
  5811. elif curr_sel_obj.kind == 'cncjob':
  5812. self.inform.emit(
  5813. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5814. color='blue', name=str(curr_sel_obj.options['name'])))
  5815. elif curr_sel_obj.kind == 'geometry':
  5816. self.inform.emit(
  5817. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5818. color='red', name=str(curr_sel_obj.options['name'])))
  5819. else:
  5820. self.collection.set_all_inactive()
  5821. self.delete_selection_shape()
  5822. if self.call_source == 'app':
  5823. # delete any text in the status bar, implicitly the last object name that was selected
  5824. self.inform.emit("")
  5825. else:
  5826. self.call_source = 'app'
  5827. else:
  5828. # If there is no selected object
  5829. # make active the first element of the overlapped objects list
  5830. if self.collection.get_active() is None:
  5831. self.collection.set_active(objects_under_the_click_list[0])
  5832. name_sel_obj = self.collection.get_active().options['name']
  5833. # In case that there is a selected object but it is not in the overlapped object list
  5834. # make that object inactive and activate the first element in the overlapped object list
  5835. if name_sel_obj not in objects_under_the_click_list:
  5836. self.collection.set_inactive(name_sel_obj)
  5837. name_sel_obj = objects_under_the_click_list[0]
  5838. self.collection.set_active(name_sel_obj)
  5839. else:
  5840. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  5841. self.collection.set_all_inactive()
  5842. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  5843. len(objects_under_the_click_list)])
  5844. curr_sel_obj = self.collection.get_active()
  5845. # delete the possible selection box around a possible selected object
  5846. self.delete_selection_shape()
  5847. # create the selection box around the selected object
  5848. if self.defaults['global_selection_shape'] is True:
  5849. self.draw_selection_shape(curr_sel_obj)
  5850. # self.inform.emit('[selected] %s: %s selected' %
  5851. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5852. if curr_sel_obj.kind == 'gerber':
  5853. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5854. color='green', name=str(curr_sel_obj.options['name'])))
  5855. elif curr_sel_obj.kind == 'excellon':
  5856. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5857. color='brown', name=str(curr_sel_obj.options['name'])))
  5858. elif curr_sel_obj.kind == 'cncjob':
  5859. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5860. color='blue', name=str(curr_sel_obj.options['name'])))
  5861. elif curr_sel_obj.kind == 'geometry':
  5862. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5863. color='red', name=str(curr_sel_obj.options['name'])))
  5864. # for obj in self.collection.get_list():
  5865. # obj.plot()
  5866. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  5867. # TODO: on selected objects change the object colors and do not draw the selection box
  5868. # self.plotcanvas.update() # this updates the canvas
  5869. except Exception as e:
  5870. log.error("[ERROR] Something went bad. %s" % str(e))
  5871. return
  5872. def delete_hover_shape(self):
  5873. self.hover_shapes.clear()
  5874. self.hover_shapes.redraw()
  5875. def draw_hover_shape(self, sel_obj, color=None):
  5876. """
  5877. :param sel_obj: the object for which the hover shape must be drawn
  5878. :return:
  5879. """
  5880. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5881. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5882. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5883. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5884. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5885. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5886. hover_rect = hover_rect.buffer(-0.1)
  5887. hover_rect = hover_rect.buffer(0.2)
  5888. else:
  5889. hover_rect = hover_rect.buffer(-0.00393)
  5890. hover_rect = hover_rect.buffer(0.00787)
  5891. if color:
  5892. face = Color(color)
  5893. face.alpha = 0.2
  5894. outline = Color(color, alpha=0.8)
  5895. else:
  5896. face = Color(self.defaults['global_sel_fill'])
  5897. face.alpha = 0.2
  5898. outline = self.defaults['global_sel_line']
  5899. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5900. def delete_selection_shape(self):
  5901. self.move_tool.sel_shapes.clear()
  5902. self.move_tool.sel_shapes.redraw()
  5903. def draw_selection_shape(self, sel_obj, color=None):
  5904. """
  5905. :param sel_obj: the object for which the selection shape must be drawn
  5906. :return:
  5907. """
  5908. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5909. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5910. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5911. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5912. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5913. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5914. sel_rect = sel_rect.buffer(-0.1)
  5915. sel_rect = sel_rect.buffer(0.2)
  5916. else:
  5917. sel_rect = sel_rect.buffer(-0.00393)
  5918. sel_rect = sel_rect.buffer(0.00787)
  5919. if color:
  5920. face = Color(color, alpha=0.2)
  5921. outline = Color(color, alpha=0.8)
  5922. else:
  5923. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  5924. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  5925. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5926. color=outline,
  5927. face_color=face,
  5928. update=True,
  5929. layer=0,
  5930. tolerance=None))
  5931. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5932. """
  5933. :param old_coords: old coordinates
  5934. :param coords: new coordinates
  5935. :return:
  5936. """
  5937. if 'color' in kwargs:
  5938. color = kwargs['color']
  5939. else:
  5940. color = self.defaults['global_sel_line']
  5941. if 'face_color' in kwargs:
  5942. face_color = kwargs['face_color']
  5943. else:
  5944. face_color = self.defaults['global_sel_fill']
  5945. if 'face_alpha' in kwargs:
  5946. face_alpha = kwargs['face_alpha']
  5947. else:
  5948. face_alpha = 0.3
  5949. x0, y0 = old_coords
  5950. x1, y1 = coords
  5951. pt1 = (x0, y0)
  5952. pt2 = (x1, y0)
  5953. pt3 = (x1, y1)
  5954. pt4 = (x0, y1)
  5955. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5956. color_t = Color(face_color)
  5957. color_t.alpha = face_alpha
  5958. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5959. layer=0, tolerance=None)
  5960. def on_file_new_click(self):
  5961. if self.collection.get_list() and self.should_we_save:
  5962. msgbox = QtWidgets.QMessageBox()
  5963. # msgbox.setText("<B>Save changes ...</B>")
  5964. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5965. "Creating a New project will delete them.\n"
  5966. "Do you want to Save the project?"))
  5967. msgbox.setWindowTitle(_("Save changes"))
  5968. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5969. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5970. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5971. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5972. msgbox.setDefaultButton(bt_yes)
  5973. msgbox.exec_()
  5974. response = msgbox.clickedButton()
  5975. if response == bt_yes:
  5976. self.on_file_saveprojectas()
  5977. elif response == bt_cancel:
  5978. return
  5979. elif response == bt_no:
  5980. self.on_file_new()
  5981. else:
  5982. self.on_file_new()
  5983. self.inform.emit('[success] %s...' %
  5984. _("New Project created"))
  5985. def on_file_new(self):
  5986. """
  5987. Callback for menu item File->New. Returns the application to its
  5988. startup state. This method is thread-safe.
  5989. :return: None
  5990. """
  5991. self.report_usage("on_file_new")
  5992. # Remove everything from memory
  5993. App.log.debug("on_file_new()")
  5994. if self.call_source != 'app':
  5995. self.editor2object(cleanup=True)
  5996. # ## EDITOR section
  5997. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  5998. self.exc_editor = FlatCAMExcEditor(self)
  5999. self.grb_editor = FlatCAMGrbEditor(self)
  6000. # Clear pool
  6001. self.clear_pool()
  6002. for obj in self.collection.get_list():
  6003. # delete shapes left drawn from mark shape_collections, if any
  6004. if isinstance(obj, FlatCAMGerber):
  6005. try:
  6006. obj.mark_shapes.enabled = False
  6007. obj.mark_shapes.clear(update=True)
  6008. except AttributeError:
  6009. pass
  6010. # also delete annotation shapes, if any
  6011. elif isinstance(obj, FlatCAMCNCjob):
  6012. try:
  6013. obj.annotation.enabled = False
  6014. obj.annotation.clear(update=True)
  6015. except AttributeError:
  6016. pass
  6017. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6018. self.init_tcl()
  6019. self.delete_selection_shape()
  6020. self.collection.delete_all()
  6021. self.setup_component_editor()
  6022. # Clear project filename
  6023. self.project_filename = None
  6024. # Load the application defaults
  6025. self.load_defaults(filename='current_defaults')
  6026. # Re-fresh project options
  6027. self.on_options_app2project()
  6028. # Init Tools
  6029. self.init_tools()
  6030. # Close any Tabs opened in the Plot Tab Area section
  6031. for index in range(self.ui.plot_tab_area.count()):
  6032. self.ui.plot_tab_area.closeTab(index)
  6033. # for whatever reason previous command does not close the last tab so I do it manually
  6034. self.ui.plot_tab_area.closeTab(0)
  6035. # # And then add again the Plot Area
  6036. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6037. self.ui.plot_tab_area.protectTab(0)
  6038. # take the focus of the Notebook on Project Tab.
  6039. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6040. self.set_ui_title(name=_("New Project - Not saved"))
  6041. def obj_properties(self):
  6042. self.report_usage("obj_properties()")
  6043. self.properties_tool.run(toggle=False)
  6044. def on_project_context_save(self):
  6045. obj = self.collection.get_active()
  6046. if type(obj) == FlatCAMGeometry:
  6047. self.on_file_exportdxf()
  6048. elif type(obj) == FlatCAMExcellon:
  6049. self.on_file_saveexcellon()
  6050. elif type(obj) == FlatCAMCNCjob:
  6051. obj.on_exportgcode_button_click()
  6052. elif type(obj) == FlatCAMGerber:
  6053. self.on_file_savegerber()
  6054. def obj_move(self):
  6055. self.report_usage("obj_move()")
  6056. self.move_tool.run(toggle=False)
  6057. def on_fileopengerber(self, checked=None, name=None):
  6058. """
  6059. File menu callback for opening a Gerber.
  6060. :return: None
  6061. """
  6062. self.report_usage("on_fileopengerber")
  6063. App.log.debug("on_fileopengerber()")
  6064. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6065. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6066. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6067. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6068. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6069. "*.mil);;" \
  6070. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6071. "Allegro Files (*.art);;" \
  6072. "Mentor Files (*.pho *.gdo);;" \
  6073. "All Files (*.*)"
  6074. if name is None:
  6075. try:
  6076. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6077. directory=self.get_last_folder(),
  6078. filter=_filter_)
  6079. except TypeError:
  6080. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6081. filenames = [str(filename) for filename in filenames]
  6082. else:
  6083. filenames = [name]
  6084. if len(filenames) == 0:
  6085. self.inform.emit('[WARNING_NOTCL] %s' %
  6086. _("Open Gerber cancelled."))
  6087. else:
  6088. for filename in filenames:
  6089. if filename != '':
  6090. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6091. def on_fileopenexcellon(self, checked=None, name=None):
  6092. """
  6093. File menu callback for opening an Excellon file.
  6094. :return: None
  6095. """
  6096. self.report_usage("on_fileopenexcellon")
  6097. App.log.debug("on_fileopenexcellon()")
  6098. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6099. "All Files (*.*)"
  6100. if name is None:
  6101. try:
  6102. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6103. directory=self.get_last_folder(),
  6104. filter=_filter_)
  6105. except TypeError:
  6106. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6107. filenames = [str(filename) for filename in filenames]
  6108. else:
  6109. filenames = [str(name)]
  6110. if len(filenames) == 0:
  6111. self.inform.emit('[WARNING_NOTCL]%s' %
  6112. _(" Open Excellon cancelled."))
  6113. else:
  6114. for filename in filenames:
  6115. if filename != '':
  6116. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6117. def on_fileopengcode(self, checked=None, name=None):
  6118. """
  6119. File menu call back for opening gcode.
  6120. :return: None
  6121. """
  6122. self.report_usage("on_fileopengcode")
  6123. App.log.debug("on_fileopengcode()")
  6124. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6125. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6126. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6127. "All Files (*.*)"
  6128. if name is None:
  6129. try:
  6130. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6131. directory=self.get_last_folder(),
  6132. filter=_filter_)
  6133. except TypeError:
  6134. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6135. filenames = [str(filename) for filename in filenames]
  6136. else:
  6137. filenames = [name]
  6138. if len(filenames) == 0:
  6139. self.inform.emit('[WARNING_NOTCL] %s' %
  6140. _("Open G-Code cancelled."))
  6141. else:
  6142. for filename in filenames:
  6143. if filename != '':
  6144. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6145. def on_file_openproject(self, checked=None):
  6146. """
  6147. File menu callback for opening a project.
  6148. :return: None
  6149. """
  6150. self.report_usage("on_file_openproject")
  6151. App.log.debug("on_file_openproject()")
  6152. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6153. try:
  6154. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6155. directory=self.get_last_folder(), filter=_filter_)
  6156. except TypeError:
  6157. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6158. # The Qt methods above will return a QString which can cause problems later.
  6159. # So far json.dump() will fail to serialize it.
  6160. # TODO: Improve the serialization methods and remove this fix.
  6161. filename = str(filename)
  6162. if filename == "":
  6163. self.inform.emit('[WARNING_NOTCL] %s' %
  6164. _("Open Project cancelled."))
  6165. else:
  6166. # self.worker_task.emit({'fcn': self.open_project,
  6167. # 'params': [filename]})
  6168. # The above was failing because open_project() is not
  6169. # thread safe. The new_project()
  6170. self.open_project(filename)
  6171. def on_file_openconfig(self, checked=None):
  6172. """
  6173. File menu callback for opening a config file.
  6174. :return: None
  6175. """
  6176. self.report_usage("on_file_openconfig")
  6177. App.log.debug("on_file_openconfig()")
  6178. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6179. try:
  6180. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6181. directory=self.data_path, filter=_filter_)
  6182. except TypeError:
  6183. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6184. filter=_filter_)
  6185. if filename == "":
  6186. self.inform.emit('[WARNING_NOTCL] %s' %
  6187. _("Open Config cancelled."))
  6188. else:
  6189. self.open_config_file(filename)
  6190. def on_file_exportsvg(self):
  6191. """
  6192. Callback for menu item File->Export SVG.
  6193. :return: None
  6194. """
  6195. self.report_usage("on_file_exportsvg")
  6196. App.log.debug("on_file_exportsvg()")
  6197. obj = self.collection.get_active()
  6198. if obj is None:
  6199. self.inform.emit('[WARNING_NOTCL] %s' %
  6200. _("No object selected."))
  6201. msg = _("Please Select a Geometry object to export")
  6202. msgbox = QtWidgets.QMessageBox()
  6203. msgbox.setInformativeText(msg)
  6204. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6205. msgbox.setDefaultButton(bt_ok)
  6206. msgbox.exec_()
  6207. return
  6208. # Check for more compatible types and add as required
  6209. if (not isinstance(obj, FlatCAMGeometry)
  6210. and not isinstance(obj, FlatCAMGerber)
  6211. and not isinstance(obj, FlatCAMCNCjob)
  6212. and not isinstance(obj, FlatCAMExcellon)):
  6213. msg = '[ERROR_NOTCL] %s' % \
  6214. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6215. msgbox = QtWidgets.QMessageBox()
  6216. msgbox.setInformativeText(msg)
  6217. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6218. msgbox.setDefaultButton(bt_ok)
  6219. msgbox.exec_()
  6220. return
  6221. name = obj.options["name"]
  6222. _filter = "SVG File (*.svg);;All Files (*.*)"
  6223. try:
  6224. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6225. caption=_("Export SVG"),
  6226. directory=self.get_last_save_folder() + '/' + str(name),
  6227. filter=_filter)
  6228. except TypeError:
  6229. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6230. filename = str(filename)
  6231. if filename == "":
  6232. self.inform.emit('[WARNING_NOTCL]%s' %
  6233. _(" Export SVG cancelled."))
  6234. return
  6235. else:
  6236. self.export_svg(name, filename)
  6237. if self.defaults["global_open_style"] is False:
  6238. self.file_opened.emit("SVG", filename)
  6239. self.file_saved.emit("SVG", filename)
  6240. def on_file_exportpng(self):
  6241. self.report_usage("on_file_exportpng")
  6242. App.log.debug("on_file_exportpng()")
  6243. self.date = str(datetime.today()).rpartition('.')[0]
  6244. self.date = ''.join(c for c in self.date if c not in ':-')
  6245. self.date = self.date.replace(' ', '_')
  6246. image = _screenshot()
  6247. data = np.asarray(image)
  6248. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6249. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6250. _('Data must be a 3D array with last dimension 3 or 4'))
  6251. return
  6252. filter_ = "PNG File (*.png);;All Files (*.*)"
  6253. try:
  6254. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6255. caption=_("Export PNG Image"),
  6256. directory=self.get_last_save_folder() + '/png_' + self.date,
  6257. filter=filter_)
  6258. except TypeError:
  6259. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6260. filename = str(filename)
  6261. if filename == "":
  6262. self.inform.emit(_("Export PNG cancelled."))
  6263. return
  6264. else:
  6265. write_png(filename, data)
  6266. if self.defaults["global_open_style"] is False:
  6267. self.file_opened.emit("png", filename)
  6268. self.file_saved.emit("png", filename)
  6269. def on_file_savegerber(self):
  6270. """
  6271. Callback for menu item in Project context menu.
  6272. :return: None
  6273. """
  6274. self.report_usage("on_file_savegerber")
  6275. App.log.debug("on_file_savegerber()")
  6276. obj = self.collection.get_active()
  6277. if obj is None:
  6278. self.inform.emit('[WARNING_NOTCL] %s' %
  6279. _("No object selected. Please select an Gerber object to export."))
  6280. return
  6281. # Check for more compatible types and add as required
  6282. if not isinstance(obj, FlatCAMGerber):
  6283. self.inform.emit('[ERROR_NOTCL] %s' %
  6284. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6285. return
  6286. name = self.collection.get_active().options["name"]
  6287. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6288. try:
  6289. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6290. caption="Save Gerber source file",
  6291. directory=self.get_last_save_folder() + '/' + name,
  6292. filter=_filter)
  6293. except TypeError:
  6294. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  6295. filename = str(filename)
  6296. if filename == "":
  6297. self.inform.emit('[WARNING_NOTCL] %s' %
  6298. _("Save Gerber source file cancelled."))
  6299. return
  6300. else:
  6301. self.save_source_file(name, filename)
  6302. if self.defaults["global_open_style"] is False:
  6303. self.file_opened.emit("Gerber", filename)
  6304. self.file_saved.emit("Gerber", filename)
  6305. def on_file_saveexcellon(self):
  6306. """
  6307. Callback for menu item in project context menu.
  6308. :return: None
  6309. """
  6310. self.report_usage("on_file_saveexcellon")
  6311. App.log.debug("on_file_saveexcellon()")
  6312. obj = self.collection.get_active()
  6313. if obj is None:
  6314. self.inform.emit('[WARNING_NOTCL] %s' %
  6315. _("No object selected. Please select an Excellon object to export."))
  6316. return
  6317. # Check for more compatible types and add as required
  6318. if not isinstance(obj, FlatCAMExcellon):
  6319. self.inform.emit('[ERROR_NOTCL] %s' %
  6320. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6321. return
  6322. name = self.collection.get_active().options["name"]
  6323. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6324. try:
  6325. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6326. caption=_("Save Excellon source file"),
  6327. directory=self.get_last_save_folder() + '/' + name,
  6328. filter=_filter)
  6329. except TypeError:
  6330. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  6331. filename = str(filename)
  6332. if filename == "":
  6333. self.inform.emit('[WARNING_NOTCL] %s' %
  6334. _("Saving Excellon source file cancelled."))
  6335. return
  6336. else:
  6337. self.save_source_file(name, filename)
  6338. if self.defaults["global_open_style"] is False:
  6339. self.file_opened.emit("Excellon", filename)
  6340. self.file_saved.emit("Excellon", filename)
  6341. def on_file_exportexcellon(self):
  6342. """
  6343. Callback for menu item File->Export->Excellon.
  6344. :return: None
  6345. """
  6346. self.report_usage("on_file_exportexcellon")
  6347. App.log.debug("on_file_exportexcellon()")
  6348. obj = self.collection.get_active()
  6349. if obj is None:
  6350. self.inform.emit('[WARNING_NOTCL] %s' %
  6351. _("No object selected. Please Select an Excellon object to export."))
  6352. return
  6353. # Check for more compatible types and add as required
  6354. if not isinstance(obj, FlatCAMExcellon):
  6355. self.inform.emit('[ERROR_NOTCL] %s' %
  6356. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6357. return
  6358. name = self.collection.get_active().options["name"]
  6359. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6360. try:
  6361. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6362. caption=_("Export Excellon"),
  6363. directory=self.get_last_save_folder() + '/' + name,
  6364. filter=_filter)
  6365. except TypeError:
  6366. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  6367. filename = str(filename)
  6368. if filename == "":
  6369. self.inform.emit('[WARNING_NOTCL] %s' %
  6370. _("Export Excellon cancelled."))
  6371. return
  6372. else:
  6373. self.export_excellon(name, filename)
  6374. if self.defaults["global_open_style"] is False:
  6375. self.file_opened.emit("Excellon", filename)
  6376. self.file_saved.emit("Excellon", filename)
  6377. def on_file_exportgerber(self):
  6378. """
  6379. Callback for menu item File->Export->Gerber.
  6380. :return: None
  6381. """
  6382. self.report_usage("on_file_exportgerber")
  6383. App.log.debug("on_file_exportgerber()")
  6384. obj = self.collection.get_active()
  6385. if obj is None:
  6386. self.inform.emit('[WARNING_NOTCL] %s' %
  6387. _("No object selected. Please Select an Gerber object to export."))
  6388. return
  6389. # Check for more compatible types and add as required
  6390. if not isinstance(obj, FlatCAMGerber):
  6391. self.inform.emit('[ERROR_NOTCL] %s' %
  6392. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6393. return
  6394. name = self.collection.get_active().options["name"]
  6395. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  6396. try:
  6397. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6398. caption=_("Export Gerber"),
  6399. directory=self.get_last_save_folder() + '/' + name,
  6400. filter=_filter_)
  6401. except TypeError:
  6402. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  6403. filename = str(filename)
  6404. if filename == "":
  6405. self.inform.emit('[WARNING_NOTCL] %s' %
  6406. _("Export Gerber cancelled."))
  6407. return
  6408. else:
  6409. self.export_gerber(name, filename)
  6410. if self.defaults["global_open_style"] is False:
  6411. self.file_opened.emit("Gerber", filename)
  6412. self.file_saved.emit("Gerber", filename)
  6413. def on_file_exportdxf(self):
  6414. """
  6415. Callback for menu item File->Export DXF.
  6416. :return: None
  6417. """
  6418. self.report_usage("on_file_exportdxf")
  6419. App.log.debug("on_file_exportdxf()")
  6420. obj = self.collection.get_active()
  6421. if obj is None:
  6422. self.inform.emit('[WARNING_NOTCL] %s' %
  6423. _("No object selected."))
  6424. msg = _("Please Select a Geometry object to export")
  6425. msgbox = QtWidgets.QMessageBox()
  6426. msgbox.setInformativeText(msg)
  6427. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6428. msgbox.setDefaultButton(bt_ok)
  6429. msgbox.exec_()
  6430. return
  6431. # Check for more compatible types and add as required
  6432. if not isinstance(obj, FlatCAMGeometry):
  6433. msg = '[ERROR_NOTCL] %s' % \
  6434. _("Only Geometry objects can be used.")
  6435. msgbox = QtWidgets.QMessageBox()
  6436. msgbox.setInformativeText(msg)
  6437. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6438. msgbox.setDefaultButton(bt_ok)
  6439. msgbox.exec_()
  6440. return
  6441. name = self.collection.get_active().options["name"]
  6442. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6443. try:
  6444. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6445. caption=_("Export DXF"),
  6446. directory=self.get_last_save_folder() + '/' + name,
  6447. filter=_filter_)
  6448. except TypeError:
  6449. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  6450. filter=_filter_)
  6451. filename = str(filename)
  6452. if filename == "":
  6453. self.inform.emit('[WARNING_NOTCL] %s' %
  6454. _("Export DXF cancelled."))
  6455. return
  6456. else:
  6457. self.export_dxf(name, filename)
  6458. if self.defaults["global_open_style"] is False:
  6459. self.file_opened.emit("DXF", filename)
  6460. self.file_saved.emit("DXF", filename)
  6461. def on_file_importsvg(self, type_of_obj):
  6462. """
  6463. Callback for menu item File->Import SVG.
  6464. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6465. :type type_of_obj: str
  6466. :return: None
  6467. """
  6468. self.report_usage("on_file_importsvg")
  6469. App.log.debug("on_file_importsvg()")
  6470. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  6471. try:
  6472. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6473. directory=self.get_last_folder(), filter=_filter_)
  6474. except TypeError:
  6475. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6476. filter=_filter_)
  6477. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6478. type_of_obj = "geometry"
  6479. filenames = [str(filename) for filename in filenames]
  6480. if len(filenames) == 0:
  6481. self.inform.emit('[WARNING_NOTCL] %s' %
  6482. _("Open SVG cancelled."))
  6483. else:
  6484. for filename in filenames:
  6485. if filename != '':
  6486. self.worker_task.emit({'fcn': self.import_svg,
  6487. 'params': [filename, type_of_obj]})
  6488. def on_file_importdxf(self, type_of_obj):
  6489. """
  6490. Callback for menu item File->Import DXF.
  6491. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6492. :type type_of_obj: str
  6493. :return: None
  6494. """
  6495. self.report_usage("on_file_importdxf")
  6496. App.log.debug("on_file_importdxf()")
  6497. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6498. try:
  6499. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6500. directory=self.get_last_folder(),
  6501. filter=_filter_)
  6502. except TypeError:
  6503. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6504. filter=_filter_)
  6505. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6506. type_of_obj = "geometry"
  6507. filenames = [str(filename) for filename in filenames]
  6508. if len(filenames) == 0:
  6509. self.inform.emit('[WARNING_NOTCL] %s' %
  6510. _("Open DXF cancelled."))
  6511. else:
  6512. for filename in filenames:
  6513. if filename != '':
  6514. self.worker_task.emit({'fcn': self.import_dxf,
  6515. 'params': [filename, type_of_obj]})
  6516. # ###############################################################################################################
  6517. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6518. # ###############################################################################################################
  6519. def init_code_editor(self, name):
  6520. # Signals section
  6521. # Disconnect the old signals
  6522. try:
  6523. self.ui.buttonOpen.clicked.disconnect()
  6524. except TypeError:
  6525. pass
  6526. try:
  6527. self.ui.buttonSave.clicked.disconnect()
  6528. except TypeError:
  6529. pass
  6530. # add the tab if it was closed
  6531. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  6532. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  6533. # delete the absolute and relative position and messages in the infobar
  6534. self.ui.position_label.setText("")
  6535. self.ui.rel_position_label.setText("")
  6536. # first clear previous text in text editor (if any)
  6537. self.ui.code_editor.clear()
  6538. self.ui.code_editor.setReadOnly(False)
  6539. self.toggle_codeeditor = True
  6540. self.ui.code_editor.completer_enable = False
  6541. # Switch plot_area to CNCJob tab
  6542. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6543. def on_view_source(self):
  6544. self.inform.emit('%s' %
  6545. _("Viewing the source code of the selected object."))
  6546. self.proc_container.view.set_busy(_("Loading..."))
  6547. try:
  6548. obj = self.collection.get_active()
  6549. except Exception as e:
  6550. log.debug("App.on_view_source() --> %s" % str(e))
  6551. self.inform.emit('[WARNING_NOTCL] %s' %
  6552. _("Select an Gerber or Excellon file to view it's source file."))
  6553. return 'fail'
  6554. if obj.kind == 'gerber':
  6555. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  6556. else:
  6557. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  6558. self.init_code_editor(name=_("Source Editor"))
  6559. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6560. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6561. # then append the text from GCode to the text editor
  6562. try:
  6563. file = StringIO(obj.source_file)
  6564. except AttributeError:
  6565. self.inform.emit('[WARNING_NOTCL] %s' %
  6566. _("There is no selected object for which to see it's source file code."))
  6567. return 'fail'
  6568. self.ui.cncjob_frame.hide()
  6569. try:
  6570. for line in file:
  6571. QtWidgets.QApplication.processEvents()
  6572. proc_line = str(line).strip('\n')
  6573. self.ui.code_editor.append(proc_line)
  6574. except Exception as e:
  6575. log.debug('App.on_view_source() -->%s' % str(e))
  6576. self.inform.emit('[ERROR] %s: %s' %
  6577. (_('Failed to load the source code for the selected object'), str(e)))
  6578. return
  6579. self.handleTextChanged()
  6580. self.ui.cncjob_frame.show()
  6581. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6582. self.proc_container.view.set_idle()
  6583. # self.ui.show()
  6584. def on_toggle_code_editor(self):
  6585. self.report_usage("on_toggle_code_editor()")
  6586. if self.toggle_codeeditor is False:
  6587. self.init_code_editor(name=_("Code Editor"))
  6588. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  6589. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  6590. else:
  6591. for idx in range(self.ui.plot_tab_area.count()):
  6592. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  6593. self.ui.plot_tab_area.closeTab(idx)
  6594. break
  6595. self.toggle_codeeditor = False
  6596. def on_filenewscript(self):
  6597. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6598. self.init_code_editor(name=_("Script Editor"))
  6599. self.ui.code_editor.completer_enable = True
  6600. self.ui.code_editor.append(_(
  6601. "#\n"
  6602. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  6603. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  6604. "#\n\n"
  6605. "# FlatCAM commands list:\n"
  6606. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  6607. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  6608. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  6609. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  6610. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  6611. "# WriteGCode\n"
  6612. "#\n\n"
  6613. ))
  6614. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6615. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6616. self.handleTextChanged()
  6617. self.ui.code_editor.show()
  6618. def on_fileopenscript(self):
  6619. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6620. try:
  6621. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  6622. directory=self.get_last_folder(), filter=_filter_)
  6623. except TypeError:
  6624. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  6625. # The Qt methods above will return a QString which can cause problems later.
  6626. # So far json.dump() will fail to serialize it.
  6627. # TODO: Improve the serialization methods and remove this fix.
  6628. filename = str(filename)
  6629. if filename == "":
  6630. self.inform.emit('[WARNING_NOTCL] %s' %
  6631. _("Open TCL script cancelled."))
  6632. else:
  6633. self.on_filenewscript()
  6634. try:
  6635. with open(filename, "r") as opened_script:
  6636. try:
  6637. for line in opened_script:
  6638. proc_line = str(line).strip('\n')
  6639. self.ui.code_editor.append(proc_line)
  6640. except Exception as e:
  6641. log.debug('App.on_fileopenscript() -->%s' % str(e))
  6642. self.inform.emit('[ERROR] %s %s' %
  6643. (_('App.on_fileopenscript() -->'), str(e)))
  6644. return
  6645. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6646. self.handleTextChanged()
  6647. self.ui.show()
  6648. except Exception as e:
  6649. log.debug("App.on_fileopenscript() -> %s" % str(e))
  6650. def on_filerunscript(self, name=None):
  6651. """
  6652. File menu callback for loading and running a TCL script.
  6653. :return: None
  6654. """
  6655. self.report_usage("on_filerunscript")
  6656. App.log.debug("on_file_runscript()")
  6657. if name:
  6658. filename = name
  6659. else:
  6660. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6661. try:
  6662. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6663. directory=self.get_last_folder(), filter=_filter_)
  6664. except TypeError:
  6665. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6666. # The Qt methods above will return a QString which can cause problems later.
  6667. # So far json.dump() will fail to serialize it.
  6668. # TODO: Improve the serialization methods and remove this fix.
  6669. filename = str(filename)
  6670. if filename == "":
  6671. self.inform.emit('[WARNING_NOTCL] %s' %
  6672. _("Run TCL script cancelled."))
  6673. else:
  6674. try:
  6675. with open(filename, "r") as tcl_script:
  6676. cmd_line_shellfile_content = tcl_script.read()
  6677. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  6678. except Exception as e:
  6679. log.debug("App.on_filerunscript() -> %s" % str(e))
  6680. sys.exit(2)
  6681. def on_file_saveproject(self):
  6682. """
  6683. Callback for menu item File->Save Project. Saves the project to
  6684. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6685. if set to None. The project is saved by calling ``self.save_project()``.
  6686. :return: None
  6687. """
  6688. self.report_usage("on_file_saveproject")
  6689. if self.project_filename is None:
  6690. self.on_file_saveprojectas()
  6691. else:
  6692. self.worker_task.emit({'fcn': self.save_project,
  6693. 'params': [self.project_filename]})
  6694. if self.defaults["global_open_style"] is False:
  6695. self.file_opened.emit("project", self.project_filename)
  6696. self.file_saved.emit("project", self.project_filename)
  6697. self.set_ui_title(name=self.project_filename)
  6698. self.should_we_save = False
  6699. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6700. """
  6701. Callback for menu item File->Save Project As... Opens a file
  6702. chooser and saves the project to the given file via
  6703. ``self.save_project()``.
  6704. :param make_copy if to be create a copy of the project; boolean
  6705. :param use_thread: if to be run in a separate thread; boolean
  6706. :param quit_action: if to be followed by quiting the application; boolean
  6707. :return: None
  6708. """
  6709. self.report_usage("on_file_saveprojectas")
  6710. self.date = str(datetime.today()).rpartition('.')[0]
  6711. self.date = ''.join(c for c in self.date if c not in ':-')
  6712. self.date = self.date.replace(' ', '_')
  6713. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  6714. try:
  6715. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6716. caption=_("Save Project As ..."),
  6717. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  6718. filter=filter_)
  6719. except TypeError:
  6720. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  6721. filename = str(filename)
  6722. if filename == '':
  6723. self.inform.emit('[WARNING_NOTCL] %s' %
  6724. _("Save Project cancelled."))
  6725. return
  6726. try:
  6727. f = open(filename, 'r')
  6728. f.close()
  6729. except IOError:
  6730. pass
  6731. if use_thread is True:
  6732. self.worker_task.emit({'fcn': self.save_project,
  6733. 'params': [filename, quit_action]})
  6734. else:
  6735. self.save_project(filename, quit_action)
  6736. # self.save_project(filename)
  6737. if self.defaults["global_open_style"] is False:
  6738. self.file_opened.emit("project", filename)
  6739. self.file_saved.emit("project", filename)
  6740. if not make_copy:
  6741. self.project_filename = filename
  6742. self.set_ui_title(name=self.project_filename)
  6743. self.should_we_save = False
  6744. def export_svg(self, obj_name, filename, scale_factor=0.00):
  6745. """
  6746. Exports a Geometry Object to an SVG file.
  6747. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6748. :param filename: Path to the SVG file to save to.
  6749. :param scale_factor: factor by which to change/scale the thickness of the features
  6750. :return:
  6751. """
  6752. self.report_usage("export_svg()")
  6753. if filename is None:
  6754. filename = self.defaults["global_last_save_folder"]
  6755. self.log.debug("export_svg()")
  6756. try:
  6757. obj = self.collection.get_by_name(str(obj_name))
  6758. except:
  6759. # TODO: The return behavior has not been established... should raise exception?
  6760. return "Could not retrieve object: %s" % obj_name
  6761. with self.proc_container.new(_("Exporting SVG")) as proc:
  6762. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6763. # Determine bounding area for svg export
  6764. bounds = obj.bounds()
  6765. size = obj.size()
  6766. # Convert everything to strings for use in the xml doc
  6767. svgwidth = str(size[0])
  6768. svgheight = str(size[1])
  6769. minx = str(bounds[0])
  6770. miny = str(bounds[1] - size[1])
  6771. uom = obj.units.lower()
  6772. # Add a SVG Header and footer to the svg output from shapely
  6773. # The transform flips the Y Axis so that everything renders
  6774. # properly within svg apps such as inkscape
  6775. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6776. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6777. svg_header += 'width="' + svgwidth + uom + '" '
  6778. svg_header += 'height="' + svgheight + uom + '" '
  6779. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6780. svg_header += '<g transform="scale(1,-1)">'
  6781. svg_footer = '</g> </svg>'
  6782. svg_elem = svg_header + exported_svg + svg_footer
  6783. # Parse the xml through a xml parser just to add line feeds
  6784. # and to make it look more pretty for the output
  6785. svgcode = parse_xml_string(svg_elem)
  6786. try:
  6787. with open(filename, 'w') as fp:
  6788. fp.write(svgcode.toprettyxml())
  6789. except PermissionError:
  6790. self.inform.emit('[WARNING] %s' %
  6791. _("Permission denied, saving not possible.\n"
  6792. "Most likely another app is holding the file open and not accessible."))
  6793. return 'fail'
  6794. if self.defaults["global_open_style"] is False:
  6795. self.file_opened.emit("SVG", filename)
  6796. self.file_saved.emit("SVG", filename)
  6797. self.inform.emit('[success] %s: %s' %
  6798. (_("SVG file exported to"), filename))
  6799. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  6800. """
  6801. Exports a Geometry Object to an SVG file in negative.
  6802. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6803. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6804. :param filename: Path to the SVG file to save to.
  6805. :param boundary: thickness of a black border to surround all the features
  6806. :param scale_factor: factor by which to change/scale the thickness of the features
  6807. :param use_thread: if to be run in a separate thread; boolean
  6808. :return:
  6809. """
  6810. self.report_usage("export_negative()")
  6811. if filename is None:
  6812. filename = self.defaults["global_last_save_folder"]
  6813. self.log.debug("export_svg() negative")
  6814. try:
  6815. obj = self.collection.get_by_name(str(obj_name))
  6816. except:
  6817. # TODO: The return behavior has not been established... should raise exception?
  6818. return "Could not retrieve object: %s" % obj_name
  6819. try:
  6820. box = self.collection.get_by_name(str(box_name))
  6821. except:
  6822. # TODO: The return behavior has not been established... should raise exception?
  6823. return "Could not retrieve object: %s" % box_name
  6824. if box is None:
  6825. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  6826. (_("No object Box. Using instead"), obj))
  6827. box = obj
  6828. def make_negative_film():
  6829. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6830. self.progress.emit(40)
  6831. # Determine bounding area for svg export
  6832. bounds = box.bounds()
  6833. size = box.size()
  6834. uom = obj.units.lower()
  6835. # Convert everything to strings for use in the xml doc
  6836. svgwidth = str(size[0] + (2 * boundary))
  6837. svgheight = str(size[1] + (2 * boundary))
  6838. minx = str(bounds[0] - boundary)
  6839. miny = str(bounds[1] + boundary + size[1])
  6840. miny_rect = str(bounds[1] - boundary)
  6841. # Add a SVG Header and footer to the svg output from shapely
  6842. # The transform flips the Y Axis so that everything renders
  6843. # properly within svg apps such as inkscape
  6844. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6845. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6846. svg_header += 'width="' + svgwidth + uom + '" '
  6847. svg_header += 'height="' + svgheight + uom + '" '
  6848. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6849. svg_header += '>'
  6850. svg_header += '<g transform="scale(1,-1)">'
  6851. svg_footer = '</g> </svg>'
  6852. self.progress.emit(60)
  6853. # Change the attributes of the exported SVG
  6854. # We don't need stroke-width - wrong, we do when we have lines with certain width
  6855. # We set opacity to maximum
  6856. # We set the color to WHITE
  6857. root = ET.fromstring(exported_svg)
  6858. for child in root:
  6859. child.set('fill', '#FFFFFF')
  6860. child.set('opacity', '1.0')
  6861. child.set('stroke', '#FFFFFF')
  6862. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  6863. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  6864. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  6865. first_svg_elem_tag = 'rect'
  6866. first_svg_elem_attribs = {
  6867. 'x': minx,
  6868. 'y': miny_rect,
  6869. 'width': svgwidth,
  6870. 'height': svgheight,
  6871. 'id': 'neg_rect',
  6872. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  6873. }
  6874. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  6875. exported_svg = ET.tostring(root)
  6876. svg_elem = svg_header + str(exported_svg) + svg_footer
  6877. self.progress.emit(80)
  6878. # Parse the xml through a xml parser just to add line feeds
  6879. # and to make it look more pretty for the output
  6880. doc = parse_xml_string(svg_elem)
  6881. try:
  6882. with open(filename, 'w') as fp:
  6883. fp.write(doc.toprettyxml())
  6884. except PermissionError:
  6885. self.inform.emit('[WARNING] %s' %
  6886. _("Permission denied, saving not possible.\n"
  6887. "Most likely another app is holding the file open and not accessible."))
  6888. return 'fail'
  6889. self.progress.emit(100)
  6890. if self.defaults["global_open_style"] is False:
  6891. self.file_opened.emit("SVG", filename)
  6892. self.file_saved.emit("SVG", filename)
  6893. self.inform.emit('[success] %s: %s' %
  6894. (_("SVG file exported to"), filename))
  6895. if use_thread is True:
  6896. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6897. def job_thread_film(app_obj):
  6898. try:
  6899. make_negative_film()
  6900. except Exception as e:
  6901. proc.done()
  6902. return
  6903. proc.done()
  6904. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6905. else:
  6906. make_negative_film()
  6907. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  6908. """
  6909. Exports a Geometry Object to an SVG file in positive black.
  6910. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6911. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6912. :param filename: Path to the SVG file to save to.
  6913. :param scale_factor: factor by which to change/scale the thickness of the features
  6914. :param use_thread: if to be run in a separate thread; boolean
  6915. :return:
  6916. """
  6917. self.report_usage("export_svg_black()")
  6918. if filename is None:
  6919. filename = self.defaults["global_last_save_folder"]
  6920. self.log.debug("export_svg() black")
  6921. try:
  6922. obj = self.collection.get_by_name(str(obj_name))
  6923. except:
  6924. # TODO: The return behavior has not been established... should raise exception?
  6925. return "Could not retrieve object: %s" % obj_name
  6926. try:
  6927. box = self.collection.get_by_name(str(box_name))
  6928. except:
  6929. # TODO: The return behavior has not been established... should raise exception?
  6930. return "Could not retrieve object: %s" % box_name
  6931. if box is None:
  6932. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  6933. (_("No object Box. Using instead"), obj))
  6934. box = obj
  6935. def make_black_film():
  6936. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6937. self.progress.emit(40)
  6938. # Change the attributes of the exported SVG
  6939. # We don't need stroke-width
  6940. # We set opacity to maximum
  6941. # We set the colour to WHITE
  6942. root = ET.fromstring(exported_svg)
  6943. for child in root:
  6944. child.set('fill', '#000000')
  6945. child.set('opacity', '1.0')
  6946. child.set('stroke', '#000000')
  6947. exported_svg = ET.tostring(root)
  6948. # Determine bounding area for svg export
  6949. bounds = box.bounds()
  6950. size = box.size()
  6951. # This contain the measure units
  6952. uom = obj.units.lower()
  6953. # Define a boundary around SVG of about 1.0mm (~39mils)
  6954. if uom in "mm":
  6955. boundary = 1.0
  6956. else:
  6957. boundary = 0.0393701
  6958. self.progress.emit(80)
  6959. # Convert everything to strings for use in the xml doc
  6960. svgwidth = str(size[0] + (2 * boundary))
  6961. svgheight = str(size[1] + (2 * boundary))
  6962. minx = str(bounds[0] - boundary)
  6963. miny = str(bounds[1] + boundary + size[1])
  6964. self.log.debug(minx)
  6965. self.log.debug(miny)
  6966. # Add a SVG Header and footer to the svg output from shapely
  6967. # The transform flips the Y Axis so that everything renders
  6968. # properly within svg apps such as inkscape
  6969. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6970. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6971. svg_header += 'width="' + svgwidth + uom + '" '
  6972. svg_header += 'height="' + svgheight + uom + '" '
  6973. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6974. svg_header += '>'
  6975. svg_header += '<g transform="scale(1,-1)">'
  6976. svg_footer = '</g> </svg>'
  6977. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  6978. self.progress.emit(90)
  6979. # Parse the xml through a xml parser just to add line feeds
  6980. # and to make it look more pretty for the output
  6981. doc = parse_xml_string(svg_elem)
  6982. try:
  6983. with open(filename, 'w') as fp:
  6984. fp.write(doc.toprettyxml())
  6985. except PermissionError:
  6986. self.inform.emit('[WARNING] %s' %
  6987. _("Permission denied, saving not possible.\n"
  6988. "Most likely another app is holding the file open and not accessible."))
  6989. return 'fail'
  6990. self.progress.emit(100)
  6991. if self.defaults["global_open_style"] is False:
  6992. self.file_opened.emit("SVG", filename)
  6993. self.file_saved.emit("SVG", filename)
  6994. self.inform.emit('[success] %s: %s' %
  6995. (_("SVG file exported to"), filename))
  6996. if use_thread is True:
  6997. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6998. def job_thread_film(app_obj):
  6999. try:
  7000. make_black_film()
  7001. except Exception as e:
  7002. proc.done()
  7003. return
  7004. proc.done()
  7005. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7006. else:
  7007. make_black_film()
  7008. def save_source_file(self, obj_name, filename, use_thread=True):
  7009. """
  7010. Exports a FlatCAM Object to an Gerber/Excellon file.
  7011. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7012. :param filename: Path to the Gerber file to save to.
  7013. :param use_thread: if to be run in a separate thread
  7014. :return:
  7015. """
  7016. self.report_usage("save source file()")
  7017. if filename is None:
  7018. filename = self.defaults["global_last_save_folder"]
  7019. self.log.debug("save source file()")
  7020. obj = self.collection.get_by_name(obj_name)
  7021. file_string = StringIO(obj.source_file)
  7022. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7023. try:
  7024. with open(filename, 'w') as file:
  7025. file.writelines('G04*\n')
  7026. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7027. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7028. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7029. file.writelines('G04 Created on : %s*\n' % time_string)
  7030. for line in file_string:
  7031. file.writelines(line)
  7032. except PermissionError:
  7033. self.inform.emit('[WARNING] %s' %
  7034. _("Permission denied, saving not possible.\n"
  7035. "Most likely another app is holding the file open and not accessible."))
  7036. return 'fail'
  7037. def export_excellon(self, obj_name, filename, use_thread=True):
  7038. """
  7039. Exports a Excellon Object to an Excellon file.
  7040. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7041. :param filename: Path to the Excellon file to save to.
  7042. :param use_thread: if to be run in a separate thread
  7043. :return:
  7044. """
  7045. self.report_usage("export_excellon()")
  7046. if filename is None:
  7047. filename = self.defaults["global_last_save_folder"]
  7048. self.log.debug("export_excellon()")
  7049. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7050. self.defaults["excellon_exp_decimals"]
  7051. )
  7052. units = ''
  7053. try:
  7054. obj = self.collection.get_by_name(str(obj_name))
  7055. except:
  7056. # TODO: The return behavior has not been established... should raise exception?
  7057. return "Could not retrieve object: %s" % obj_name
  7058. # updated units
  7059. eunits = self.defaults["excellon_exp_units"]
  7060. ewhole = self.defaults["excellon_exp_integer"]
  7061. efract = self.defaults["excellon_exp_decimals"]
  7062. ezeros = self.defaults["excellon_exp_zeros"]
  7063. eformat = self.defaults["excellon_exp_format"]
  7064. slot_type = self.defaults["excellon_exp_slot_type"]
  7065. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7066. if fc_units == 'MM':
  7067. factor = 1 if eunits == 'METRIC' else 0.03937
  7068. else:
  7069. factor = 25.4 if eunits == 'METRIC' else 1
  7070. def make_excellon():
  7071. try:
  7072. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7073. header = 'M48\n'
  7074. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7075. (str(self.version), str(self.version_date))
  7076. header += ';Filename: %s' % str(obj_name) + '\n'
  7077. header += ';Created on : %s' % time_str + '\n'
  7078. if eformat == 'dec':
  7079. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7080. header += eunits + '\n'
  7081. for tool in obj.tools:
  7082. if eunits == 'METRIC':
  7083. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7084. tool=str(tool),
  7085. dec=2)
  7086. else:
  7087. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7088. tool=str(tool),
  7089. dec=4)
  7090. else:
  7091. if ezeros == 'LZ':
  7092. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7093. form='ndec', e_zeros='LZ', factor=factor,
  7094. slot_type=slot_type)
  7095. header += '%s,%s\n' % (eunits, 'LZ')
  7096. header += format_exc
  7097. for tool in obj.tools:
  7098. if eunits == 'METRIC':
  7099. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7100. tool=str(tool),
  7101. dec=2)
  7102. else:
  7103. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7104. tool=str(tool),
  7105. dec=4)
  7106. else:
  7107. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7108. form='ndec', e_zeros='TZ', factor=factor,
  7109. slot_type=slot_type)
  7110. header += '%s,%s\n' % (eunits, 'TZ')
  7111. header += format_exc
  7112. for tool in obj.tools:
  7113. if eunits == 'METRIC':
  7114. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7115. tool=str(tool),
  7116. dec=2)
  7117. else:
  7118. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7119. tool=str(tool),
  7120. dec=4)
  7121. header += '%\n'
  7122. footer = 'M30\n'
  7123. exported_excellon = header
  7124. exported_excellon += excellon_code
  7125. exported_excellon += footer
  7126. try:
  7127. with open(filename, 'w') as fp:
  7128. fp.write(exported_excellon)
  7129. except PermissionError:
  7130. self.inform.emit('[WARNING] %s' %
  7131. _("Permission denied, saving not possible.\n"
  7132. "Most likely another app is holding the file open and not accessible."))
  7133. return 'fail'
  7134. if self.defaults["global_open_style"] is False:
  7135. self.file_opened.emit("Excellon", filename)
  7136. self.file_saved.emit("Excellon", filename)
  7137. self.inform.emit('[success] %s: %s' %
  7138. (_("Excellon file exported to"), filename))
  7139. except Exception as e:
  7140. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7141. return 'fail'
  7142. if use_thread is True:
  7143. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7144. def job_thread_exc(app_obj):
  7145. ret = make_excellon()
  7146. if ret == 'fail':
  7147. self.inform.emit('[ERROR_NOTCL] %s' %
  7148. _('Could not export Excellon file.'))
  7149. return
  7150. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7151. else:
  7152. ret = make_excellon()
  7153. if ret == 'fail':
  7154. self.inform.emit('[ERROR_NOTCL] %s' %
  7155. _('Could not export Excellon file.'))
  7156. return
  7157. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7158. """
  7159. Exports a Gerber Object to an Gerber file.
  7160. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7161. :param filename: Path to the Gerber file to save to.
  7162. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7163. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7164. :param use_thread: if to be run in a separate thread
  7165. :return:
  7166. """
  7167. self.report_usage("export_gerber()")
  7168. if filename is None:
  7169. filename = self.defaults["global_last_save_folder"]
  7170. self.log.debug("export_gerber()")
  7171. if local_use is None:
  7172. try:
  7173. obj = self.collection.get_by_name(str(obj_name))
  7174. except:
  7175. # TODO: The return behavior has not been established... should raise exception?
  7176. return "Could not retrieve object: %s" % obj_name
  7177. else:
  7178. obj = local_use
  7179. # updated units
  7180. gunits = self.defaults["gerber_exp_units"]
  7181. gwhole = self.defaults["gerber_exp_integer"]
  7182. gfract = self.defaults["gerber_exp_decimals"]
  7183. gzeros = self.defaults["gerber_exp_zeros"]
  7184. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7185. if fc_units == 'MM':
  7186. factor = 1 if gunits == 'MM' else 0.03937
  7187. else:
  7188. factor = 25.4 if gunits == 'MM' else 1
  7189. def make_gerber():
  7190. try:
  7191. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7192. header = 'G04*\n'
  7193. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7194. (str(self.version), str(self.version_date))
  7195. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7196. header += 'G04 Created on : %s*' % time_str + '\n'
  7197. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7198. header += "%MO{units}*%\n".format(units=gunits)
  7199. for apid in obj.apertures:
  7200. if obj.apertures[apid]['type'] == 'C':
  7201. header += "%ADD{apid}{type},{size}*%\n".format(
  7202. apid=str(apid),
  7203. type='C',
  7204. size=(factor * obj.apertures[apid]['size'])
  7205. )
  7206. elif obj.apertures[apid]['type'] == 'R':
  7207. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7208. apid=str(apid),
  7209. type='R',
  7210. width=(factor * obj.apertures[apid]['width']),
  7211. height=(factor * obj.apertures[apid]['height'])
  7212. )
  7213. elif obj.apertures[apid]['type'] == 'O':
  7214. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7215. apid=str(apid),
  7216. type='O',
  7217. width=(factor * obj.apertures[apid]['width']),
  7218. height=(factor * obj.apertures[apid]['height'])
  7219. )
  7220. header += '\n'
  7221. # obsolete units but some software may need it
  7222. if gunits == 'IN':
  7223. header += 'G70*\n'
  7224. else:
  7225. header += 'G71*\n'
  7226. # Absolute Mode
  7227. header += 'G90*\n'
  7228. header += 'G01*\n'
  7229. # positive polarity
  7230. header += '%LPD*%\n'
  7231. footer = 'M02*\n'
  7232. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7233. exported_gerber = header
  7234. exported_gerber += gerber_code
  7235. exported_gerber += footer
  7236. if local_use is None:
  7237. try:
  7238. with open(filename, 'w') as fp:
  7239. fp.write(exported_gerber)
  7240. except PermissionError:
  7241. self.inform.emit('[WARNING] %s' %
  7242. _("Permission denied, saving not possible.\n"
  7243. "Most likely another app is holding the file open and not accessible."))
  7244. return 'fail'
  7245. if self.defaults["global_open_style"] is False:
  7246. self.file_opened.emit("Gerber", filename)
  7247. self.file_saved.emit("Gerber", filename)
  7248. self.inform.emit('[success] %s: %s' %
  7249. (_("Gerber file exported to"), filename))
  7250. else:
  7251. return exported_gerber
  7252. except Exception as e:
  7253. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7254. return 'fail'
  7255. if use_thread is True:
  7256. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7257. def job_thread_grb(app_obj):
  7258. ret = make_gerber()
  7259. if ret == 'fail':
  7260. self.inform.emit('[ERROR_NOTCL] %s' %
  7261. _('Could not export Gerber file.'))
  7262. return
  7263. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7264. else:
  7265. ret = make_gerber()
  7266. if ret == 'fail':
  7267. self.inform.emit('[ERROR_NOTCL] %s' %
  7268. _('Could not export Gerber file.'))
  7269. return 'fail'
  7270. if local_use is not None:
  7271. return ret
  7272. def export_dxf(self, obj_name, filename, use_thread=True):
  7273. """
  7274. Exports a Geometry Object to an DXF file.
  7275. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7276. :param filename: Path to the DXF file to save to.
  7277. :param use_thread: if to be run in a separate thread
  7278. :return:
  7279. """
  7280. self.report_usage("export_dxf()")
  7281. if filename is None:
  7282. filename = self.defaults["global_last_save_folder"]
  7283. self.log.debug("export_dxf()")
  7284. format_exc = ''
  7285. units = ''
  7286. try:
  7287. obj = self.collection.get_by_name(str(obj_name))
  7288. except:
  7289. # TODO: The return behavior has not been established... should raise exception?
  7290. return "Could not retrieve object: %s" % obj_name
  7291. # updated units
  7292. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7293. if units == 'IN' or units == 'INCH':
  7294. units = 'INCH'
  7295. elif units == 'MM' or units == 'METIRC':
  7296. units ='METRIC'
  7297. def make_dxf():
  7298. try:
  7299. dxf_code = obj.export_dxf()
  7300. dxf_code.saveas(filename)
  7301. if self.defaults["global_open_style"] is False:
  7302. self.file_opened.emit("DXF", filename)
  7303. self.file_saved.emit("DXF", filename)
  7304. self.inform.emit('[success] %s: %s' %
  7305. (_("DXF file exported to"), filename))
  7306. except:
  7307. return 'fail'
  7308. if use_thread is True:
  7309. with self.proc_container.new(_("Exporting DXF")) as proc:
  7310. def job_thread_exc(app_obj):
  7311. ret = make_dxf()
  7312. if ret == 'fail':
  7313. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  7314. _('Could not export DXF file.'))
  7315. return
  7316. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7317. else:
  7318. ret = make_dxf()
  7319. if ret == 'fail':
  7320. self.inform.emit('[WARNING_NOTCL] %s' %
  7321. _('Could not export DXF file.'))
  7322. return
  7323. def import_svg(self, filename, geo_type='geometry', outname=None):
  7324. """
  7325. Adds a new Geometry Object to the projects and populates
  7326. it with shapes extracted from the SVG file.
  7327. :param filename: Path to the SVG file.
  7328. :param outname:
  7329. :return:
  7330. """
  7331. self.report_usage("import_svg()")
  7332. obj_type = ""
  7333. if geo_type is None or geo_type == "geometry":
  7334. obj_type = "geometry"
  7335. elif geo_type == "gerber":
  7336. obj_type = geo_type
  7337. else:
  7338. self.inform.emit('[ERROR_NOTCL] %s' %
  7339. _("Not supported type is picked as parameter. "
  7340. "Only Geometry and Gerber are supported"))
  7341. return
  7342. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7343. def obj_init(geo_obj, app_obj):
  7344. geo_obj.import_svg(filename, obj_type, units=units)
  7345. geo_obj.multigeo = False
  7346. with self.proc_container.new(_("Importing SVG")) as proc:
  7347. # Object name
  7348. name = outname or filename.split('/')[-1].split('\\')[-1]
  7349. self.new_object(obj_type, name, obj_init, autoselected=False)
  7350. self.progress.emit(20)
  7351. # Register recent file
  7352. self.file_opened.emit("svg", filename)
  7353. # GUI feedback
  7354. self.inform.emit('[success] %s: %s' %
  7355. (_("Opened"), filename))
  7356. self.progress.emit(100)
  7357. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7358. """
  7359. Adds a new Geometry Object to the projects and populates
  7360. it with shapes extracted from the DXF file.
  7361. :param filename: Path to the DXF file.
  7362. :param outname:
  7363. :type putname: str
  7364. :return:
  7365. """
  7366. self.report_usage("import_dxf()")
  7367. obj_type = ""
  7368. if geo_type is None or geo_type == "geometry":
  7369. obj_type = "geometry"
  7370. elif geo_type == "gerber":
  7371. obj_type = geo_type
  7372. else:
  7373. self.inform.emit('[ERROR_NOTCL] %s' %
  7374. _("Not supported type is picked as parameter. "
  7375. "Only Geometry and Gerber are supported"))
  7376. return
  7377. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7378. def obj_init(geo_obj, app_obj):
  7379. geo_obj.import_dxf(filename, obj_type, units=units)
  7380. geo_obj.multigeo = False
  7381. with self.proc_container.new(_("Importing DXF")) as proc:
  7382. # Object name
  7383. name = outname or filename.split('/')[-1].split('\\')[-1]
  7384. self.new_object(obj_type, name, obj_init, autoselected=False)
  7385. self.progress.emit(20)
  7386. # Register recent file
  7387. self.file_opened.emit("dxf", filename)
  7388. # GUI feedback
  7389. self.inform.emit('[success] %s: %s' %
  7390. (_("Opened"), filename))
  7391. self.progress.emit(100)
  7392. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  7393. """
  7394. Adds a new Geometry Object to the projects and populates
  7395. it with shapes extracted from the SVG file.
  7396. :param filename: Path to the SVG file.
  7397. :param o_type: type of FlatCAM objeect
  7398. :param dpi: dot per inch
  7399. :param mode: black or color
  7400. :param mask: dictate the level of detail
  7401. :param outname: name for the resulting file
  7402. :return:
  7403. """
  7404. self.report_usage("import_image()")
  7405. if o_type is None or o_type == "geometry":
  7406. obj_type = "geometry"
  7407. elif o_type == "gerber":
  7408. obj_type = o_type
  7409. else:
  7410. self.inform.emit('[ERROR_NOTCL] %s' %
  7411. _("Not supported type is picked as parameter. "
  7412. "Only Geometry and Gerber are supported"))
  7413. return
  7414. def obj_init(geo_obj, app_obj):
  7415. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  7416. geo_obj.multigeo = False
  7417. with self.proc_container.new(_("Importing Image")) as proc:
  7418. # Object name
  7419. name = outname or filename.split('/')[-1].split('\\')[-1]
  7420. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  7421. self.new_object(obj_type, name, obj_init)
  7422. self.progress.emit(20)
  7423. # Register recent file
  7424. self.file_opened.emit("image", filename)
  7425. # GUI feedback
  7426. self.inform.emit('[success] %s: %s' %
  7427. (_("Opened"), filename))
  7428. self.progress.emit(100)
  7429. def open_gerber(self, filename, outname=None):
  7430. """
  7431. Opens a Gerber file, parses it and creates a new object for
  7432. it in the program. Thread-safe.
  7433. :param outname: Name of the resulting object. None causes the
  7434. name to be that of the file.
  7435. :param filename: Gerber file filename
  7436. :type filename: str
  7437. :param follow: If true, the parser will not create polygons, just lines
  7438. following the gerber path.
  7439. :type follow: bool
  7440. :return: None
  7441. """
  7442. # How the object should be initialized
  7443. def obj_init(gerber_obj, app_obj):
  7444. assert isinstance(gerber_obj, FlatCAMGerber), \
  7445. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  7446. # Opening the file happens here
  7447. self.progress.emit(30)
  7448. try:
  7449. gerber_obj.parse_file(filename)
  7450. except IOError:
  7451. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7452. (_("Failed to open file"), filename))
  7453. app_obj.progress.emit(0)
  7454. return "fail"
  7455. except ParseError as err:
  7456. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  7457. (_("Failed to parse file"), filename, str(err)))
  7458. app_obj.progress.emit(0)
  7459. self.log.error(str(err))
  7460. return "fail"
  7461. except Exception as e:
  7462. log.debug("App.open_gerber() --> %s" % str(e))
  7463. msg = '[ERROR] %s' % \
  7464. _("An internal error has occurred. See shell.\n")
  7465. msg += traceback.format_exc()
  7466. app_obj.inform.emit(msg)
  7467. return "fail"
  7468. if gerber_obj.is_empty():
  7469. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  7470. # self.collection.set_active(gerber_obj.options["name"])
  7471. # self.collection.delete_active()
  7472. self.inform.emit('[ERROR_NOTCL] %s' %
  7473. _("Object is not Gerber file or empty. Aborting object creation."))
  7474. return "fail"
  7475. # Further parsing
  7476. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  7477. App.log.debug("open_gerber()")
  7478. with self.proc_container.new(_("Opening Gerber")) as proc:
  7479. self.progress.emit(10)
  7480. # Object name
  7481. name = outname or filename.split('/')[-1].split('\\')[-1]
  7482. # # ## Object creation # ##
  7483. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7484. if ret == 'fail':
  7485. self.inform.emit('[ERROR_NOTCL]%s' %
  7486. _(' Open Gerber failed. Probable not a Gerber file.'))
  7487. return
  7488. # Register recent file
  7489. self.file_opened.emit("gerber", filename)
  7490. self.progress.emit(100)
  7491. # GUI feedback
  7492. self.inform.emit('[success] %s: %s' %
  7493. (_("Opened"), filename))
  7494. def open_excellon(self, filename, outname=None):
  7495. """
  7496. Opens an Excellon file, parses it and creates a new object for
  7497. it in the program. Thread-safe.
  7498. :param outname: Name of the resulting object. None causes the
  7499. name to be that of the file.
  7500. :param filename: Excellon file filename
  7501. :type filename: str
  7502. :return: None
  7503. """
  7504. App.log.debug("open_excellon()")
  7505. # How the object should be initialized
  7506. def obj_init(excellon_obj, app_obj):
  7507. # self.progress.emit(20)
  7508. try:
  7509. ret = excellon_obj.parse_file(filename=filename)
  7510. if ret == "fail":
  7511. log.debug("Excellon parsing failed.")
  7512. self.inform.emit('[ERROR_NOTCL] %s' %
  7513. _("This is not Excellon file."))
  7514. return "fail"
  7515. except IOError:
  7516. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7517. (_("Cannot open file"), filename))
  7518. log.debug("Could not open Excellon object.")
  7519. self.progress.emit(0) # TODO: self and app_bjj mixed
  7520. return "fail"
  7521. except:
  7522. msg = '[ERROR_NOTCL] %s' % \
  7523. _("An internal error has occurred. See shell.\n")
  7524. msg += traceback.format_exc()
  7525. app_obj.inform.emit(msg)
  7526. return "fail"
  7527. ret = excellon_obj.create_geometry()
  7528. if ret == 'fail':
  7529. log.debug("Could not create geometry for Excellon object.")
  7530. return "fail"
  7531. for tool in excellon_obj.tools:
  7532. if excellon_obj.tools[tool]['solid_geometry']:
  7533. return
  7534. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7535. (_("No geometry found in file"), filename))
  7536. return "fail"
  7537. with self.proc_container.new(_("Opening Excellon.")):
  7538. # Object name
  7539. name = outname or filename.split('/')[-1].split('\\')[-1]
  7540. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  7541. if ret_val == 'fail':
  7542. self.inform.emit('[ERROR_NOTCL] %s' %
  7543. _('Open Excellon file failed. Probable not an Excellon file.'))
  7544. return
  7545. # Register recent file
  7546. self.file_opened.emit("excellon", filename)
  7547. # GUI feedback
  7548. self.inform.emit('[success] %s: %s' %
  7549. (_("Opened"), filename))
  7550. def open_gcode(self, filename, outname=None):
  7551. """
  7552. Opens a G-gcode file, parses it and creates a new object for
  7553. it in the program. Thread-safe.
  7554. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7555. :param filename: G-code file filename
  7556. :type filename: str
  7557. :return: None
  7558. """
  7559. App.log.debug("open_gcode()")
  7560. # How the object should be initialized
  7561. def obj_init(job_obj, app_obj_):
  7562. """
  7563. :param job_obj: the resulting object
  7564. :type app_obj_: App
  7565. """
  7566. assert isinstance(app_obj_, App), \
  7567. "Initializer expected App, got %s" % type(app_obj_)
  7568. self.progress.emit(10)
  7569. try:
  7570. f = open(filename)
  7571. gcode = f.read()
  7572. f.close()
  7573. except IOError:
  7574. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  7575. (_("Failed to open"), filename))
  7576. self.progress.emit(0)
  7577. return "fail"
  7578. job_obj.gcode = gcode
  7579. self.progress.emit(20)
  7580. ret = job_obj.gcode_parse()
  7581. if ret == "fail":
  7582. self.inform.emit('[ERROR_NOTCL] %s' %
  7583. _("This is not GCODE"))
  7584. return "fail"
  7585. self.progress.emit(60)
  7586. job_obj.create_geometry()
  7587. with self.proc_container.new(_("Opening G-Code.")):
  7588. # Object name
  7589. name = outname or filename.split('/')[-1].split('\\')[-1]
  7590. # New object creation and file processing
  7591. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  7592. if ret == 'fail':
  7593. self.inform.emit('[ERROR_NOTCL] %s' %
  7594. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  7595. "Attempting to create a FlatCAM CNCJob Object from "
  7596. "G-Code file failed during processing"))
  7597. return "fail"
  7598. # Register recent file
  7599. self.file_opened.emit("cncjob", filename)
  7600. # GUI feedback
  7601. self.inform.emit('[success] %s: %s' %
  7602. (_("Opened"), filename))
  7603. self.progress.emit(100)
  7604. def open_config_file(self, filename, run_from_arg=None):
  7605. """
  7606. Loads a config file from the specified file.
  7607. :param filename: Name of the file from which to load.
  7608. :type filename: str
  7609. :return: None
  7610. """
  7611. App.log.debug("Opening config file: " + filename)
  7612. # add the tab if it was closed
  7613. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  7614. # first clear previous text in text editor (if any)
  7615. self.ui.code_editor.clear()
  7616. # Switch plot_area to CNCJob tab
  7617. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7618. try:
  7619. if filename:
  7620. f = QtCore.QFile(filename)
  7621. if f.open(QtCore.QIODevice.ReadOnly):
  7622. stream = QtCore.QTextStream(f)
  7623. gcode_edited = stream.readAll()
  7624. self.ui.code_editor.setPlainText(gcode_edited)
  7625. f.close()
  7626. except IOError:
  7627. App.log.error("Failed to open config file: %s" % filename)
  7628. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7629. (_("Failed to open config file"), filename))
  7630. return
  7631. def open_project(self, filename, run_from_arg=None):
  7632. """
  7633. Loads a project from the specified file.
  7634. 1) Loads and parses file
  7635. 2) Registers the file as recently opened.
  7636. 3) Calls on_file_new()
  7637. 4) Updates options
  7638. 5) Calls new_object() with the object's from_dict() as init method.
  7639. 6) Calls plot_all()
  7640. :param filename: Name of the file from which to load.
  7641. :type filename: str
  7642. :param run_from_arg: True if run for arguments
  7643. :return: None
  7644. """
  7645. App.log.debug("Opening project: " + filename)
  7646. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7647. # Open and parse an uncompressed Project file
  7648. try:
  7649. f = open(filename, 'r')
  7650. except IOError:
  7651. App.log.error("Failed to open project file: %s" % filename)
  7652. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7653. (_("Failed to open project file"), filename))
  7654. return
  7655. try:
  7656. d = json.load(f, object_hook=dict2obj)
  7657. except Exception as e:
  7658. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7659. (filename, str(e)))
  7660. f.close()
  7661. # Open and parse a compressed Project file
  7662. try:
  7663. with lzma.open(filename) as f:
  7664. file_content = f.read().decode('utf-8')
  7665. d = json.loads(file_content, object_hook=dict2obj)
  7666. except Exception as e:
  7667. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7668. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7669. (_("Failed to open project file"), filename))
  7670. return
  7671. # Clear the current project
  7672. # # NOT THREAD SAFE # ##
  7673. if run_from_arg is True:
  7674. pass
  7675. else:
  7676. self.on_file_new()
  7677. # Project options
  7678. self.options.update(d['options'])
  7679. self.project_filename = filename
  7680. self.set_screen_units(self.options["units"])
  7681. # Re create objects
  7682. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7683. for obj in d['objs']:
  7684. def obj_init(obj_inst, app_inst):
  7685. obj_inst.from_dict(obj)
  7686. App.log.debug("Recreating from opened project an %s object: %s" %
  7687. (obj['kind'].capitalize(), obj['options']['name']))
  7688. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7689. obj['kind'].upper(),
  7690. obj['options']['name']
  7691. )
  7692. )
  7693. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  7694. # self.plot_all()
  7695. self.inform.emit('[success] %s: %s' %
  7696. (_("Project loaded from"), filename))
  7697. self.should_we_save = False
  7698. self.file_opened.emit("project", filename)
  7699. self.set_ui_title(name=self.project_filename)
  7700. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7701. def propagate_defaults(self, silent=False):
  7702. """
  7703. This method is used to set default values in classes. It's
  7704. an alternative to project options but allows the use
  7705. of values invisible to the user.
  7706. :return: None
  7707. """
  7708. if silent is False:
  7709. self.log.debug("propagate_defaults()")
  7710. # Which objects to update the given parameters.
  7711. routes = {
  7712. "global_zdownrate": CNCjob,
  7713. "excellon_zeros": Excellon,
  7714. "excellon_format_upper_in": Excellon,
  7715. "excellon_format_lower_in": Excellon,
  7716. "excellon_format_upper_mm": Excellon,
  7717. "excellon_format_lower_mm": Excellon,
  7718. "excellon_units": Excellon,
  7719. "gerber_use_buffer_for_union": Gerber,
  7720. "geometry_multidepth": Geometry
  7721. }
  7722. for param in routes:
  7723. if param in routes[param].defaults:
  7724. try:
  7725. routes[param].defaults[param] = self.defaults[param]
  7726. if silent is False:
  7727. self.log.debug(" " + param + " OK")
  7728. except KeyError:
  7729. if silent is False:
  7730. self.log.debug(" ERROR: " + param + " not in defaults.")
  7731. else:
  7732. # Try extracting the name:
  7733. # classname_param here is param in the object
  7734. if param.find(routes[param].__name__.lower() + "_") == 0:
  7735. p = param[len(routes[param].__name__) + 1:]
  7736. if p in routes[param].defaults:
  7737. routes[param].defaults[p] = self.defaults[param]
  7738. if silent is False:
  7739. self.log.debug(" " + param + " OK!")
  7740. def restore_main_win_geom(self):
  7741. try:
  7742. self.ui.setGeometry(self.defaults["global_def_win_x"],
  7743. self.defaults["global_def_win_y"],
  7744. self.defaults["global_def_win_w"],
  7745. self.defaults["global_def_win_h"])
  7746. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  7747. settings = QSettings("Open Source", "FlatCAM")
  7748. if settings.contains("maximized_gui"):
  7749. maximized_ui = settings.value('maximized_gui', type=bool)
  7750. if maximized_ui is True:
  7751. self.ui.showMaximized()
  7752. except KeyError as e:
  7753. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  7754. def plot_all(self, zoom=True):
  7755. """
  7756. Re-generates all plots from all objects.
  7757. :return: None
  7758. """
  7759. self.log.debug("Plot_all()")
  7760. for obj in self.collection.get_list():
  7761. def worker_task(obj):
  7762. with self.proc_container.new("Plotting"):
  7763. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7764. if zoom:
  7765. self.object_plotted.emit(obj)
  7766. # Send to worker
  7767. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  7768. def register_folder(self, filename):
  7769. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7770. def register_save_folder(self, filename):
  7771. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7772. def set_progress_bar(self, percentage, text=""):
  7773. self.ui.progress_bar.setValue(int(percentage))
  7774. def setup_shell(self):
  7775. """
  7776. Creates shell functions. Runs once at startup.
  7777. :return: None
  7778. """
  7779. self.log.debug("setup_shell()")
  7780. def shelp(p=None):
  7781. if not p:
  7782. return _("Available commands:\n") + \
  7783. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  7784. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  7785. if p not in commands:
  7786. return "Unknown command: %s" % p
  7787. return commands[p]["help"]
  7788. # --- Migrated to new architecture ---
  7789. # def options(name):
  7790. # ops = self.collection.get_by_name(str(name)).options
  7791. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  7792. def h(*args):
  7793. """
  7794. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  7795. and standalone parameters into list.
  7796. """
  7797. kwa = {}
  7798. a = []
  7799. n = len(args)
  7800. name = None
  7801. for i in range(n):
  7802. match = re.search(r'^-([a-zA-Z].*)', args[i])
  7803. if match:
  7804. assert name is None
  7805. name = match.group(1)
  7806. continue
  7807. if name is None:
  7808. a.append(args[i])
  7809. else:
  7810. kwa[name] = args[i]
  7811. name = None
  7812. return a, kwa
  7813. @contextmanager
  7814. def wait_signal(signal, timeout=10000):
  7815. """
  7816. Block loop until signal emitted, timeout (ms) elapses
  7817. or unhandled exception happens in a thread.
  7818. :param timeout: time after which the loop is exited
  7819. :param signal: Signal to wait for.
  7820. """
  7821. loop = QtCore.QEventLoop()
  7822. # Normal termination
  7823. signal.connect(loop.quit)
  7824. # Termination by exception in thread
  7825. self.thread_exception.connect(loop.quit)
  7826. status = {'timed_out': False}
  7827. def report_quit():
  7828. status['timed_out'] = True
  7829. loop.quit()
  7830. yield
  7831. # Temporarily change how exceptions are managed.
  7832. oeh = sys.excepthook
  7833. ex = []
  7834. def except_hook(type_, value, traceback_):
  7835. ex.append(value)
  7836. oeh(type_, value, traceback_)
  7837. sys.excepthook = except_hook
  7838. # Terminate on timeout
  7839. if timeout is not None:
  7840. QtCore.QTimer.singleShot(timeout, report_quit)
  7841. # # ## Block ## ##
  7842. loop.exec_()
  7843. # Restore exception management
  7844. sys.excepthook = oeh
  7845. if ex:
  7846. self.raiseTclError(str(ex[0]))
  7847. if status['timed_out']:
  7848. raise Exception('Timed out!')
  7849. def make_docs():
  7850. output = ''
  7851. import collections
  7852. od = collections.OrderedDict(sorted(commands.items()))
  7853. for cmd_, val in od.items():
  7854. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  7855. t = val['help']
  7856. usage_i = t.find('>')
  7857. if usage_i < 0:
  7858. expl = t
  7859. output += expl + '\n\n'
  7860. continue
  7861. expl = t[:usage_i - 1]
  7862. output += expl + '\n\n'
  7863. end_usage_i = t[usage_i:].find('\n')
  7864. if end_usage_i < 0:
  7865. end_usage_i = len(t[usage_i:])
  7866. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  7867. else:
  7868. extras = t[usage_i+end_usage_i+1:]
  7869. parts = [s.strip() for s in extras.split('\n')]
  7870. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  7871. for p in parts:
  7872. output += ' ' + p + '\n\n'
  7873. return output
  7874. '''
  7875. Howto implement TCL shell commands:
  7876. All parameters passed to command should be possible to set as None and test it afterwards.
  7877. This is because we need to see error caused in tcl,
  7878. if None value as default parameter is not allowed TCL will return empty error.
  7879. Use:
  7880. def mycommand(name=None,...):
  7881. Test it like this:
  7882. if name is None:
  7883. self.raise_tcl_error('Argument name is missing.')
  7884. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  7885. otherwise we will miss it and processing will silently continue.
  7886. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  7887. which is catched in exec_command and displayed in TCL shell console with red background.
  7888. Error in console is displayed with TCL trace.
  7889. This behavior works only within main thread,
  7890. errors with promissed tasks can be catched and detected only with log.
  7891. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  7892. TCL shell.
  7893. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  7894. '''
  7895. commands = {
  7896. 'help': {
  7897. 'fcn': shelp,
  7898. 'help': _("Shows list of commands.")
  7899. },
  7900. }
  7901. # Import/overwrite tcl commands as objects of TclCommand descendants
  7902. # This modifies the variable 'commands'.
  7903. tclCommands.register_all_commands(self, commands)
  7904. # Add commands to the tcl interpreter
  7905. for cmd in commands:
  7906. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  7907. # Make the tcl puts function return instead of print to stdout
  7908. self.tcl.eval('''
  7909. rename puts original_puts
  7910. proc puts {args} {
  7911. if {[llength $args] == 1} {
  7912. return "[lindex $args 0]"
  7913. } else {
  7914. eval original_puts $args
  7915. }
  7916. }
  7917. ''')
  7918. def setup_recent_items(self):
  7919. # TODO: Move this to constructor
  7920. icons = {
  7921. "gerber": "share/flatcam_icon16.png",
  7922. "excellon": "share/drill16.png",
  7923. 'geometry': "share/geometry16.png",
  7924. "cncjob": "share/cnc16.png",
  7925. "project": "share/project16.png",
  7926. "svg": "share/geometry16.png",
  7927. "dxf": "share/dxf16.png",
  7928. "pdf": "share/pdf32.png",
  7929. "image": "share/image16.png"
  7930. }
  7931. openers = {
  7932. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7933. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7934. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7935. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7936. 'project': self.open_project,
  7937. 'svg': self.import_svg,
  7938. 'dxf': self.import_dxf,
  7939. 'image': self.import_image,
  7940. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7941. }
  7942. # Open recent file for files
  7943. try:
  7944. f = open(self.data_path + '/recent.json')
  7945. except IOError:
  7946. App.log.error("Failed to load recent item list.")
  7947. self.inform.emit('[ERROR_NOTCL] %s' %
  7948. _("Failed to load recent item list."))
  7949. return
  7950. try:
  7951. self.recent = json.load(f)
  7952. except json.scanner.JSONDecodeError:
  7953. App.log.error("Failed to parse recent item list.")
  7954. self.inform.emit('[ERROR_NOTCL] %s' %
  7955. _("Failed to parse recent item list."))
  7956. f.close()
  7957. return
  7958. f.close()
  7959. # Open recent file for projects
  7960. try:
  7961. fp = open(self.data_path + '/recent_projects.json')
  7962. except IOError:
  7963. App.log.error("Failed to load recent project item list.")
  7964. self.inform.emit('[ERROR_NOTCL] %s' %
  7965. _("Failed to load recent projects item list."))
  7966. return
  7967. try:
  7968. self.recent_projects = json.load(fp)
  7969. except json.scanner.JSONDecodeError:
  7970. App.log.error("Failed to parse recent project item list.")
  7971. self.inform.emit('[ERROR_NOTCL] %s' %
  7972. _("Failed to parse recent project item list."))
  7973. fp.close()
  7974. return
  7975. fp.close()
  7976. # Closure needed to create callbacks in a loop.
  7977. # Otherwise late binding occurs.
  7978. def make_callback(func, fname):
  7979. def opener():
  7980. func(fname)
  7981. return opener
  7982. def reset_recent_files():
  7983. # Reset menu
  7984. self.ui.recent.clear()
  7985. self.recent = []
  7986. try:
  7987. f = open(self.data_path + '/recent.json', 'w')
  7988. except IOError:
  7989. App.log.error("Failed to open recent items file for writing.")
  7990. return
  7991. json.dump(self.recent, f)
  7992. def reset_recent_projects():
  7993. # Reset menu
  7994. self.ui.recent_projects.clear()
  7995. self.recent_projects = []
  7996. try:
  7997. fp = open(self.data_path + '/recent_projects.json', 'w')
  7998. except IOError:
  7999. App.log.error("Failed to open recent projects items file for writing.")
  8000. return
  8001. json.dump(self.recent, fp)
  8002. # Reset menu
  8003. self.ui.recent.clear()
  8004. self.ui.recent_projects.clear()
  8005. # Create menu items for projects
  8006. for recent in self.recent_projects:
  8007. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8008. if recent['kind'] == 'project':
  8009. try:
  8010. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8011. # Attach callback
  8012. o = make_callback(openers[recent["kind"]], recent['filename'])
  8013. action.triggered.connect(o)
  8014. self.ui.recent_projects.addAction(action)
  8015. except KeyError:
  8016. App.log.error("Unsupported file type: %s" % recent["kind"])
  8017. # Last action in Recent Files menu is one that Clear the content
  8018. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8019. clear_action_proj.triggered.connect(reset_recent_projects)
  8020. self.ui.recent_projects.addSeparator()
  8021. self.ui.recent_projects.addAction(clear_action_proj)
  8022. # Create menu items for files
  8023. for recent in self.recent:
  8024. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8025. if recent['kind'] != 'project':
  8026. try:
  8027. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8028. # Attach callback
  8029. o = make_callback(openers[recent["kind"]], recent['filename'])
  8030. action.triggered.connect(o)
  8031. self.ui.recent.addAction(action)
  8032. except KeyError:
  8033. App.log.error("Unsupported file type: %s" % recent["kind"])
  8034. # Last action in Recent Files menu is one that Clear the content
  8035. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8036. clear_action.triggered.connect(reset_recent_files)
  8037. self.ui.recent.addSeparator()
  8038. self.ui.recent.addAction(clear_action)
  8039. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8040. # self.ui.menufilerecent.set_submenu(recent_menu)
  8041. # recent_menu.show_all()
  8042. # self.ui.recent.show()
  8043. self.log.debug("Recent items list has been populated.")
  8044. def setup_component_editor(self):
  8045. # label = QtWidgets.QLabel("Choose an item from Project")
  8046. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8047. sel_title = QtWidgets.QTextEdit(
  8048. _('<b>Shortcut Key List</b>'))
  8049. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8050. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8051. settings = QSettings("Open Source", "FlatCAM")
  8052. if settings.contains("notebook_font_size"):
  8053. fsize = settings.value('notebook_font_size', type=int)
  8054. else:
  8055. fsize = 12
  8056. tsize = fsize + int(fsize / 2)
  8057. selected_text = (_('''
  8058. <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8059. <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8060. The normal flow when working in FlatCAM is the following:</span></p>
  8061. <ol>
  8062. <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  8063. <br />
  8064. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8065. &nbsp;</li>
  8066. <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8067. <br />
  8068. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  8069. <br />
  8070. You can change the parameters in this screen and the flow direction is like this:<br />
  8071. <br />
  8072. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8073. </ol>
  8074. <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  8075. ''').format(fsize=fsize, tsize=tsize))
  8076. sel_title.setText(selected_text)
  8077. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8078. self.ui.selected_scroll_area.setWidget(sel_title)
  8079. def setup_obj_classes(self):
  8080. """
  8081. Sets up application specifics on the FlatCAMObj class.
  8082. :return: None
  8083. """
  8084. FlatCAMObj.app = self
  8085. ObjectCollection.app = self
  8086. Gerber.app = self
  8087. Excellon.app = self
  8088. Geometry.app = self
  8089. CNCjob.app = self
  8090. FCProcess.app = self
  8091. FCProcessContainer.app = self
  8092. def version_check(self):
  8093. """
  8094. Checks for the latest version of the program. Alerts the
  8095. user if theirs is outdated. This method is meant to be run
  8096. in a separate thread.
  8097. :return: None
  8098. """
  8099. self.log.debug("version_check()")
  8100. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8101. full_url = App.version_url + \
  8102. "?s=" + str(self.defaults['global_serial']) + \
  8103. "&v=" + str(self.version) + \
  8104. "&os=" + str(self.os) + \
  8105. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8106. else:
  8107. # no_stats dict; just so it won't break things on website
  8108. no_ststs_dict = {}
  8109. no_ststs_dict["global_ststs"] = {}
  8110. full_url = App.version_url + \
  8111. "?s=" + str(self.defaults['global_serial']) + \
  8112. "&v=" + str(self.version) + \
  8113. "&os=" + str(self.os) + \
  8114. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8115. App.log.debug("Checking for updates @ %s" % full_url)
  8116. # ## Get the data
  8117. try:
  8118. f = urllib.request.urlopen(full_url)
  8119. except:
  8120. # App.log.warning("Failed checking for latest version. Could not connect.")
  8121. self.log.warning("Failed checking for latest version. Could not connect.")
  8122. self.inform.emit('[WARNING_NOTCL] %s' %
  8123. _("Failed checking for latest version. Could not connect."))
  8124. return
  8125. try:
  8126. data = json.load(f)
  8127. except Exception as e:
  8128. App.log.error("Could not parse information about latest version.")
  8129. self.inform.emit('[ERROR_NOTCL] %s' %
  8130. _("Could not parse information about latest version."))
  8131. App.log.debug("json.load(): %s" % str(e))
  8132. f.close()
  8133. return
  8134. f.close()
  8135. # ## Latest version?
  8136. if self.version >= data["version"]:
  8137. App.log.debug("FlatCAM is up to date!")
  8138. self.inform.emit('[success] %s' %
  8139. _("FlatCAM is up to date!"))
  8140. return
  8141. App.log.debug("Newer version available.")
  8142. self.message.emit(
  8143. _("Newer Version Available"),
  8144. _("There is a newer version of FlatCAM available for download:\n\n") +
  8145. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  8146. _("info")
  8147. )
  8148. def on_plotcanvas_setup(self, container=None):
  8149. """
  8150. This is doing the setup for the plot area (VisPy canvas)
  8151. :param container: widget where to install the canvas
  8152. :return: None
  8153. """
  8154. if container:
  8155. plot_container = container
  8156. else:
  8157. plot_container = self.ui.right_layout
  8158. self.plotcanvas = PlotCanvas(plot_container, self)
  8159. # So it can receive key presses
  8160. self.plotcanvas.native.setFocus()
  8161. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  8162. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  8163. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8164. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  8165. # Keys over plot enabled
  8166. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  8167. self.app_cursor = self.plotcanvas.new_cursor()
  8168. self.app_cursor.enabled = False
  8169. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8170. def on_zoom_fit(self, event):
  8171. """
  8172. Callback for zoom-out request. This can be either from the corresponding
  8173. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8174. with axes limits from the geometry bounds of all objects.
  8175. :param event: Ignored.
  8176. :return: None
  8177. """
  8178. self.plotcanvas.fit_view()
  8179. def on_zoom_in(self):
  8180. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8181. def on_zoom_out(self):
  8182. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8183. def disable_all_plots(self):
  8184. self.report_usage("disable_all_plots()")
  8185. self.disable_plots(self.collection.get_list())
  8186. self.inform.emit('[success] %s' %
  8187. _("All plots disabled."))
  8188. def disable_other_plots(self):
  8189. self.report_usage("disable_other_plots()")
  8190. self.disable_plots(self.collection.get_non_selected())
  8191. self.inform.emit('[success] %s' %
  8192. _("All non selected plots disabled."))
  8193. def enable_all_plots(self):
  8194. self.report_usage("enable_all_plots()")
  8195. self.enable_plots(self.collection.get_list())
  8196. self.inform.emit('[success] %s' %
  8197. _("All plots enabled."))
  8198. def on_enable_sel_plots(self):
  8199. log.debug("App.on_enable_sel_plot()")
  8200. object_list = self.collection.get_selected()
  8201. self.enable_plots(objects=object_list)
  8202. self.inform.emit('[success] %s' %
  8203. _("Selected plots enabled..."))
  8204. def on_disable_sel_plots(self):
  8205. log.debug("App.on_disable_sel_plot()")
  8206. # self.inform.emit(_("Disabling plots ..."))
  8207. object_list = self.collection.get_selected()
  8208. self.disable_plots(objects=object_list)
  8209. self.inform.emit('[success] %s' %
  8210. _("Selected plots disabled..."))
  8211. def enable_plots(self, objects):
  8212. """
  8213. Disables plots
  8214. :param objects: list of Objects to be enabled
  8215. :return:
  8216. """
  8217. log.debug("Enabling plots ...")
  8218. # self.inform.emit(_("Working ..."))
  8219. for obj in objects:
  8220. if obj.options['plot'] is False:
  8221. obj.options.set_change_callback(lambda x: None)
  8222. obj.options['plot'] = True
  8223. obj.options.set_change_callback(obj.on_options_change)
  8224. def worker_task(objects):
  8225. with self.proc_container.new(_("Enabling plots ...")):
  8226. for obj in objects:
  8227. # obj.options['plot'] = True
  8228. if isinstance(obj, FlatCAMCNCjob):
  8229. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8230. else:
  8231. obj.plot(visible=True)
  8232. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8233. # self.plots_updated.emit()
  8234. def disable_plots(self, objects):
  8235. """
  8236. Disables plots
  8237. :param objects: list of Objects to be disabled
  8238. :return:
  8239. """
  8240. # if no objects selected then do nothing
  8241. if not self.collection.get_selected():
  8242. return
  8243. log.debug("Disabling plots ...")
  8244. # self.inform.emit(_("Working ..."))
  8245. for obj in objects:
  8246. if obj.options['plot'] is True:
  8247. obj.options.set_change_callback(lambda x: None)
  8248. obj.options['plot'] = False
  8249. obj.options.set_change_callback(obj.on_options_change)
  8250. try:
  8251. self.delete_selection_shape()
  8252. except Exception as e:
  8253. log.debug("App.disable_plots() --> %s" % str(e))
  8254. # self.plots_updated.emit()
  8255. def worker_task(objects):
  8256. with self.proc_container.new(_("Disabling plots ...")):
  8257. for obj in objects:
  8258. # obj.options['plot'] = True
  8259. if isinstance(obj, FlatCAMCNCjob):
  8260. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8261. else:
  8262. obj.plot(visible=False)
  8263. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8264. def toggle_plots(self, objects):
  8265. """
  8266. Toggle plots visibility
  8267. :param objects: list of Objects for which to be toggled the visibility
  8268. :return:
  8269. """
  8270. # if no objects selected then do nothing
  8271. if not self.collection.get_selected():
  8272. return
  8273. log.debug("Toggling plots ...")
  8274. self.inform.emit(_("Working ..."))
  8275. for obj in objects:
  8276. if obj.options['plot'] is False:
  8277. obj.options['plot'] = True
  8278. else:
  8279. obj.options['plot'] = False
  8280. self.plots_updated.emit()
  8281. def clear_plots(self):
  8282. objects = self.collection.get_list()
  8283. for obj in objects:
  8284. obj.clear(obj == objects[-1])
  8285. # Clear pool to free memory
  8286. self.clear_pool()
  8287. def generate_cnc_job(self, objects):
  8288. self.report_usage("generate_cnc_job()")
  8289. # for obj in objects:
  8290. # obj.generatecncjob()
  8291. for obj in objects:
  8292. obj.on_generatecnc_button_click()
  8293. def save_project(self, filename, quit_action=False):
  8294. """
  8295. Saves the current project to the specified file.
  8296. :param filename: Name of the file in which to save.
  8297. :type filename: str
  8298. :param quit_action: if the project saving will be followed by an app quit; boolean
  8299. :return: None
  8300. """
  8301. self.log.debug("save_project()")
  8302. self.save_in_progress = True
  8303. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  8304. # Capture the latest changes
  8305. # Current object
  8306. try:
  8307. self.collection.get_active().read_form()
  8308. except:
  8309. self.log.debug("There was no active object")
  8310. pass
  8311. # Project options
  8312. self.options_read_form()
  8313. # Serialize the whole project
  8314. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8315. "options": self.options,
  8316. "version": self.version}
  8317. if self.defaults["global_save_compressed"] is True:
  8318. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8319. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8320. # # Write
  8321. f.write(g)
  8322. self.inform.emit('[success] %s: %s' %
  8323. (_("Project saved to"), filename))
  8324. else:
  8325. # Open file
  8326. try:
  8327. f = open(filename, 'w')
  8328. except IOError:
  8329. App.log.error("Failed to open file for saving: %s", filename)
  8330. return
  8331. # Write
  8332. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8333. f.close()
  8334. # verification of the saved project
  8335. # Open and parse
  8336. try:
  8337. saved_f = open(filename, 'r')
  8338. except IOError:
  8339. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8340. (_("Failed to verify project file"), filename, _("Retry to save it."))
  8341. )
  8342. return
  8343. try:
  8344. saved_d = json.load(saved_f, object_hook=dict2obj)
  8345. except:
  8346. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8347. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8348. )
  8349. f.close()
  8350. return
  8351. saved_f.close()
  8352. if 'version' in saved_d:
  8353. self.inform.emit('[success] %s: %s' %
  8354. (_("Project saved to"), filename))
  8355. else:
  8356. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8357. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8358. )
  8359. settings = QSettings("Open Source", "FlatCAM")
  8360. lock_state = self.ui.lock_action.isChecked()
  8361. settings.setValue('toolbar_lock', lock_state)
  8362. # This will write the setting to the platform specific storage.
  8363. del settings
  8364. # if quit:
  8365. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8366. # t.start()
  8367. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8368. def start_delayed_quit(self, delay, filename, should_quit=None):
  8369. """
  8370. :param delay: period of checking if project file size is more than zero; in seconds
  8371. :param filename: the name of the project file to be checked periodically for size more than zero
  8372. :param should_quit: if the task finished will be followed by an app quit; boolean
  8373. :return:
  8374. """
  8375. to_quit = should_quit
  8376. self.save_timer = QtCore.QTimer()
  8377. self.save_timer.setInterval(delay)
  8378. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8379. self.save_timer.start()
  8380. def check_project_file_size(self, filename, should_quit=None):
  8381. """
  8382. :param filename: the name of the project file to be checked periodically for size more than zero
  8383. :param should_quit: will quit the app if True; boolean
  8384. :return:
  8385. """
  8386. try:
  8387. if os.stat(filename).st_size > 0:
  8388. self.save_in_progress = False
  8389. self.save_timer.stop()
  8390. if should_quit:
  8391. self.app_quit.emit()
  8392. except Exception as e:
  8393. traceback.print_exc()
  8394. def on_options_app2project(self):
  8395. """
  8396. Callback for Options->Transfer Options->App=>Project. Copies options
  8397. from application defaults to project defaults.
  8398. :return: None
  8399. """
  8400. self.report_usage("on_options_app2project")
  8401. self.defaults_read_form()
  8402. self.options.update(self.defaults)
  8403. self.options_write_form()
  8404. def on_options_project2app(self):
  8405. """
  8406. Callback for Options->Transfer Options->Project=>App. Copies options
  8407. from project defaults to application defaults.
  8408. :return: None
  8409. """
  8410. self.report_usage("on_options_project2app")
  8411. self.options_read_form()
  8412. self.defaults.update(self.options)
  8413. self.defaults_write_form()
  8414. def on_options_project2object(self):
  8415. """
  8416. Callback for Options->Transfer Options->Project=>Object. Copies options
  8417. from project defaults to the currently selected object.
  8418. :return: None
  8419. """
  8420. self.report_usage("on_options_project2object")
  8421. self.options_read_form()
  8422. obj = self.collection.get_active()
  8423. if obj is None:
  8424. self.inform.emit('[WARNING_NOTCL] %s' %
  8425. _("No object selected."))
  8426. return
  8427. for option in self.options:
  8428. if option.find(obj.kind + "_") == 0:
  8429. oname = option[len(obj.kind) + 1:]
  8430. obj.options[oname] = self.options[option]
  8431. obj.to_form() # Update UI
  8432. def on_options_object2project(self):
  8433. """
  8434. Callback for Options->Transfer Options->Object=>Project. Copies options
  8435. from the currently selected object to project defaults.
  8436. :return: None
  8437. """
  8438. self.report_usage("on_options_object2project")
  8439. obj = self.collection.get_active()
  8440. if obj is None:
  8441. self.inform.emit('[WARNING_NOTCL] %s' %
  8442. _("No object selected."))
  8443. return
  8444. obj.read_form()
  8445. for option in obj.options:
  8446. if option in ['name']: # TODO: Handle this better...
  8447. continue
  8448. self.options[obj.kind + "_" + option] = obj.options[option]
  8449. self.options_write_form()
  8450. def on_options_object2app(self):
  8451. """
  8452. Callback for Options->Transfer Options->Object=>App. Copies options
  8453. from the currently selected object to application defaults.
  8454. :return: None
  8455. """
  8456. self.report_usage("on_options_object2app")
  8457. obj = self.collection.get_active()
  8458. if obj is None:
  8459. self.inform.emit('[WARNING_NOTCL] %s' %
  8460. _("No object selected."))
  8461. return
  8462. obj.read_form()
  8463. for option in obj.options:
  8464. if option in ['name']: # TODO: Handle this better...
  8465. continue
  8466. self.defaults[obj.kind + "_" + option] = obj.options[option]
  8467. self.defaults_write_form()
  8468. def on_options_app2object(self):
  8469. """
  8470. Callback for Options->Transfer Options->App=>Object. Copies options
  8471. from application defaults to the currently selected object.
  8472. :return: None
  8473. """
  8474. self.report_usage("on_options_app2object")
  8475. self.defaults_read_form()
  8476. obj = self.collection.get_active()
  8477. if obj is None:
  8478. self.inform.emit('[WARNING_NOTCL] %s' %
  8479. _("No object selected."))
  8480. return
  8481. for option in self.defaults:
  8482. if option.find(obj.kind + "_") == 0:
  8483. oname = option[len(obj.kind) + 1:]
  8484. obj.options[oname] = self.defaults[option]
  8485. obj.to_form() # Update UI
  8486. class ArgsThread(QtCore.QObject):
  8487. open_signal = pyqtSignal(list)
  8488. start = pyqtSignal()
  8489. if sys.platform == 'win32':
  8490. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8491. else:
  8492. address = ('/tmp/testipc', 'AF_UNIX')
  8493. def __init__(self):
  8494. super(ArgsThread, self).__init__()
  8495. self.start.connect(self.run)
  8496. def my_loop(self, address):
  8497. try:
  8498. listener = Listener(*address)
  8499. while True:
  8500. conn = listener.accept()
  8501. self.serve(conn)
  8502. except socket.error as e:
  8503. conn = Client(*address)
  8504. conn.send(sys.argv)
  8505. conn.send('close')
  8506. # close the current instance only if there are args
  8507. if len(sys.argv) > 1:
  8508. sys.exit()
  8509. def serve(self, conn):
  8510. while True:
  8511. msg = conn.recv()
  8512. if msg == 'close':
  8513. break
  8514. self.open_signal.emit(msg)
  8515. conn.close()
  8516. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8517. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8518. @pyqtSlot()
  8519. def run(self):
  8520. self.my_loop(self.address)
  8521. class GracefulException(Exception):
  8522. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  8523. def __init__(self):
  8524. super().__init__()
  8525. def __str__(self):
  8526. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  8527. # end of file