FlatCAMApp.py 460 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368
  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', 'diatol', 'dist',
  1563. 'drilled_dias', 'drillz',
  1564. 'endz', 'extracut', 'factor', 'False', 'false', 'feedrate', 'feedrate_rapid',
  1565. 'filename', 'follow', 'gaps', 'gapsize', 'grid', 'gridoffset', 'gridoffsetx',
  1566. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  1567. 'milled_dias',
  1568. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  1569. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  1570. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  1571. 'toolchange', 'toolchangez', 'tooldia', 'tools', 'travelz', 'True', 'true', 'type',
  1572. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1573. ]
  1574. self.tcl_keywords = [
  1575. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1576. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1577. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1578. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1579. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1580. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1581. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1582. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1583. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1584. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1585. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1586. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1587. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1588. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1589. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1590. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1591. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1592. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1593. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1594. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1595. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1596. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1597. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1598. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1599. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1600. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1601. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1602. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1603. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1604. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1605. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1606. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1607. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1608. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1609. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1610. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1611. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1612. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1613. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1614. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1615. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1616. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1617. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1618. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1619. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1620. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1621. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1622. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1623. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1624. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1625. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1626. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1627. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1628. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1629. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1630. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1631. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1632. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1633. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1634. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1635. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1636. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1637. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1638. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1639. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1640. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1641. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1642. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1643. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1644. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1645. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1646. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1647. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1648. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1649. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1650. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1651. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1652. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1653. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1654. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1655. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1656. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1657. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1658. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1659. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1660. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1661. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1662. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1663. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1664. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1665. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1666. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1667. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1668. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1669. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1670. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1671. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1672. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1673. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1674. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1675. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1676. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1677. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1678. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1679. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1680. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1681. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1682. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1683. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1684. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1685. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1686. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1687. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1688. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1689. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1690. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1691. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1692. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1693. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1694. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1695. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1696. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1697. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1698. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1699. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1700. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1701. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1702. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1703. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1704. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1705. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1706. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1707. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1708. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1709. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1710. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1711. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1712. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1713. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1714. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1715. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1716. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1717. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1718. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1719. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1720. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1721. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1722. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1723. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1724. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1725. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1726. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1727. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1728. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1729. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1730. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1731. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1732. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1733. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1734. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1735. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1736. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1737. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1738. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1739. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1740. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1741. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1742. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1743. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1744. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1745. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1746. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1747. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1748. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1749. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1750. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1751. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1752. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1753. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1754. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1755. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1756. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1757. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1758. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1759. ]
  1760. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1761. # ####################################################################################
  1762. # ####################### Shell SETUP ################################################
  1763. # ####################################################################################
  1764. self.shell = FCShell(self, version=self.version)
  1765. self.shell._edit.set_model_data(self.myKeywords)
  1766. self.ui.code_editor.set_model_data(self.myKeywords)
  1767. self.shell.setWindowIcon(self.ui.app_icon)
  1768. self.shell.setWindowTitle("FlatCAM Shell")
  1769. self.shell.resize(*self.defaults["global_shell_shape"])
  1770. self.shell.append_output("FlatCAM %s - " % self.version)
  1771. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1772. self.init_tcl()
  1773. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1774. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1775. self.ui.shell_dock.setWidget(self.shell)
  1776. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1777. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1778. QtWidgets.QDockWidget.DockWidgetFloatable |
  1779. QtWidgets.QDockWidget.DockWidgetClosable)
  1780. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1781. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1782. if self.defaults["global_shell_at_startup"]:
  1783. self.ui.shell_dock.show()
  1784. else:
  1785. self.ui.shell_dock.hide()
  1786. # ##################################################################################
  1787. # ###################### Tools and Plugins #########################################
  1788. # ##################################################################################
  1789. self.dblsidedtool = None
  1790. self.measurement_tool = None
  1791. self.panelize_tool = None
  1792. self.film_tool = None
  1793. self.paste_tool = None
  1794. self.calculator_tool = None
  1795. self.sub_tool = None
  1796. self.move_tool = None
  1797. self.cutout_tool = None
  1798. self.ncclear_tool = None
  1799. self.paint_tool = None
  1800. self.transform_tool = None
  1801. self.properties_tool = None
  1802. self.pdf_tool = None
  1803. self.image_tool = None
  1804. self.pcb_wizard_tool = None
  1805. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1806. self.install_tools()
  1807. # ### System Font Parsing ###
  1808. # self.f_parse = ParseFont(self)
  1809. # self.parse_system_fonts()
  1810. # #####################################################################################
  1811. # ########################## START-UP ARGUMENTS #######################################
  1812. # #####################################################################################
  1813. # test if the program was started with a script as parameter
  1814. if self.cmd_line_shellfile:
  1815. try:
  1816. with open(self.cmd_line_shellfile, "r") as myfile:
  1817. cmd_line_shellfile_text = myfile.read()
  1818. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1819. except Exception as ext:
  1820. print("ERROR: ", ext)
  1821. sys.exit(2)
  1822. # #####################################################################################
  1823. # ######################## Check for updates ##########################################
  1824. # #####################################################################################
  1825. # Separate thread (Not worker)
  1826. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1827. if (self.beta is False or self.beta is None) and \
  1828. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1829. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1830. self.thr2 = QtCore.QThread()
  1831. self.worker_task.emit({'fcn': self.version_check,
  1832. 'params': []})
  1833. self.thr2.start(QtCore.QThread.LowPriority)
  1834. # #####################################################################################
  1835. # ###################### Variables for global usage ###################################
  1836. # #####################################################################################
  1837. # register files with FlatCAM; it works only for Windows for now
  1838. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1839. self.on_register_files()
  1840. # coordinates for relative position display
  1841. self.rel_point1 = (0, 0)
  1842. self.rel_point2 = (0, 0)
  1843. # variable to store coordinates
  1844. self.pos = (0, 0)
  1845. self.pos_jump = (0, 0)
  1846. # variable to store mouse coordinates
  1847. self.mouse = [0, 0]
  1848. # decide if we have a double click or single click
  1849. self.doubleclick = False
  1850. # variable to store if a command is active (then the var is not None) and which one it is
  1851. self.command_active = None
  1852. # variable to store the status of moving selection action
  1853. # None value means that it's not an selection action
  1854. # True value = a selection from left to right
  1855. # False value = a selection from right to left
  1856. self.selection_type = None
  1857. # List to store the objects that are currently loaded in FlatCAM
  1858. # This list is updated on each object creation or object delete
  1859. self.all_objects_list = []
  1860. # List to store the objects that are selected
  1861. self.sel_objects_list = []
  1862. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1863. self.key_modifiers = None
  1864. # Variable to hold the status of the axis
  1865. self.toggle_axis = True
  1866. # Variable to store the status of the fullscreen event
  1867. self.toggle_fscreen = False
  1868. # Variable to store the status of the code editor
  1869. self.toggle_codeeditor = False
  1870. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1871. self.click_noproject = False
  1872. self.cursor = None
  1873. # Variable to store the GCODE that was edited
  1874. self.gcode_edited = ""
  1875. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1876. self.preferences_changed_flag = False
  1877. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1878. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1879. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1880. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1881. ]
  1882. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1883. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1884. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1885. 'mpf'
  1886. ]
  1887. self.svg_list = ['svg']
  1888. self.dxf_list = ['dxf']
  1889. self.pdf_list = ['pdf']
  1890. self.prj_list = ['flatprj']
  1891. self.conf_list = ['flatconfig']
  1892. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1893. # flag for polygons not cleared
  1894. self.poly_not_cleared = False
  1895. # VisPy visuals
  1896. self.isHovering = False
  1897. self.notHovering = True
  1898. # when True, the app has to return from any thread
  1899. self.abort_flag = False
  1900. # ###############################################################################
  1901. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  1902. # ############# It's done only once after install ###############
  1903. # ###############################################################################
  1904. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1905. fac_def_from_file = factory_file.read()
  1906. factory_defaults = json.loads(fac_def_from_file)
  1907. # if the file contain an empty dictionary then save the factory defaults into the file
  1908. if not factory_defaults:
  1909. self.save_factory_defaults(silent=False)
  1910. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1911. initial_lay = 'compact'
  1912. self.on_layout(lay=initial_lay)
  1913. # Set the combobox in Preferences to the current layout
  1914. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1915. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1916. factory_file.close()
  1917. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1918. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1919. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1920. # after the first run, this object should be False
  1921. self.defaults["first_run"] = False
  1922. # ###############################################################################
  1923. # ################# ADDING FlatCAM EDITORS section ##############################
  1924. # ###############################################################################
  1925. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1926. # at the first launch of the App , the editors will not be functional.
  1927. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1928. self.exc_editor = FlatCAMExcEditor(self)
  1929. self.grb_editor = FlatCAMGrbEditor(self)
  1930. self.log.debug("Finished adding FlatCAM Editor's.")
  1931. self.set_ui_title(name=_("New Project - Not saved"))
  1932. # ###############################################################################
  1933. # ####################### Finished the CONSTRUCTOR ##############################
  1934. # ###############################################################################
  1935. App.log.debug("END of constructor. Releasing control.")
  1936. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1937. # the path/file_name must be enclosed in quotes if it contain spaces
  1938. if App.args:
  1939. self.args_at_startup.emit(App.args)
  1940. @staticmethod
  1941. def copy_and_overwrite(from_path, to_path):
  1942. """
  1943. From here:
  1944. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1945. :param from_path: source path
  1946. :param to_path: destination path
  1947. :return: None
  1948. """
  1949. if os.path.exists(to_path):
  1950. shutil.rmtree(to_path)
  1951. try:
  1952. shutil.copytree(from_path, to_path)
  1953. except FileNotFoundError:
  1954. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1955. shutil.copytree(from_new_path, to_path)
  1956. def on_startup_args(self, args=None):
  1957. """
  1958. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1959. :param args: a list containing the application args at startup
  1960. :return: None
  1961. """
  1962. if args:
  1963. args_to_process = args
  1964. else:
  1965. args_to_process = App.args
  1966. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1967. for argument in args_to_process:
  1968. if '.FlatPrj' in argument:
  1969. try:
  1970. project_name = str(argument)
  1971. if project_name == "":
  1972. self.inform.emit(_("Open cancelled."))
  1973. else:
  1974. # self.open_project(project_name)
  1975. run_from_arg = True
  1976. # self.worker_task.emit({'fcn': self.open_project,
  1977. # 'params': [project_name, run_from_arg]})
  1978. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1979. except Exception as e:
  1980. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1981. elif '.FlatConfig' in argument:
  1982. try:
  1983. file_name = str(argument)
  1984. if file_name == "":
  1985. self.inform.emit(_("Open Config file failed."))
  1986. else:
  1987. # run_from_arg = True
  1988. # self.worker_task.emit({'fcn': self.open_config_file,
  1989. # 'params': [file_name, run_from_arg]})
  1990. self.open_config_file(file_name, run_from_arg=True)
  1991. except Exception as e:
  1992. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1993. elif '.FlatScript' in argument:
  1994. try:
  1995. file_name = str(argument)
  1996. if file_name == "":
  1997. self.inform.emit(_("Open Script file failed."))
  1998. else:
  1999. # run_from_arg = True
  2000. # self.worker_task.emit({'fcn': self.open_script_file,
  2001. # 'params': [file_name, run_from_arg]})
  2002. self.on_filerunscript(name=file_name)
  2003. except Exception as e:
  2004. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2005. else:
  2006. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2007. proc_arg = argument.lower()
  2008. for ext in exc_list:
  2009. proc_ext = ext.replace(' ', '')
  2010. if proc_ext.lower() in proc_arg and proc_ext != '':
  2011. file_name = str(argument)
  2012. if file_name == "":
  2013. self.inform.emit(_("Open Excellon file failed."))
  2014. else:
  2015. self.on_fileopenexcellon(name=file_name)
  2016. return
  2017. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2018. for ext in gco_list:
  2019. proc_ext = ext.replace(' ', '')
  2020. if proc_ext.lower() in proc_arg and proc_ext != '':
  2021. file_name = str(argument)
  2022. if file_name == "":
  2023. self.inform.emit(_("Open GCode file failed."))
  2024. else:
  2025. self.on_fileopengcode(name=file_name)
  2026. return
  2027. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2028. for ext in grb_list:
  2029. proc_ext = ext.replace(' ', '')
  2030. if proc_ext.lower() in proc_arg and proc_ext != '':
  2031. file_name = str(argument)
  2032. if file_name == "":
  2033. self.inform.emit(_("Open Gerber file failed."))
  2034. else:
  2035. self.on_fileopengerber(name=file_name)
  2036. return
  2037. def set_ui_title(self, name):
  2038. """
  2039. Sets the title of the main window.
  2040. :param name: String that store the project path and project name
  2041. :return: None
  2042. """
  2043. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2044. (self.version,
  2045. ('BETA' if self.beta else ''),
  2046. platform.architecture()[0],
  2047. name)
  2048. )
  2049. def defaults_read_form(self):
  2050. """
  2051. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2052. :return: None
  2053. """
  2054. for option in self.defaults_form_fields:
  2055. try:
  2056. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2057. except Exception as e:
  2058. log.debug("App.defaults_read_form() --> %s" % str(e))
  2059. def defaults_write_form(self, factor=None, fl_units=None):
  2060. """
  2061. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2062. self.defaults dictionary.
  2063. :param factor: will apply a factor to the values that written in the GUI elements
  2064. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2065. :return: None
  2066. """
  2067. for option in self.defaults:
  2068. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2069. # try:
  2070. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2071. # except KeyError:
  2072. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2073. # # TODO: Rethink this?
  2074. # pass
  2075. def defaults_write_form_field(self, field, factor=None, units=None):
  2076. """
  2077. Basically it is the worker in the self.defaults_write_form()
  2078. :param field: the GUI element in Preferences GUI to be updated
  2079. :param factor: factor to be applied to the field parameter
  2080. :param units: current FLatCAM measuring units
  2081. :return: None, it updates GUI elements
  2082. """
  2083. try:
  2084. if factor is None:
  2085. if units is None:
  2086. self.defaults_form_fields[field].set_value(self.defaults[field])
  2087. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2088. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2089. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2090. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2091. else:
  2092. if units is None:
  2093. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2094. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2095. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2096. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2097. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2098. except KeyError:
  2099. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2100. # TODO: Rethink this?
  2101. pass
  2102. except AttributeError:
  2103. log.debug(field)
  2104. def clear_pool(self):
  2105. """
  2106. Clear the multiprocessing pool and calls garbage collector.
  2107. :return: None
  2108. """
  2109. self.pool.close()
  2110. self.pool = Pool()
  2111. self.pool_recreated.emit(self.pool)
  2112. gc.collect()
  2113. def install_tools(self):
  2114. """
  2115. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2116. Instantiation of the Tools classes.
  2117. The order that the tools are installed is important as they can depend on each other install position.
  2118. :return: None
  2119. """
  2120. self.dblsidedtool = DblSidedTool(self)
  2121. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2122. self.measurement_tool = Measurement(self)
  2123. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2124. self.panelize_tool = Panelize(self)
  2125. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2126. self.film_tool = Film(self)
  2127. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2128. self.paste_tool = SolderPaste(self)
  2129. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2130. self.calculator_tool = ToolCalculator(self)
  2131. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2132. self.sub_tool = ToolSub(self)
  2133. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2134. self.move_tool = ToolMove(self)
  2135. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2136. before=self.ui.menueditorigin)
  2137. self.cutout_tool = CutOut(self)
  2138. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2139. before=self.measurement_tool.menuAction)
  2140. self.ncclear_tool = NonCopperClear(self)
  2141. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2142. before=self.measurement_tool.menuAction, separator=True)
  2143. self.paint_tool = ToolPaint(self)
  2144. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2145. before=self.measurement_tool.menuAction, separator=True)
  2146. self.transform_tool = ToolTransform(self)
  2147. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2148. self.properties_tool = Properties(self)
  2149. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2150. self.pdf_tool = ToolPDF(self)
  2151. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2152. separator=True)
  2153. self.image_tool = ToolImage(self)
  2154. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2155. separator=True)
  2156. self.pcb_wizard_tool = PcbWizard(self)
  2157. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2158. self.log.debug("Tools are installed.")
  2159. def remove_tools(self):
  2160. """
  2161. Will remove all the actions in the Tool menu.
  2162. :return: None
  2163. """
  2164. for act in self.ui.menutool.actions():
  2165. self.ui.menutool.removeAction(act)
  2166. def init_tools(self):
  2167. """
  2168. Initialize the Tool tab in the notebook side of the central widget.
  2169. Remove the actions in the Tools menu.
  2170. Instantiate again the FlatCAM tools (plugins).
  2171. All this is required when changing the layout: standard, compact etc.
  2172. :return: None
  2173. """
  2174. log.debug("init_tools()")
  2175. # delete the data currently in the Tools Tab and the Tab itself
  2176. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2177. if widget is not None:
  2178. widget.deleteLater()
  2179. self.ui.notebook.removeTab(2)
  2180. # rebuild the Tools Tab
  2181. self.ui.tool_tab = QtWidgets.QWidget()
  2182. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2183. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2184. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2185. self.ui.tool_scroll_area = VerticalScrollArea()
  2186. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2187. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2188. # first remove all of them
  2189. self.remove_tools()
  2190. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2191. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2192. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2193. # third install all of them
  2194. self.install_tools()
  2195. self.log.debug("Tools are initialized.")
  2196. # def parse_system_fonts(self):
  2197. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2198. # 'params': []})
  2199. def connect_toolbar_signals(self):
  2200. """
  2201. Reconnect the signals to the actions in the toolbar.
  2202. This has to be done each time after the FlatCAM tools are removed/installed.
  2203. :return: None
  2204. """
  2205. # Toolbar
  2206. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2207. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2208. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2209. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2210. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2211. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2212. self.ui.replot_btn.triggered.connect(self.plot_all)
  2213. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2214. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2215. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2216. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2217. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2218. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2219. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2220. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2221. self.ui.delete_btn.triggered.connect(self.on_delete)
  2222. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2223. # Tools Toolbar Signals
  2224. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2225. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2226. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2227. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2228. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2229. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2230. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2231. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2232. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2233. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2234. def object2editor(self):
  2235. """
  2236. Send the current Geometry or Excellon object (if any) into the it's editor.
  2237. :return: None
  2238. """
  2239. self.report_usage("object2editor()")
  2240. edited_object = self.collection.get_active()
  2241. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2242. isinstance(edited_object, FlatCAMExcellon):
  2243. pass
  2244. else:
  2245. self.inform.emit('[WARNING_NOTCL] %s' %
  2246. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2247. return
  2248. if isinstance(edited_object, FlatCAMGeometry):
  2249. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2250. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2251. # we set the notebook to hidden
  2252. self.ui.splitter.setSizes([0, 1])
  2253. if edited_object.multigeo is True:
  2254. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2255. if len(edited_tools) > 1:
  2256. self.inform.emit('[WARNING_NOTCL] %s' %
  2257. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2258. "is not possible.\n"
  2259. "Edit only one geometry at a time."))
  2260. # determine the tool dia of the selected tool
  2261. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2262. # now find the key in the edited_object.tools that has this tooldia
  2263. multi_tool = 1
  2264. for tool in edited_object.tools:
  2265. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2266. multi_tool = tool
  2267. break
  2268. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2269. else:
  2270. self.geo_editor.edit_fcgeometry(edited_object)
  2271. # set call source to the Editor we go into
  2272. self.call_source = 'geo_editor'
  2273. elif isinstance(edited_object, FlatCAMExcellon):
  2274. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2275. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2276. if self.ui.splitter.sizes()[0] == 0:
  2277. self.ui.splitter.setSizes([1, 1])
  2278. self.exc_editor.edit_fcexcellon(edited_object)
  2279. # set call source to the Editor we go into
  2280. self.call_source = 'exc_editor'
  2281. elif isinstance(edited_object, FlatCAMGerber):
  2282. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2283. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2284. if self.ui.splitter.sizes()[0] == 0:
  2285. self.ui.splitter.setSizes([1, 1])
  2286. self.grb_editor.edit_fcgerber(edited_object)
  2287. # set call source to the Editor we go into
  2288. self.call_source = 'grb_editor'
  2289. # make sure that we can't select another object while in Editor Mode:
  2290. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2291. self.ui.project_frame.setDisabled(True)
  2292. # delete any selection shape that might be active as they are not relevant in Editor
  2293. self.delete_selection_shape()
  2294. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2295. self.ui.plot_tab_area.protectTab(0)
  2296. self.inform.emit('[WARNING_NOTCL] %s' %
  2297. _("Editor is activated ..."))
  2298. self.should_we_save = True
  2299. def editor2object(self, cleanup=None):
  2300. """
  2301. Transfers the Geometry or Excellon from it's editor to the current object.
  2302. :return: None
  2303. """
  2304. self.report_usage("editor2object()")
  2305. # do not update a geometry or excellon object unless it comes out of an editor
  2306. if self.call_source != 'app':
  2307. edited_obj = self.collection.get_active()
  2308. if cleanup is None:
  2309. msgbox = QtWidgets.QMessageBox()
  2310. msgbox.setText(_("Do you want to save the edited object?"))
  2311. msgbox.setWindowTitle(_("Close Editor"))
  2312. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2313. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2314. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2315. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2316. msgbox.setDefaultButton(bt_yes)
  2317. msgbox.exec_()
  2318. response = msgbox.clickedButton()
  2319. if response == bt_yes:
  2320. # clean the Tools Tab
  2321. self.ui.tool_scroll_area.takeWidget()
  2322. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2323. self.ui.notebook.setTabText(2, "Tool")
  2324. if isinstance(edited_obj, FlatCAMGeometry):
  2325. obj_type = "Geometry"
  2326. if cleanup is None:
  2327. self.geo_editor.update_fcgeometry(edited_obj)
  2328. self.geo_editor.update_options(edited_obj)
  2329. self.geo_editor.deactivate()
  2330. # update the geo object options so it is including the bounding box values
  2331. try:
  2332. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2333. edited_obj.options['xmin'] = xmin
  2334. edited_obj.options['ymin'] = ymin
  2335. edited_obj.options['xmax'] = xmax
  2336. edited_obj.options['ymax'] = ymax
  2337. except AttributeError as e:
  2338. self.inform.emit('[WARNING] %s' %
  2339. _("Object empty after edit."))
  2340. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2341. elif isinstance(edited_obj, FlatCAMGerber):
  2342. obj_type = "Gerber"
  2343. if cleanup is None:
  2344. self.grb_editor.update_fcgerber()
  2345. self.grb_editor.update_options(edited_obj)
  2346. self.grb_editor.deactivate_grb_editor()
  2347. # delete the old object (the source object) if it was an empty one
  2348. if len(edited_obj.solid_geometry) == 0:
  2349. old_name = edited_obj.options['name']
  2350. self.collection.set_active(old_name)
  2351. self.collection.delete_active()
  2352. elif isinstance(edited_obj, FlatCAMExcellon):
  2353. obj_type = "Excellon"
  2354. if cleanup is None:
  2355. self.exc_editor.update_fcexcellon(edited_obj)
  2356. self.exc_editor.update_options(edited_obj)
  2357. self.exc_editor.deactivate()
  2358. else:
  2359. self.inform.emit('[WARNING_NOTCL] %s' %
  2360. _("Select a Gerber, Geometry or Excellon Object to update."))
  2361. return
  2362. self.inform.emit('[selected] %s %s' %
  2363. (obj_type, _("is updated, returning to App...")))
  2364. elif response == bt_no:
  2365. # clean the Tools Tab
  2366. self.ui.tool_scroll_area.takeWidget()
  2367. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2368. self.ui.notebook.setTabText(2, "Tool")
  2369. if isinstance(edited_obj, FlatCAMGeometry):
  2370. self.geo_editor.deactivate()
  2371. elif isinstance(edited_obj, FlatCAMGerber):
  2372. self.grb_editor.deactivate_grb_editor()
  2373. elif isinstance(edited_obj, FlatCAMExcellon):
  2374. self.exc_editor.deactivate()
  2375. # set focus on the project tab
  2376. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2377. else:
  2378. self.inform.emit('[WARNING_NOTCL] %s' %
  2379. _("Select a Gerber, Geometry or Excellon Object to update."))
  2380. return
  2381. elif response == bt_cancel:
  2382. return
  2383. else:
  2384. if isinstance(edited_obj, FlatCAMGeometry):
  2385. self.geo_editor.deactivate()
  2386. elif isinstance(edited_obj, FlatCAMGerber):
  2387. self.grb_editor.deactivate_grb_editor()
  2388. elif isinstance(edited_obj, FlatCAMExcellon):
  2389. self.exc_editor.deactivate()
  2390. else:
  2391. self.inform.emit('[WARNING_NOTCL] %s' %
  2392. _("Select a Gerber, Geometry or Excellon Object to update."))
  2393. return
  2394. # if notebook is hidden we show it
  2395. if self.ui.splitter.sizes()[0] == 0:
  2396. self.ui.splitter.setSizes([1, 1])
  2397. # restore the call_source to app
  2398. self.call_source = 'app'
  2399. edited_obj.plot()
  2400. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2401. self.ui.plot_tab_area.protectTab(0)
  2402. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2403. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2404. self.ui.project_frame.setDisabled(False)
  2405. def get_last_folder(self):
  2406. """
  2407. Get the folder path from where the last file was opened.
  2408. :return: String, last opened folder path
  2409. """
  2410. return self.defaults["global_last_folder"]
  2411. def get_last_save_folder(self):
  2412. """
  2413. Get the folder path from where the last file was saved.
  2414. :return: String, last saved folder path
  2415. """
  2416. loc = self.defaults["global_last_save_folder"]
  2417. if loc is None:
  2418. loc = self.defaults["global_last_folder"]
  2419. if loc is None:
  2420. loc = os.path.dirname(__file__)
  2421. return loc
  2422. def report_usage(self, resource):
  2423. """
  2424. Increments usage counter for the given resource
  2425. in self.defaults['global_stats'].
  2426. :param resource: Name of the resource.
  2427. :return: None
  2428. """
  2429. if resource in self.defaults['global_stats']:
  2430. self.defaults['global_stats'][resource] += 1
  2431. else:
  2432. self.defaults['global_stats'][resource] = 1
  2433. def init_tcl(self):
  2434. """
  2435. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2436. :return: None
  2437. """
  2438. if hasattr(self, 'tcl'):
  2439. # self.tcl = None
  2440. # TODO we need to clean non default variables and procedures here
  2441. # new object cannot be used here as it will not remember values created for next passes,
  2442. # because tcl was execudted in old instance of TCL
  2443. pass
  2444. else:
  2445. self.tcl = tk.Tcl()
  2446. self.setup_shell()
  2447. self.log.debug("TCL Shell has been initialized.")
  2448. # TODO: This shouldn't be here.
  2449. class TclErrorException(Exception):
  2450. """
  2451. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2452. """
  2453. pass
  2454. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2455. """
  2456. Shows a message on the FlatCAM Shell
  2457. :param msg: Message to display.
  2458. :param show: Opens the shell.
  2459. :param error: Shows the message as an error.
  2460. :param warning: Shows the message as an warning.
  2461. :param success: Shows the message as an success.
  2462. :param selected: Indicate that something was selected on canvas
  2463. :return: None
  2464. """
  2465. if show:
  2466. self.ui.shell_dock.show()
  2467. try:
  2468. if error:
  2469. self.shell.append_error(msg + "\n")
  2470. elif warning:
  2471. self.shell.append_warning(msg + "\n")
  2472. elif success:
  2473. self.shell.append_success(msg + "\n")
  2474. elif selected:
  2475. self.shell.append_selected(msg + "\n")
  2476. else:
  2477. self.shell.append_output(msg + "\n")
  2478. except AttributeError:
  2479. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2480. def raise_tcl_unknown_error(self, unknownException):
  2481. """
  2482. Raise exception if is different type than TclErrorException
  2483. this is here mainly to show unknown errors inside TCL shell console.
  2484. :param unknownException:
  2485. :return:
  2486. """
  2487. if not isinstance(unknownException, self.TclErrorException):
  2488. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2489. else:
  2490. raise unknownException
  2491. def display_tcl_error(self, error, error_info=None):
  2492. """
  2493. Escape bracket [ with '\' otherwise there is error
  2494. "ERROR: missing close-bracket" instead of real error
  2495. :param error: it may be text or exception
  2496. :param error_info: Some informations about the error
  2497. :return: None
  2498. """
  2499. if isinstance(error, Exception):
  2500. exc_type, exc_value, exc_traceback = error_info
  2501. if not isinstance(error, self.TclErrorException):
  2502. show_trace = 1
  2503. else:
  2504. show_trace = int(self.defaults['global_verbose_error_level'])
  2505. if show_trace > 0:
  2506. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2507. trc_formated = []
  2508. for a in reversed(trc):
  2509. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2510. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2511. else:
  2512. text = "%s" % error
  2513. else:
  2514. text = error
  2515. text = text.replace('[', '\\[').replace('"', '\\"')
  2516. self.tcl.eval('return -code error "%s"' % text)
  2517. def raise_tcl_error(self, text):
  2518. """
  2519. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2520. :param text: text of error
  2521. :return: raise exception
  2522. """
  2523. self.display_tcl_error(text)
  2524. raise self.TclErrorException(text)
  2525. def exec_command(self, text):
  2526. """
  2527. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2528. Also handles execution in separated threads
  2529. :param text: FlatCAM TclCommand with parameters
  2530. :return: output if there was any
  2531. """
  2532. self.report_usage('exec_command')
  2533. result = self.exec_command_test(text, False)
  2534. # MS: added this method call so the geometry is updated once the TCL command is executed
  2535. self.plot_all()
  2536. return result
  2537. def exec_command_test(self, text, reraise=True):
  2538. """
  2539. Same as exec_command(...) with additional control over exceptions.
  2540. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2541. :param text: Input command
  2542. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2543. :return: Output from the command
  2544. """
  2545. text = str(text)
  2546. try:
  2547. self.shell.open_proccessing() # Disables input box.
  2548. result = self.tcl.eval(str(text))
  2549. if result != 'None':
  2550. self.shell.append_output(result + '\n')
  2551. except tk.TclError as e:
  2552. # This will display more precise answer if something in TCL shell fails
  2553. result = self.tcl.eval("set errorInfo")
  2554. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2555. self.shell.append_error('ERROR: ' + result + '\n')
  2556. # Show error in console and just return or in test raise exception
  2557. if reraise:
  2558. raise e
  2559. finally:
  2560. self.shell.close_proccessing()
  2561. pass
  2562. return result
  2563. # """
  2564. # Code below is unsused. Saved for later.
  2565. # """
  2566. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2567. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2568. # self.log.debug(parts)
  2569. # try:
  2570. # if parts[0] not in commands:
  2571. # self.shell.append_error("Unknown command\n")
  2572. # return
  2573. #
  2574. # #import inspect
  2575. # #inspect.getargspec(someMethod)
  2576. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2577. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2578. # self.shell.append_error(
  2579. # "Command %s takes %d arguments. %d given.\n" %
  2580. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2581. # )
  2582. # return
  2583. #
  2584. # cmdfcn = commands[parts[0]]["fcn"]
  2585. # cmdconv = commands[parts[0]]["converters"]
  2586. # if len(parts) - 1 > 0:
  2587. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2588. # else:
  2589. # retval = cmdfcn()
  2590. # retfcn = commands[parts[0]]["retfcn"]
  2591. # if retval and retfcn(retval):
  2592. # self.shell.append_output(retfcn(retval) + "\n")
  2593. #
  2594. # except Exception as e:
  2595. # #self.shell.append_error(''.join(traceback.format_exc()))
  2596. # #self.shell.append_error("?\n")
  2597. # self.shell.append_error(str(e) + "\n")
  2598. def info(self, msg):
  2599. """
  2600. Informs the user. Normally on the status bar, optionally
  2601. also on the shell.
  2602. :param msg: Text to write.
  2603. :return: None
  2604. """
  2605. # Type of message in brackets at the beginning of the message.
  2606. match = re.search("\[([^\]]+)\](.*)", msg)
  2607. if match:
  2608. level = match.group(1)
  2609. msg_ = match.group(2)
  2610. self.ui.fcinfo.set_status(str(msg_), level=level)
  2611. if level.lower() == "error":
  2612. self.shell_message(msg, error=True, show=True)
  2613. elif level.lower() == "warning":
  2614. self.shell_message(msg, warning=True, show=True)
  2615. elif level.lower() == "error_notcl":
  2616. self.shell_message(msg, error=True, show=False)
  2617. elif level.lower() == "warning_notcl":
  2618. self.shell_message(msg, warning=True, show=False)
  2619. elif level.lower() == "success":
  2620. self.shell_message(msg, success=True, show=False)
  2621. elif level.lower() == "selected":
  2622. self.shell_message(msg, selected=True, show=False)
  2623. else:
  2624. self.shell_message(msg, show=False)
  2625. else:
  2626. self.ui.fcinfo.set_status(str(msg), level="info")
  2627. # make sure that if the message is to clear the infobar with a space
  2628. # is not printed over and over on the shell
  2629. if msg != '':
  2630. self.shell_message(msg)
  2631. def restore_toolbar_view(self):
  2632. """
  2633. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2634. was saved in the defaults dictionary.
  2635. :return: None
  2636. """
  2637. tb = self.defaults["global_toolbar_view"]
  2638. if tb & 1:
  2639. self.ui.toolbarfile.setVisible(True)
  2640. else:
  2641. self.ui.toolbarfile.setVisible(False)
  2642. if tb & 2:
  2643. self.ui.toolbargeo.setVisible(True)
  2644. else:
  2645. self.ui.toolbargeo.setVisible(False)
  2646. if tb & 4:
  2647. self.ui.toolbarview.setVisible(True)
  2648. else:
  2649. self.ui.toolbarview.setVisible(False)
  2650. if tb & 8:
  2651. self.ui.toolbartools.setVisible(True)
  2652. else:
  2653. self.ui.toolbartools.setVisible(False)
  2654. if tb & 16:
  2655. self.ui.exc_edit_toolbar.setVisible(True)
  2656. else:
  2657. self.ui.exc_edit_toolbar.setVisible(False)
  2658. if tb & 32:
  2659. self.ui.geo_edit_toolbar.setVisible(True)
  2660. else:
  2661. self.ui.geo_edit_toolbar.setVisible(False)
  2662. if tb & 64:
  2663. self.ui.grb_edit_toolbar.setVisible(True)
  2664. else:
  2665. self.ui.grb_edit_toolbar.setVisible(False)
  2666. if tb & 128:
  2667. self.ui.snap_toolbar.setVisible(True)
  2668. else:
  2669. self.ui.snap_toolbar.setVisible(False)
  2670. if tb & 256:
  2671. self.ui.toolbarshell.setVisible(True)
  2672. else:
  2673. self.ui.toolbarshell.setVisible(False)
  2674. def load_defaults(self, filename):
  2675. """
  2676. Loads the aplication's default settings from current_defaults.FlatConfig into
  2677. ``self.defaults``.
  2678. :return: None
  2679. """
  2680. try:
  2681. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2682. options = f.read()
  2683. f.close()
  2684. except IOError:
  2685. self.log.error("Could not load defaults file.")
  2686. self.inform.emit('[ERROR] %s' %
  2687. _("Could not load defaults file."))
  2688. # in case the defaults file can't be loaded, show all toolbars
  2689. self.defaults["global_toolbar_view"] = 511
  2690. return
  2691. try:
  2692. defaults = json.loads(options)
  2693. except:
  2694. # in case the defaults file can't be loaded, show all toolbars
  2695. self.defaults["global_toolbar_view"] = 511
  2696. e = sys.exc_info()[0]
  2697. App.log.error(str(e))
  2698. self.inform.emit('[ERROR] %s' %
  2699. _("Failed to parse defaults file."))
  2700. return
  2701. self.defaults.update(defaults)
  2702. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2703. # restore the toolbar view
  2704. self.restore_toolbar_view()
  2705. def on_import_preferences(self):
  2706. """
  2707. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2708. ``self.defaults``.
  2709. :return: None
  2710. """
  2711. self.report_usage("on_import_preferences")
  2712. App.log.debug("on_import_preferences()")
  2713. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2714. try:
  2715. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2716. directory=self.data_path,
  2717. filter=filter_)
  2718. except TypeError:
  2719. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2720. filter=filter_)
  2721. filename = str(filename)
  2722. if filename == "":
  2723. self.inform.emit('[WARNING_NOTCL] %s' %
  2724. _("FlatCAM preferences import cancelled."))
  2725. else:
  2726. try:
  2727. f = open(filename)
  2728. options = f.read()
  2729. f.close()
  2730. except IOError:
  2731. self.log.error("Could not load defaults file.")
  2732. self.inform.emit('[ERROR_NOTCL] %s' %
  2733. _("Could not load defaults file."))
  2734. return
  2735. try:
  2736. defaults_from_file = json.loads(options)
  2737. except Exception as e:
  2738. e = sys.exc_info()[0]
  2739. App.log.error(str(e))
  2740. self.inform.emit('[ERROR_NOTCL] %s' %
  2741. _("Failed to parse defaults file."))
  2742. return
  2743. self.defaults.update(defaults_from_file)
  2744. self.on_preferences_edited()
  2745. self.inform.emit('[success] %s: %s' %
  2746. (_("Imported Defaults from"), filename))
  2747. def on_export_preferences(self):
  2748. """
  2749. Save the defaults dictionary to a file.
  2750. :return: None
  2751. """
  2752. self.report_usage("on_export_preferences")
  2753. App.log.debug("on_export_preferences()")
  2754. defaults_file_content = None
  2755. self.date = str(datetime.today()).rpartition('.')[0]
  2756. self.date = ''.join(c for c in self.date if c not in ':-')
  2757. self.date = self.date.replace(' ', '_')
  2758. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2759. try:
  2760. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2761. caption=_("Export FlatCAM Preferences"),
  2762. directory=self.data_path + '/preferences_' + self.date,
  2763. filter=filter__
  2764. )
  2765. except TypeError:
  2766. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2767. filter=filter__)
  2768. filename = str(filename)
  2769. defaults_from_file = {}
  2770. if filename == "":
  2771. self.inform.emit('[WARNING_NOTCL] %s' %
  2772. _("FlatCAM preferences export cancelled."))
  2773. return
  2774. else:
  2775. try:
  2776. f = open(filename, 'w')
  2777. defaults_file_content = f.read()
  2778. f.close()
  2779. except PermissionError:
  2780. self.inform.emit('[WARNING] %s' %
  2781. _("Permission denied, saving not possible.\n"
  2782. "Most likely another app is holding the file open and not accessible."))
  2783. return
  2784. except IOError:
  2785. App.log.debug('Creating a new preferences file ...')
  2786. f = open(filename, 'w')
  2787. json.dump({}, f)
  2788. f.close()
  2789. except:
  2790. e = sys.exc_info()[0]
  2791. App.log.error("Could not load defaults file.")
  2792. App.log.error(str(e))
  2793. self.inform.emit('[ERROR_NOTCL] %s' %
  2794. _("Could not load preferences file."))
  2795. return
  2796. try:
  2797. defaults_from_file = json.loads(defaults_file_content)
  2798. except:
  2799. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2800. # Update options
  2801. self.defaults_read_form()
  2802. defaults_from_file.update(self.defaults)
  2803. self.propagate_defaults(silent=True)
  2804. # Save update options
  2805. try:
  2806. f = open(filename, "w")
  2807. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2808. f.close()
  2809. except:
  2810. self.inform.emit('[ERROR_NOTCL] %s' %
  2811. _("Failed to write defaults to file."))
  2812. return
  2813. if self.defaults["global_open_style"] is False:
  2814. self.file_opened.emit("preferences", filename)
  2815. self.file_saved.emit("preferences", filename)
  2816. self.inform.emit('[success] %s: %s' %
  2817. (_("Exported preferences to"), filename))
  2818. def on_preferences_open_folder(self):
  2819. """
  2820. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  2821. :return: None
  2822. """
  2823. self.report_usage("on_preferences_open_folder()")
  2824. if sys.platform == 'win32':
  2825. subprocess.Popen('explorer %s' % self.data_path)
  2826. elif sys.platform == 'darwin':
  2827. os.system('open "%s"' % self.data_path)
  2828. else:
  2829. subprocess.Popen(['xdg-open', self.data_path])
  2830. self.inform.emit('[success] %s' %
  2831. _("FlatCAM Preferences Folder opened."))
  2832. def save_geometry(self, x, y, width, height, notebook_width):
  2833. """
  2834. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2835. launch of the application.
  2836. :param x: X position of the main window
  2837. :param y: Y position of the main window
  2838. :param width: width of the main window
  2839. :param height: height of the main window
  2840. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2841. :return: None
  2842. """
  2843. self.defaults["global_def_win_x"] = x
  2844. self.defaults["global_def_win_y"] = y
  2845. self.defaults["global_def_win_w"] = width
  2846. self.defaults["global_def_win_h"] = height
  2847. self.defaults["global_def_notebook_width"] = notebook_width
  2848. self.save_defaults()
  2849. def message_dialog(self, title, message, kind="info"):
  2850. """
  2851. Builds and show a custom QMessageBox to be used in FlatCAM.
  2852. :param title: title of the QMessageBox
  2853. :param message: message to be displayed
  2854. :param kind: type of QMessageBox; will display a specific icon.
  2855. :return:
  2856. """
  2857. icon = {"info": QtWidgets.QMessageBox.Information,
  2858. "warning": QtWidgets.QMessageBox.Warning,
  2859. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2860. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2861. dlg.setText(message)
  2862. dlg.exec_()
  2863. def register_recent(self, kind, filename):
  2864. """
  2865. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2866. dictionary.
  2867. :param kind: type of file that was opened
  2868. :param filename: the path and file name for the file that was opened
  2869. :return:
  2870. """
  2871. self.log.debug("register_recent()")
  2872. self.log.debug(" %s" % kind)
  2873. self.log.debug(" %s" % filename)
  2874. record = {'kind': str(kind), 'filename': str(filename)}
  2875. if record in self.recent:
  2876. return
  2877. if record in self.recent_projects:
  2878. return
  2879. if record['kind'] == 'project':
  2880. self.recent_projects.insert(0, record)
  2881. else:
  2882. self.recent.insert(0, record)
  2883. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2884. self.recent.pop()
  2885. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2886. self.recent_projects.pop()
  2887. try:
  2888. f = open(self.data_path + '/recent.json', 'w')
  2889. except IOError:
  2890. App.log.error("Failed to open recent items file for writing.")
  2891. self.inform.emit('[ERROR_NOTCL] %s' %
  2892. _('Failed to open recent files file for writing.'))
  2893. return
  2894. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2895. f.close()
  2896. try:
  2897. fp = open(self.data_path + '/recent_projects.json', 'w')
  2898. except IOError:
  2899. App.log.error("Failed to open recent items file for writing.")
  2900. self.inform.emit('[ERROR_NOTCL] %s' %
  2901. _('Failed to open recent projects file for writing.'))
  2902. return
  2903. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2904. fp.close()
  2905. # Re-build the recent items menu
  2906. self.setup_recent_items()
  2907. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2908. """
  2909. Creates a new specialized FlatCAMObj and attaches it to the application,
  2910. this is, updates the GUI accordingly, any other records and plots it.
  2911. This method is thread-safe.
  2912. Notes:
  2913. * If the name is in use, the self.collection will modify it
  2914. when appending it to the collection. There is no need to handle
  2915. name conflicts here.
  2916. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2917. :type kind: str
  2918. :param name: Name for the object.
  2919. :type name: str
  2920. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2921. The function is called with 2 parameters: the new object and the App instance.
  2922. :type initialize: function
  2923. :param active:
  2924. :param fit:
  2925. :param plot: If to plot the resulting object
  2926. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2927. self.colleaction
  2928. :return: None
  2929. :rtype: None
  2930. """
  2931. App.log.debug("new_object()")
  2932. obj_plot = plot
  2933. obj_autoselected = autoselected
  2934. t0 = time.time() # Debug
  2935. # ## Create object
  2936. classdict = {
  2937. "gerber": FlatCAMGerber,
  2938. "excellon": FlatCAMExcellon,
  2939. "cncjob": FlatCAMCNCjob,
  2940. "geometry": FlatCAMGeometry
  2941. }
  2942. App.log.debug("Calling object constructor...")
  2943. obj = classdict[kind](name)
  2944. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2945. # Set options from "Project options" form
  2946. self.options_read_form()
  2947. # IMPORTANT
  2948. # The key names in defaults and options dictionary's are not random:
  2949. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2950. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2951. # the options from project options form into the self.options. After that, below, depending on the type of
  2952. # object that is created, it will strip the name of the object and the underline (if the original key was
  2953. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2954. # "toolchange"
  2955. for option in self.options:
  2956. if option.find(kind + "_") == 0:
  2957. oname = option[len(kind) + 1:]
  2958. obj.options[oname] = self.options[option]
  2959. obj.isHovering = False
  2960. obj.notHovering = True
  2961. # Initialize as per user request
  2962. # User must take care to implement initialize
  2963. # in a thread-safe way as is is likely that we
  2964. # have been invoked in a separate thread.
  2965. t1 = time.time()
  2966. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2967. try:
  2968. return_value = initialize(obj, self)
  2969. except Exception as e:
  2970. msg = '[ERROR_NOTCL] %s' % \
  2971. _("An internal error has ocurred. See shell.\n")
  2972. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2973. msg += traceback.format_exc()
  2974. self.inform.emit(msg)
  2975. # if str(e) == "Empty Geometry":
  2976. # self.inform.emit("[ERROR_NOTCL] )
  2977. # else:
  2978. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2979. return "fail"
  2980. t2 = time.time()
  2981. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2982. if return_value == 'fail':
  2983. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2984. return "fail"
  2985. # Check units and convert if necessary
  2986. # This condition CAN be true because initialize() can change obj.units
  2987. if self.options["units"].upper() != obj.units.upper():
  2988. self.inform.emit('%s: %s' %
  2989. (_("Converting units to "), self.options["units"]))
  2990. obj.convert_units(self.options["units"])
  2991. t3 = time.time()
  2992. self.log.debug("%f seconds converting units." % (t3 - t2))
  2993. # Create the bounding box for the object and then add the results to the obj.options
  2994. try:
  2995. xmin, ymin, xmax, ymax = obj.bounds()
  2996. obj.options['xmin'] = xmin
  2997. obj.options['ymin'] = ymin
  2998. obj.options['xmax'] = xmax
  2999. obj.options['ymax'] = ymax
  3000. except Exception as e:
  3001. log.warning("The object has no bounds properties. %s" % str(e))
  3002. return "fail"
  3003. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3004. # Move the object to the main thread and let the app know that it is available.
  3005. obj.moveToThread(self.main_thread)
  3006. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3007. return obj
  3008. def new_excellon_object(self):
  3009. """
  3010. Creates a new, blank Excellon object.
  3011. :return: None
  3012. """
  3013. self.report_usage("new_excellon_object()")
  3014. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3015. def new_geometry_object(self):
  3016. """
  3017. Creates a new, blank and single-tool Geometry object.
  3018. :return: None
  3019. """
  3020. self.report_usage("new_geometry_object()")
  3021. def initialize(obj, self):
  3022. obj.multitool = False
  3023. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3024. def new_gerber_object(self):
  3025. """
  3026. Creates a new, blank Gerber object.
  3027. :return: None
  3028. """
  3029. self.report_usage("new_gerber_object()")
  3030. def initialize(grb_obj, self):
  3031. grb_obj.multitool = False
  3032. grb_obj.source_file = []
  3033. grb_obj.multigeo = False
  3034. grb_obj.follow = False
  3035. grb_obj.apertures = {}
  3036. grb_obj.solid_geometry = []
  3037. try:
  3038. grb_obj.options['xmin'] = 0
  3039. grb_obj.options['ymin'] = 0
  3040. grb_obj.options['xmax'] = 0
  3041. grb_obj.options['ymax'] = 0
  3042. except KeyError:
  3043. pass
  3044. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3045. def on_object_created(self, obj, plot, autoselect):
  3046. """
  3047. Event callback for object creation.
  3048. It will add the new object to the collection. After that it will plot the object in a threaded way
  3049. :param obj: The newly created FlatCAM object.
  3050. :param plot: if the newly create object t obe plotted
  3051. :param autoselect: if the newly created object to be autoselected after creation
  3052. :return: None
  3053. """
  3054. t0 = time.time() # DEBUG
  3055. self.log.debug("on_object_created()")
  3056. # The Collection might change the name if there is a collision
  3057. self.collection.append(obj)
  3058. # after adding the object to the collection always update the list of objects that are in the collection
  3059. self.all_objects_list = self.collection.get_list()
  3060. # self.inform.emit('[selected] %s created & selected: %s' %
  3061. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3062. if obj.kind == 'gerber':
  3063. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3064. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3065. elif obj.kind == 'excellon':
  3066. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3067. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3068. elif obj.kind == 'cncjob':
  3069. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3070. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3071. elif obj.kind == 'geometry':
  3072. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3073. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3074. # update the SHELL auto-completer model with the name of the new object
  3075. self.myKeywords.append(obj.options['name'])
  3076. self.shell._edit.set_model_data(self.myKeywords)
  3077. self.ui.code_editor.set_model_data(self.myKeywords)
  3078. if autoselect:
  3079. # select the just opened object but deselect the previous ones
  3080. self.collection.set_all_inactive()
  3081. self.collection.set_active(obj.options["name"])
  3082. else:
  3083. self.collection.set_all_inactive()
  3084. # here it is done the object plotting
  3085. def worker_task(t_obj):
  3086. with self.proc_container.new(_("Plotting")):
  3087. if isinstance(t_obj, FlatCAMCNCjob):
  3088. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3089. else:
  3090. t_obj.plot()
  3091. t1 = time.time() # DEBUG
  3092. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3093. self.object_plotted.emit(t_obj)
  3094. # Send to worker
  3095. # self.worker.add_task(worker_task, [self])
  3096. if plot is True:
  3097. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3098. def on_object_changed(self, obj):
  3099. """
  3100. Called whenever the geometry of the object was changed in some way.
  3101. This require the update of it's bounding values so it can be the selected on canvas.
  3102. Update the bounding box data from obj.options
  3103. :param obj: the object that was changed
  3104. :return: None
  3105. """
  3106. xmin, ymin, xmax, ymax = obj.bounds()
  3107. obj.options['xmin'] = xmin
  3108. obj.options['ymin'] = ymin
  3109. obj.options['xmax'] = xmax
  3110. obj.options['ymax'] = ymax
  3111. log.debug("Object changed, updating the bounding box data on self.options")
  3112. # delete the old selection shape
  3113. self.delete_selection_shape()
  3114. self.should_we_save = True
  3115. def on_object_plotted(self, obj):
  3116. """
  3117. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3118. :param obj: object to be fit into view
  3119. :return: None
  3120. """
  3121. self.on_zoom_fit(None)
  3122. def options_read_form(self):
  3123. """
  3124. Same as it's equivalent from the defaults.
  3125. self.options use to store the preferences per project. No longer used.
  3126. :return: None
  3127. """
  3128. for option in self.options_form_fields:
  3129. self.options[option] = self.options_form_fields[option].get_value()
  3130. def options_write_form(self):
  3131. """
  3132. Same as it's equivalent from the defaults.
  3133. self.options use to store the preferences per project. No longer used.
  3134. :return: None
  3135. """
  3136. for option in self.options:
  3137. self.options_write_form_field(option)
  3138. def options_write_form_field(self, field):
  3139. """
  3140. Same as it's equivalent from the defaults.
  3141. self.options use to store the preferences per project. No longer used.
  3142. :return: None
  3143. """
  3144. try:
  3145. self.options_form_fields[field].set_value(self.options[field])
  3146. except KeyError:
  3147. # Changed from error to debug. This allows to have data stored
  3148. # which is not user-editable.
  3149. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3150. pass
  3151. def on_about(self):
  3152. """
  3153. Displays the "about" dialog found in the Menu --> Help.
  3154. :return: None
  3155. """
  3156. self.report_usage("on_about")
  3157. version = self.version
  3158. version_date = self.version_date
  3159. beta = self.beta
  3160. class AboutDialog(QtWidgets.QDialog):
  3161. def __init__(self, parent=None):
  3162. QtWidgets.QDialog.__init__(self, parent)
  3163. # Icon and title
  3164. self.setWindowIcon(parent.app_icon)
  3165. self.setWindowTitle(_("About FlatCAM"))
  3166. self.resize(600, 200)
  3167. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3168. # self.setStyleSheet(
  3169. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3170. # "background-attachment: fixed"
  3171. # )
  3172. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3173. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3174. # palette = QtGui.QPalette()
  3175. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3176. # self.setPalette(palette)
  3177. logo = QtWidgets.QLabel()
  3178. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3179. title = QtWidgets.QLabel(
  3180. _(
  3181. "<font size=8><B>FlatCAM</B></font><BR>"
  3182. "2D Computer-Aided Printed Circuit Board<BR>"
  3183. "Manufacturing.<BR>"
  3184. "<BR>"
  3185. "<BR>"
  3186. "<B>Development</B> "
  3187. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  3188. "<b>DOWNLOAD</B> area "
  3189. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  3190. ""
  3191. )
  3192. )
  3193. title.setOpenExternalLinks(True)
  3194. closebtn = QtWidgets.QPushButton(_("Close"))
  3195. tab_widget = QtWidgets.QTabWidget()
  3196. description_label = QtWidgets.QLabel(
  3197. _(
  3198. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3199. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>"
  3200. ).format(version=version,
  3201. beta=('BETA' if beta else ''),
  3202. date=version_date,
  3203. arch=platform.architecture()[0])
  3204. )
  3205. description_label.setOpenExternalLinks(True)
  3206. programmers_label = QtWidgets.QLabel(
  3207. _(
  3208. "Juan Pablo Caram <BR>"
  3209. "<BR>"
  3210. "Denis Hayrullin<BR>"
  3211. "Kamil Sopko<BR>"
  3212. "Marius Stanciu<BR>"
  3213. "Matthieu Berthomé<BR><Br>"
  3214. "and many others found "
  3215. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  3216. "<BR>"
  3217. )
  3218. )
  3219. programmers_label.setOpenExternalLinks(True)
  3220. translators_label = QtWidgets.QLabel(
  3221. _(
  3222. "Brasilian - Portuguese: \t\t Carlos Stein\n"
  3223. "German: \t\t Marius Stanciu (Google-Translation)\n"
  3224. "Romanian: \t\t Marius Stanciu\n"
  3225. "Russian: \t\t Andrey Kultyapov <camellan@yandex.ru>\n"
  3226. "Spanish: \t\t Marius Stanciu (Google-Translation)\n"
  3227. )
  3228. )
  3229. translators_label.setOpenExternalLinks(True)
  3230. license_label = QtWidgets.QLabel(
  3231. _(
  3232. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3233. 'Licensed under the MIT license:\n'
  3234. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3235. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3236. 'of this software and associated documentation files (the "Software"), to deal\n'
  3237. 'in the Software without restriction, including without limitation the rights\n'
  3238. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3239. 'copies of the Software, and to permit persons to whom the Software is\n'
  3240. ' furnished to do so, subject to the following conditions:\n\n'
  3241. 'The above copyright notice and this permission notice shall be included in\n'
  3242. 'all copies or substantial portions of the Software.\n\n'
  3243. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3244. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3245. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3246. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3247. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3248. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3249. 'THE SOFTWARE.'
  3250. )
  3251. )
  3252. license_label.setOpenExternalLinks(True)
  3253. # layouts
  3254. layout1 = QtWidgets.QVBoxLayout()
  3255. layout1_1 = QtWidgets.QHBoxLayout()
  3256. layout1_2 = QtWidgets.QHBoxLayout()
  3257. layout2 = QtWidgets.QHBoxLayout()
  3258. layout3 = QtWidgets.QHBoxLayout()
  3259. self.setLayout(layout1)
  3260. layout1.addLayout(layout1_1)
  3261. layout1.addLayout(layout1_2)
  3262. layout1.addLayout(layout2)
  3263. layout1.addLayout(layout3)
  3264. layout1_1.addStretch()
  3265. layout1_1.addWidget(description_label)
  3266. layout1_2.addWidget(tab_widget)
  3267. self.splash_tab = QtWidgets.QWidget()
  3268. self.splash_tab.setObjectName("splash_about")
  3269. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3270. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3271. tab_widget.addTab(self.splash_tab, _("Splash"))
  3272. self.programmmers_tab = QtWidgets.QWidget()
  3273. self.programmmers_tab.setObjectName("programmers_about")
  3274. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3275. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3276. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3277. self.translators_tab = QtWidgets.QWidget()
  3278. self.translators_tab.setObjectName("translators_about")
  3279. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3280. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3281. tab_widget.addTab(self.translators_tab, _("Translators"))
  3282. self.license_tab = QtWidgets.QWidget()
  3283. self.license_tab.setObjectName("license_about")
  3284. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3285. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3286. tab_widget.addTab(self.license_tab, _("License"))
  3287. self.splash_tab_layout.addWidget(logo, stretch=0)
  3288. self.splash_tab_layout.addWidget(title, stretch=1)
  3289. self.programmmers_tab_layout.addWidget(programmers_label)
  3290. self.programmmers_tab_layout.addStretch()
  3291. self.translators_tab_layout.addWidget(translators_label)
  3292. self.translators_tab_layout.addStretch()
  3293. self.license_tab_layout.addWidget(license_label)
  3294. self.license_tab_layout.addStretch()
  3295. layout3.addStretch()
  3296. layout3.addWidget(closebtn)
  3297. closebtn.clicked.connect(self.accept)
  3298. AboutDialog(self.ui).exec_()
  3299. def on_file_savedefaults(self):
  3300. """
  3301. Callback for menu item File->Save Defaults. Saves application default options
  3302. ``self.defaults`` to current_defaults.FlatConfig.
  3303. :return: None
  3304. """
  3305. self.save_defaults()
  3306. # def on_app_exit(self):
  3307. # self.report_usage("on_app_exit()")
  3308. #
  3309. # if self.collection.get_list():
  3310. # msgbox = QtWidgets.QMessageBox()
  3311. # # msgbox.setText("<B>Save changes ...</B>")
  3312. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3313. # "\n"
  3314. # "Do you want to Save the project?")
  3315. # msgbox.setWindowTitle("Save changes")
  3316. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3317. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3318. # QtWidgets.QMessageBox.Cancel)
  3319. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3320. #
  3321. # response = msgbox.exec_()
  3322. #
  3323. # if response == QtWidgets.QMessageBox.Yes:
  3324. # self.on_file_saveprojectas(thread=False)
  3325. # elif response == QtWidgets.QMessageBox.Cancel:
  3326. # return
  3327. # self.save_defaults()
  3328. # else:
  3329. # self.save_defaults()
  3330. # log.debug("Application defaults saved ... Exit event.")
  3331. # QtWidgets.qApp.quit()
  3332. def save_defaults(self, silent=False, data_path=None):
  3333. """
  3334. Saves application default options
  3335. ``self.defaults`` to current_defaults.FlatConfig file.
  3336. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3337. used at the next launch of the application.
  3338. :param silent: whether to display a message in status bar or not; boolean
  3339. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3340. When the application is portable it should be a mobile location.
  3341. :return: None
  3342. """
  3343. self.report_usage("save_defaults")
  3344. if data_path is None:
  3345. data_path = self.data_path
  3346. # Read options from file
  3347. try:
  3348. f = open(data_path + "/current_defaults.FlatConfig")
  3349. defaults_file_content = f.read()
  3350. f.close()
  3351. except:
  3352. e = sys.exc_info()[0]
  3353. App.log.error("Could not load defaults file.")
  3354. App.log.error(str(e))
  3355. self.inform.emit('[ERROR_NOTCL] %s' %
  3356. _("Could not load defaults file."))
  3357. return
  3358. try:
  3359. defaults = json.loads(defaults_file_content)
  3360. except:
  3361. e = sys.exc_info()[0]
  3362. App.log.error("Failed to parse defaults file.")
  3363. App.log.error(str(e))
  3364. self.inform.emit('[ERROR_NOTCL] %s' %
  3365. _("Failed to parse defaults file."))
  3366. return
  3367. # Update options
  3368. self.defaults_read_form()
  3369. defaults.update(self.defaults)
  3370. self.propagate_defaults(silent=True)
  3371. # Save the toolbar view
  3372. tb_status = 0
  3373. if self.ui.toolbarfile.isVisible():
  3374. tb_status += 1
  3375. if self.ui.toolbargeo.isVisible():
  3376. tb_status += 2
  3377. if self.ui.toolbarview.isVisible():
  3378. tb_status += 4
  3379. if self.ui.toolbartools.isVisible():
  3380. tb_status += 8
  3381. if self.ui.exc_edit_toolbar.isVisible():
  3382. tb_status += 16
  3383. if self.ui.geo_edit_toolbar.isVisible():
  3384. tb_status += 32
  3385. if self.ui.grb_edit_toolbar.isVisible():
  3386. tb_status += 64
  3387. if self.ui.snap_toolbar.isVisible():
  3388. tb_status += 128
  3389. if self.ui.toolbarshell.isVisible():
  3390. tb_status += 256
  3391. self.defaults["global_toolbar_view"] = tb_status
  3392. # Save update options
  3393. try:
  3394. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3395. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3396. f.close()
  3397. except:
  3398. self.inform.emit('[ERROR_NOTCL] %s' %
  3399. _("Failed to write defaults to file."))
  3400. return
  3401. if not silent:
  3402. self.inform.emit('[success] %s' %
  3403. _("Preferences saved."))
  3404. def save_factory_defaults(self, silent=False, data_path=None):
  3405. """
  3406. Saves application factory default options
  3407. ``self.defaults`` to factory_defaults.FlatConfig.
  3408. It's a one time job done just after the first install.
  3409. :param silent: whether to display a message in status bar or not; boolean
  3410. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3411. When the application is portable it should be a mobile location.
  3412. :return: None
  3413. """
  3414. self.report_usage("save_factory_defaults")
  3415. if data_path is None:
  3416. data_path = self.data_path
  3417. # Read options from file
  3418. try:
  3419. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3420. factory_defaults_file_content = f_f_def.read()
  3421. f_f_def.close()
  3422. except:
  3423. e = sys.exc_info()[0]
  3424. App.log.error("Could not load factory defaults file.")
  3425. App.log.error(str(e))
  3426. self.inform.emit('[ERROR_NOTCL] %s' %
  3427. _("Could not load factory defaults file."))
  3428. return
  3429. try:
  3430. factory_defaults = json.loads(factory_defaults_file_content)
  3431. except:
  3432. e = sys.exc_info()[0]
  3433. App.log.error("Failed to parse factory defaults file.")
  3434. App.log.error(str(e))
  3435. self.inform.emit('[ERROR_NOTCL] %s' %
  3436. _("Failed to parse factory defaults file."))
  3437. return
  3438. # Update options
  3439. self.defaults_read_form()
  3440. factory_defaults.update(self.defaults)
  3441. self.propagate_defaults(silent=True)
  3442. # Save update options
  3443. try:
  3444. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3445. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3446. f_f_def_s.close()
  3447. except:
  3448. self.inform.emit('[ERROR_NOTCL] %s' %
  3449. _("Failed to write factory defaults to file."))
  3450. return
  3451. if silent is False:
  3452. self.inform.emit(_("Factory defaults saved."))
  3453. def final_save(self):
  3454. """
  3455. Callback for doing a preferences save to file whenever the application is about to quit.
  3456. If the project has changes, it will ask the user to save the project.
  3457. :return: None
  3458. """
  3459. if self.save_in_progress:
  3460. self.inform.emit('[WARNING_NOTCL] %s' %
  3461. _("Application is saving the project. Please wait ..."))
  3462. return
  3463. if self.should_we_save and self.collection.get_list():
  3464. msgbox = QtWidgets.QMessageBox()
  3465. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3466. "\n"
  3467. "Do you want to Save the project?"))
  3468. msgbox.setWindowTitle(_("Save changes"))
  3469. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3470. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3471. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3472. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3473. msgbox.setDefaultButton(bt_yes)
  3474. msgbox.exec_()
  3475. response = msgbox.clickedButton()
  3476. if response == bt_yes:
  3477. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3478. elif response == bt_no:
  3479. self.quit_application()
  3480. elif response == bt_cancel:
  3481. return
  3482. else:
  3483. self.quit_application()
  3484. def quit_application(self):
  3485. """
  3486. Called (as a pyslot or not) when the application is quit.
  3487. :return: None
  3488. """
  3489. self.save_defaults()
  3490. log.debug("App.final_save() --> App Defaults saved.")
  3491. # save toolbar state to file
  3492. settings = QSettings("Open Source", "FlatCAM")
  3493. settings.setValue('saved_gui_state', self.ui.saveState())
  3494. settings.setValue('maximized_gui', self.ui.isMaximized())
  3495. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3496. settings.setValue('notebook_font_size',
  3497. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3498. settings.setValue('axis_font_size',
  3499. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3500. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3501. # This will write the setting to the platform specific storage.
  3502. del settings
  3503. log.debug("App.final_save() --> App UI state saved.")
  3504. QtWidgets.qApp.quit()
  3505. def on_portable_checked(self, state):
  3506. """
  3507. Callback called when the checkbox in Preferences GUI is checked.
  3508. It will set the application as portable by creating the preferences and recent files in the
  3509. 'config' folder found in the FlatCAM installation folder.
  3510. :param state: boolean, the state of the checkbox when clicked/checked
  3511. :return:
  3512. """
  3513. line_no = 0
  3514. data = None
  3515. if sys.platform != 'win32':
  3516. # this won't work in Linux or MacOS
  3517. return
  3518. # test if the app was frozen and choose the path for the configuration file
  3519. if getattr(sys, "frozen", False) is True:
  3520. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3521. else:
  3522. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3523. config_file = current_data_path + '\\configuration.txt'
  3524. try:
  3525. with open(config_file, 'r') as f:
  3526. try:
  3527. data = f.readlines()
  3528. except Exception as e:
  3529. log.debug('App.__init__() -->%s' % str(e))
  3530. return
  3531. except FileNotFoundError:
  3532. pass
  3533. for line in data:
  3534. line = line.strip('\n')
  3535. param = str(line).rpartition('=')
  3536. if param[0] == 'portable':
  3537. break
  3538. line_no += 1
  3539. if state:
  3540. data[line_no] = 'portable=True\n'
  3541. # create the new defauults files
  3542. # create current_defaults.FlatConfig file if there is none
  3543. try:
  3544. f = open(current_data_path + '/current_defaults.FlatConfig')
  3545. f.close()
  3546. except IOError:
  3547. App.log.debug('Creating empty current_defaults.FlatConfig')
  3548. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3549. json.dump({}, f)
  3550. f.close()
  3551. # create factory_defaults.FlatConfig file if there is none
  3552. try:
  3553. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3554. f.close()
  3555. except IOError:
  3556. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3557. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3558. json.dump({}, f)
  3559. f.close()
  3560. try:
  3561. f = open(current_data_path + '/recent.json')
  3562. f.close()
  3563. except IOError:
  3564. App.log.debug('Creating empty recent.json')
  3565. f = open(current_data_path + '/recent.json', 'w')
  3566. json.dump([], f)
  3567. f.close()
  3568. try:
  3569. fp = open(current_data_path + '/recent_projects.json')
  3570. fp.close()
  3571. except IOError:
  3572. App.log.debug('Creating empty recent_projects.json')
  3573. fp = open(current_data_path + '/recent_projects.json', 'w')
  3574. json.dump([], fp)
  3575. fp.close()
  3576. # save the current defaults to the new defaults file
  3577. self.save_defaults(silent=True, data_path=current_data_path)
  3578. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3579. else:
  3580. data[line_no] = 'portable=False\n'
  3581. with open(config_file, 'w') as f:
  3582. f.writelines(data)
  3583. def on_toggle_shell(self):
  3584. """
  3585. Toggle shell: if is visible close it, if it is closed then open it
  3586. :return:
  3587. """
  3588. self.report_usage("on_toggle_shell()")
  3589. if self.ui.shell_dock.isVisible():
  3590. self.ui.shell_dock.hide()
  3591. else:
  3592. self.ui.shell_dock.show()
  3593. def on_register_files(self, obj_type=None):
  3594. """
  3595. Called whenever there is a need to register file extensions with FlatCAM.
  3596. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3597. :param obj_type: the type of object to be register for.
  3598. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3599. :return: None
  3600. """
  3601. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3602. new_reg_path = 'Software\\Classes\\'
  3603. # find if the current user is admin
  3604. try:
  3605. is_admin = os.getuid() == 0
  3606. except AttributeError:
  3607. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3608. if is_admin is True:
  3609. root_path = winreg.HKEY_CLASSES_ROOT
  3610. else:
  3611. root_path = winreg.HKEY_CURRENT_USER
  3612. # create the keys
  3613. def set_reg(name, root_path, new_reg_path, value):
  3614. try:
  3615. winreg.CreateKey(root_path, new_reg_path)
  3616. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3617. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3618. return True
  3619. except WindowsError:
  3620. return False
  3621. # delete key in registry
  3622. def delete_reg(root_path, reg_path, key_to_del):
  3623. key_to_del_path = reg_path + key_to_del
  3624. try:
  3625. winreg.DeleteKey(root_path, key_to_del_path)
  3626. return True
  3627. except WindowsError:
  3628. return False
  3629. if obj_type is None or obj_type == 'excellon':
  3630. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3631. exc_list = [x for x in exc_list if x != '']
  3632. # register all keys in the Preferences window
  3633. for ext in exc_list:
  3634. new_k = new_reg_path + ext
  3635. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3636. # and unregister those that are no longer in the Preferences windows but are in the file
  3637. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3638. if ext not in exc_list:
  3639. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3640. # now write the updated extensions to the self.defaults
  3641. new_ext = ''
  3642. for ext in exc_list:
  3643. new_ext = new_ext + ext + ', '
  3644. self.defaults["fa_excellon"] = new_ext
  3645. self.inform.emit(_("[success] Selected Excellon file extensions registered with FlatCAM."))
  3646. if obj_type is None or obj_type == 'gcode':
  3647. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3648. gco_list = [x for x in gco_list if x != '']
  3649. # register all keys in the Preferences window
  3650. for ext in gco_list:
  3651. new_k = new_reg_path + ext
  3652. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3653. # and unregister those that are no longer in the Preferences windows but are in the file
  3654. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3655. if ext not in gco_list:
  3656. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3657. # now write the updated extensions to the self.defaults
  3658. new_ext = ''
  3659. for ext in gco_list:
  3660. new_ext = new_ext + ext + ', '
  3661. self.defaults["fa_gcode"] = new_ext
  3662. self.inform.emit('[success] %s' %
  3663. _("Selected GCode file extensions registered with FlatCAM."))
  3664. if obj_type is None or obj_type == 'gerber':
  3665. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3666. grb_list = [x for x in grb_list if x != '']
  3667. # register all keys in the Preferences window
  3668. for ext in grb_list:
  3669. new_k = new_reg_path + ext
  3670. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3671. # and unregister those that are no longer in the Preferences windows but are in the file
  3672. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3673. if ext not in grb_list:
  3674. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3675. # now write the updated extensions to the self.defaults
  3676. new_ext = ''
  3677. for ext in grb_list:
  3678. new_ext = new_ext + ext + ', '
  3679. self.defaults["fa_gerber"] = new_ext
  3680. self.inform.emit('[success] %s' %
  3681. _("Selected Gerber file extensions registered with FlatCAM."))
  3682. def on_edit_join(self, name=None):
  3683. """
  3684. Callback for Edit->Join. Joins the selected geometry objects into
  3685. a new one.
  3686. :return: None
  3687. """
  3688. self.report_usage("on_edit_join()")
  3689. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3690. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3691. tooldias = []
  3692. geo_type_list = set()
  3693. objs = self.collection.get_selected()
  3694. for obj in objs:
  3695. geo_type_list.add(obj.multigeo)
  3696. # if len(geo_type_list) == 1 means that all list elements are the same
  3697. if len(geo_type_list) != 1:
  3698. self.inform.emit('[ERROR] %s' %
  3699. _("Failed join. The Geometry objects are of different types.\n"
  3700. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3701. "convert from one to another and retry joining \n"
  3702. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3703. "the result may not be what was expected. \n"
  3704. "Check the generated GCODE."))
  3705. return
  3706. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3707. if True in geo_type_list:
  3708. def initialize(obj, app):
  3709. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3710. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3711. for v in obj.tools.values():
  3712. v['data']['name'] = obj_name_multi
  3713. self.new_object("geometry", obj_name_multi, initialize)
  3714. else:
  3715. def initialize(obj, app):
  3716. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3717. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3718. for v in obj.tools.values():
  3719. v['data']['name'] = obj_name_single
  3720. self.new_object("geometry", obj_name_single, initialize)
  3721. self.should_we_save = True
  3722. def on_edit_join_exc(self):
  3723. """
  3724. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3725. a new Excellon.
  3726. :return: None
  3727. """
  3728. self.report_usage("on_edit_join_exc()")
  3729. objs = self.collection.get_selected()
  3730. for obj in objs:
  3731. if not isinstance(obj, FlatCAMExcellon):
  3732. self.inform.emit('[ERROR_NOTCL] %s' %
  3733. _("Failed. Excellon joining works only on Excellon objects."))
  3734. return
  3735. def initialize(obj, app):
  3736. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3737. self.new_object("excellon", 'Combo_Excellon', initialize)
  3738. self.should_we_save = True
  3739. def on_edit_join_grb(self):
  3740. """
  3741. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3742. a new Gerber object.
  3743. :return: None
  3744. """
  3745. self.report_usage("on_edit_join_grb()")
  3746. objs = self.collection.get_selected()
  3747. for obj in objs:
  3748. if not isinstance(obj, FlatCAMGerber):
  3749. self.inform.emit('[ERROR_NOTCL] %s' %
  3750. _("Failed. Gerber joining works only on Gerber objects."))
  3751. return
  3752. def initialize(obj, app):
  3753. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3754. self.new_object("gerber", 'Combo_Gerber', initialize)
  3755. self.should_we_save = True
  3756. def on_convert_singlegeo_to_multigeo(self):
  3757. """
  3758. Called for converting a Geometry object from single-geo to multi-geo.
  3759. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3760. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3761. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3762. the solid-geometry of that tool.
  3763. :return: None
  3764. """
  3765. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3766. obj = self.collection.get_active()
  3767. if obj is None:
  3768. self.inform.emit('[ERROR_NOTCL] %s' %
  3769. _("Failed. Select a Geometry Object and try again."))
  3770. return
  3771. if not isinstance(obj, FlatCAMGeometry):
  3772. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3773. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3774. return
  3775. obj.multigeo = True
  3776. for tooluid, dict_value in obj.tools.items():
  3777. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3778. if not isinstance(obj.solid_geometry, list):
  3779. obj.solid_geometry = [obj.solid_geometry]
  3780. obj.solid_geometry[:] = []
  3781. obj.plot()
  3782. self.should_we_save = True
  3783. self.inform.emit('[success] %s' %
  3784. _("A Geometry object was converted to MultiGeo type."))
  3785. def on_convert_multigeo_to_singlegeo(self):
  3786. """
  3787. Called for converting a Geometry object from multi-geo to single-geo.
  3788. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3789. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3790. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3791. the solid-geometry of that tool.
  3792. :return: None
  3793. """
  3794. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3795. obj = self.collection.get_active()
  3796. if obj is None:
  3797. self.inform.emit('[ERROR_NOTCL] %s' %
  3798. _("Failed. Select a Geometry Object and try again."))
  3799. return
  3800. if not isinstance(obj, FlatCAMGeometry):
  3801. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3802. (_("Expected a FlatCAMGeometry, got %s"), type(obj)))
  3803. return
  3804. obj.multigeo = False
  3805. total_solid_geometry = []
  3806. for tooluid, dict_value in obj.tools.items():
  3807. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3808. # clear the original geometry
  3809. dict_value['solid_geometry'][:] = []
  3810. obj.solid_geometry = deepcopy(total_solid_geometry)
  3811. obj.plot()
  3812. self.should_we_save = True
  3813. self.inform.emit('[success] %s' %
  3814. _("A Geometry object was converted to SingleGeo type."))
  3815. def on_options_dict_change(self, field):
  3816. """
  3817. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  3818. current project. This feature is no longer used.
  3819. :param field:
  3820. :return:
  3821. """
  3822. self.options_write_form_field(field)
  3823. if field == "units":
  3824. self.set_screen_units(self.options['units'])
  3825. def on_defaults_dict_change(self, field):
  3826. """
  3827. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3828. Edit -> Preferences tab window.
  3829. :param field: the key of the self.defaults dictionary that was changed.
  3830. :return: None
  3831. """
  3832. self.defaults_write_form_field(field)
  3833. if field == "units":
  3834. self.set_screen_units(self.defaults['units'])
  3835. def set_screen_units(self, units):
  3836. """
  3837. Set the FlatCAM units on the status bar.
  3838. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3839. :return: None
  3840. """
  3841. self.ui.units_label.setText("[" + units.lower() + "]")
  3842. def on_toggle_units(self, no_pref=False):
  3843. """
  3844. Callback for the Units radio-button change in the Preferences tab.
  3845. Changes the application's default units adn for the project too.
  3846. If changing the project's units, the change propagates to all of
  3847. the objects in the project.
  3848. :return: None
  3849. """
  3850. self.report_usage("on_toggle_units")
  3851. if self.toggle_units_ignore:
  3852. return
  3853. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3854. # If option is the same, then ignore
  3855. if new_units == self.defaults["units"].upper():
  3856. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3857. return
  3858. # Options to scale
  3859. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3860. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3861. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3862. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3863. "excellon_z_pdepth",
  3864. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3865. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3866. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3867. "geometry_feedrate_probe",
  3868. 'cncjob_tooldia',
  3869. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3870. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  3871. "tools_2sided_drilldia", "tools_film_boundary",
  3872. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3873. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3874. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3875. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3876. "tools_transform_offset_y",
  3877. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3878. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3879. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3880. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3881. 'global_gridx', 'global_gridy', 'global_snap_max']
  3882. def scale_options(sfactor):
  3883. for dim in dimensions:
  3884. if dim == 'excellon_toolchangexy':
  3885. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3886. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3887. coords_xy[0] *= sfactor
  3888. coords_xy[1] *= sfactor
  3889. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3890. elif dim == 'geometry_toolchangexy':
  3891. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3892. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3893. coords_xy[0] *= sfactor
  3894. coords_xy[1] *= sfactor
  3895. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3896. elif dim == 'geometry_cnctooldia':
  3897. tools_diameters = []
  3898. try:
  3899. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3900. tools_diameters = [eval(a) for a in tools_string if a != '']
  3901. except Exception as e:
  3902. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3903. self.options['geometry_cnctooldia'] = ''
  3904. for t in range(len(tools_diameters)):
  3905. tools_diameters[t] *= sfactor
  3906. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3907. elif dim == 'tools_ncctools':
  3908. ncctools = []
  3909. try:
  3910. tools_string = self.defaults["tools_ncctools"].split(",")
  3911. ncctools = [eval(a) for a in tools_string if a != '']
  3912. except Exception as e:
  3913. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3914. self.options['tools_ncctools'] = ''
  3915. for t in range(len(ncctools)):
  3916. ncctools[t] *= sfactor
  3917. self.options['tools_ncctools'] += "%f," % ncctools[t]
  3918. elif dim == 'tools_solderpaste_tools':
  3919. sptools = []
  3920. try:
  3921. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3922. sptools = [eval(a) for a in tools_string if a != '']
  3923. except Exception as e:
  3924. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3925. self.options['tools_solderpaste_tools'] = ""
  3926. for t in range(len(sptools)):
  3927. sptools[t] *= sfactor
  3928. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  3929. elif dim == 'tools_solderpaste_xy_toolchange':
  3930. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3931. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3932. sp_coords[0] *= sfactor
  3933. sp_coords[1] *= sfactor
  3934. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3935. elif dim == 'global_gridx' or dim == 'global_gridy':
  3936. if new_units == 'IN':
  3937. val = 0.1
  3938. try:
  3939. val = float(self.defaults[dim]) * sfactor
  3940. except Exception as e:
  3941. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3942. self.options[dim] = float('%.6f' % val)
  3943. else:
  3944. val = 0.1
  3945. try:
  3946. val = float(self.defaults[dim]) * sfactor
  3947. except Exception as e:
  3948. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3949. self.options[dim] = float('%.4f' % val)
  3950. else:
  3951. val = 0.1
  3952. try:
  3953. val = float(self.options[dim]) * sfactor
  3954. except Exception as e:
  3955. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3956. self.options[dim] = val
  3957. def scale_defaults(sfactor):
  3958. for dim in dimensions:
  3959. if dim == 'excellon_toolchangexy':
  3960. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3961. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3962. coords_xy[0] *= sfactor
  3963. coords_xy[1] *= sfactor
  3964. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3965. elif dim == 'geometry_toolchangexy':
  3966. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3967. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3968. coords_xy[0] *= sfactor
  3969. coords_xy[1] *= sfactor
  3970. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3971. elif dim == 'geometry_cnctooldia':
  3972. tools_diameters = []
  3973. try:
  3974. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3975. tools_diameters = [eval(a) for a in tools_string if a != '']
  3976. except Exception as e:
  3977. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3978. self.defaults['geometry_cnctooldia'] = ''
  3979. for t in range(len(tools_diameters)):
  3980. tools_diameters[t] *= sfactor
  3981. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  3982. elif dim == 'tools_ncctools':
  3983. ncctools = []
  3984. try:
  3985. tools_string = self.defaults["tools_ncctools"].split(",")
  3986. ncctools = [eval(a) for a in tools_string if a != '']
  3987. except Exception as e:
  3988. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3989. self.defaults['tools_ncctools'] = ''
  3990. for t in range(len(ncctools)):
  3991. ncctools[t] *= sfactor
  3992. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  3993. elif dim == 'tools_solderpaste_tools':
  3994. sptools = []
  3995. try:
  3996. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3997. sptools = [eval(a) for a in tools_string if a != '']
  3998. except Exception as e:
  3999. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4000. self.defaults['tools_solderpaste_tools'] = ""
  4001. for t in range(len(sptools)):
  4002. sptools[t] *= sfactor
  4003. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4004. elif dim == 'tools_solderpaste_xy_toolchange':
  4005. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4006. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4007. sp_coords[0] *= sfactor
  4008. sp_coords[1] *= sfactor
  4009. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4010. elif dim == 'global_gridx' or dim == 'global_gridy':
  4011. if new_units == 'IN':
  4012. val = 0.1
  4013. try:
  4014. val = float(self.defaults[dim]) * sfactor
  4015. except Exception as e:
  4016. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4017. self.defaults[dim] = float('%.6f' % val)
  4018. else:
  4019. val = 0.1
  4020. try:
  4021. val = float(self.defaults[dim]) * sfactor
  4022. except Exception as e:
  4023. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4024. self.defaults[dim] = float('%.4f' % val)
  4025. else:
  4026. val = 0.1
  4027. try:
  4028. val = float(self.defaults[dim]) * sfactor
  4029. except Exception as e:
  4030. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4031. self.defaults[dim] = val
  4032. # The scaling factor depending on choice of units.
  4033. factor = 1/25.4
  4034. if new_units == 'MM':
  4035. factor = 25.4
  4036. # Changing project units. Warn user.
  4037. msgbox = QtWidgets.QMessageBox()
  4038. msgbox.setWindowTitle(_("Toggle Units"))
  4039. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4040. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4041. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4042. "properties of all objects to be scaled accordingly.\nContinue?"))
  4043. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4044. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4045. msgbox.setDefaultButton(bt_ok)
  4046. msgbox.exec_()
  4047. response = msgbox.clickedButton()
  4048. if response == bt_ok:
  4049. if no_pref is False:
  4050. self.options_read_form()
  4051. scale_options(factor)
  4052. self.options_write_form()
  4053. self.defaults_read_form()
  4054. scale_defaults(factor)
  4055. self.defaults_write_form(fl_units=new_units)
  4056. # save the defaults to file, some may assume that the conversion is enough and it's not
  4057. self.on_save_button()
  4058. self.should_we_save = True
  4059. # change this only if the workspace is active
  4060. if self.defaults['global_workspace'] is True:
  4061. self.plotcanvas.draw_workspace()
  4062. # adjust the grid values on the main toolbar
  4063. dec = 6 if new_units == 'IN'else 4
  4064. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4065. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4066. if not self.ui.grid_gap_link_cb.isChecked():
  4067. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4068. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4069. for obj in self.collection.get_list():
  4070. obj.convert_units(new_units)
  4071. # make that the properties stored in the object are also updated
  4072. self.object_changed.emit(obj)
  4073. obj.build_ui()
  4074. current = self.collection.get_active()
  4075. if current is not None:
  4076. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4077. if not isinstance(current, FlatCAMGeometry):
  4078. current.to_form()
  4079. self.plot_all()
  4080. self.inform.emit('[success] %s: %s' %
  4081. (_("Converted units to %s"), new_units))
  4082. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4083. self.set_screen_units(new_units)
  4084. else:
  4085. # Undo toggling
  4086. self.toggle_units_ignore = True
  4087. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4088. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4089. else:
  4090. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4091. self.toggle_units_ignore = False
  4092. self.inform.emit('[WARNING_NOTCL]%s' %
  4093. _(" Units conversion cancelled."))
  4094. self.options_read_form()
  4095. self.defaults_read_form()
  4096. def on_toggle_units_click(self):
  4097. try:
  4098. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4099. except (TypeError, AttributeError):
  4100. pass
  4101. if self.defaults["units"] == 'MM':
  4102. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4103. else:
  4104. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4105. self.on_toggle_units(no_pref=True)
  4106. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4107. lambda: self.on_toggle_units(no_pref=False))
  4108. def on_fullscreen(self):
  4109. self.report_usage("on_fullscreen()")
  4110. if self.toggle_fscreen is False:
  4111. if sys.platform == 'win32':
  4112. self.ui.showFullScreen()
  4113. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4114. tb.setVisible(False)
  4115. self.ui.splitter_left.setVisible(False)
  4116. self.toggle_fscreen = True
  4117. else:
  4118. if sys.platform == 'win32':
  4119. self.ui.showNormal()
  4120. self.restore_toolbar_view()
  4121. self.ui.splitter_left.setVisible(True)
  4122. self.toggle_fscreen = False
  4123. def on_toggle_plotarea(self):
  4124. self.report_usage("on_toggle_plotarea()")
  4125. try:
  4126. name = self.ui.plot_tab_area.widget(0).objectName()
  4127. except AttributeError:
  4128. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4129. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4130. self.ui.plot_tab_area.protectTab(0)
  4131. return
  4132. if name != 'plotarea':
  4133. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4134. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4135. self.ui.plot_tab_area.protectTab(0)
  4136. else:
  4137. self.ui.plot_tab_area.closeTab(0)
  4138. def on_toggle_notebook(self):
  4139. if self.ui.splitter.sizes()[0] == 0:
  4140. self.ui.splitter.setSizes([1, 1])
  4141. else:
  4142. self.ui.splitter.setSizes([0, 1])
  4143. def on_toggle_axis(self):
  4144. self.report_usage("on_toggle_axis()")
  4145. if self.toggle_axis is False:
  4146. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4147. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4148. self.plotcanvas.redraw()
  4149. self.toggle_axis = True
  4150. else:
  4151. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4152. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4153. self.plotcanvas.redraw()
  4154. self.toggle_axis = False
  4155. def on_toggle_grid(self):
  4156. self.report_usage("on_toggle_grid()")
  4157. self.ui.grid_snap_btn.trigger()
  4158. def on_options_combo_change(self, sel):
  4159. """
  4160. Called when the combo box to choose between application defaults and
  4161. project option changes value. The corresponding variables are
  4162. copied to the UI.
  4163. :param sel: The option index that was chosen.
  4164. :return: None
  4165. """
  4166. # combo_sel = self.ui.notebook.combo_options.get_active()
  4167. App.log.debug("Options --> %s" % sel)
  4168. # form = [self.defaults_form, self.options_form][sel]
  4169. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4170. if sel == 0:
  4171. self.gen_form = self.ui.general_defaults_form
  4172. self.ger_form = self.ui.gerber_defaults_form
  4173. self.exc_form = self.ui.excellon_defaults_form
  4174. self.geo_form = self.ui.geometry_defaults_form
  4175. self.cnc_form = self.ui.cncjob_defaults_form
  4176. self.tools_form = self.ui.tools_defaults_form
  4177. self.fa_form = self.ui.fa_defaults_form
  4178. elif sel == 1:
  4179. self.gen_form = self.ui.general_options_form
  4180. self.ger_form = self.ui.gerber_options_form
  4181. self.exc_form = self.ui.excellon_options_form
  4182. self.geo_form = self.ui.geometry_options_form
  4183. self.cnc_form = self.ui.cncjob_options_form
  4184. self.tools_form = self.ui.tools_options_form
  4185. self.fa_form = self.ui.fa_options_form
  4186. else:
  4187. return
  4188. try:
  4189. self.ui.general_scroll_area.takeWidget()
  4190. except:
  4191. self.log.debug("Nothing to remove")
  4192. self.ui.general_scroll_area.setWidget(self.gen_form)
  4193. self.gen_form.show()
  4194. try:
  4195. self.ui.gerber_scroll_area.takeWidget()
  4196. except:
  4197. self.log.debug("Nothing to remove")
  4198. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4199. self.ger_form.show()
  4200. try:
  4201. self.ui.excellon_scroll_area.takeWidget()
  4202. except:
  4203. self.log.debug("Nothing to remove")
  4204. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4205. self.exc_form.show()
  4206. try:
  4207. self.ui.geometry_scroll_area.takeWidget()
  4208. except:
  4209. self.log.debug("Nothing to remove")
  4210. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4211. self.geo_form.show()
  4212. try:
  4213. self.ui.cncjob_scroll_area.takeWidget()
  4214. except:
  4215. self.log.debug("Nothing to remove")
  4216. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4217. self.cnc_form.show()
  4218. try:
  4219. self.ui.tools_scroll_area.takeWidget()
  4220. except:
  4221. self.log.debug("Nothing to remove")
  4222. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4223. self.tools_form.show()
  4224. try:
  4225. self.ui.fa_scroll_area.takeWidget()
  4226. except:
  4227. self.log.debug("Nothing to remove")
  4228. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4229. self.fa_form.show()
  4230. self.log.debug("Finished GUI form initialization.")
  4231. # self.options2form()
  4232. def on_excellon_defaults_button(self):
  4233. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4234. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4235. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4236. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4237. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4238. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4239. log.debug("Excellon app defaults loaded ...")
  4240. def on_excellon_options_button(self):
  4241. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4242. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4243. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4244. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4245. self.options_form_fields["excellon_zeros"].set_value('L')
  4246. self.options_form_fields["excellon_units"].set_value('INCH')
  4247. log.debug("Excellon options defaults loaded ...")
  4248. # Setting plot colors handlers
  4249. def on_pf_color_entry(self):
  4250. self.defaults['global_plot_fill'] = \
  4251. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4252. self.defaults['global_plot_fill'][7:9]
  4253. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4254. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4255. def on_pf_color_button(self):
  4256. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4257. c_dialog = QtWidgets.QColorDialog()
  4258. plot_fill_color = c_dialog.getColor(initial=current_color)
  4259. if plot_fill_color.isValid() is False:
  4260. return
  4261. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4262. "background-color:%s" % str(plot_fill_color.name()))
  4263. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4264. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4265. self.defaults['global_plot_fill'] = new_val
  4266. def on_pf_color_spinner(self):
  4267. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4268. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4269. self.defaults['global_plot_fill'] = \
  4270. self.defaults['global_plot_fill'][:7] + \
  4271. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4272. self.defaults['global_plot_line'] = \
  4273. self.defaults['global_plot_line'][:7] + \
  4274. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4275. def on_pf_color_slider(self):
  4276. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4277. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4278. def on_pl_color_entry(self):
  4279. self.defaults['global_plot_line'] = \
  4280. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4281. self.defaults['global_plot_line'][7:9]
  4282. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4283. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4284. def on_pl_color_button(self):
  4285. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4286. # print(current_color)
  4287. c_dialog = QtWidgets.QColorDialog()
  4288. plot_line_color = c_dialog.getColor(initial=current_color)
  4289. if plot_line_color.isValid() is False:
  4290. return
  4291. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4292. "background-color:%s" % str(plot_line_color.name()))
  4293. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4294. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4295. self.defaults['global_plot_line'] = new_val_line
  4296. # Setting selection colors (left - right) handlers
  4297. def on_sf_color_entry(self):
  4298. self.defaults['global_sel_fill'] = \
  4299. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4300. self.defaults['global_sel_fill'][7:9]
  4301. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4302. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4303. def on_sf_color_button(self):
  4304. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4305. c_dialog = QtWidgets.QColorDialog()
  4306. plot_fill_color = c_dialog.getColor(initial=current_color)
  4307. if plot_fill_color.isValid() is False:
  4308. return
  4309. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4310. "background-color:%s" % str(plot_fill_color.name()))
  4311. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4312. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4313. self.defaults['global_sel_fill'] = new_val
  4314. def on_sf_color_spinner(self):
  4315. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4316. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4317. self.defaults['global_sel_fill'] = \
  4318. self.defaults['global_sel_fill'][:7] + \
  4319. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4320. self.defaults['global_sel_line'] = \
  4321. self.defaults['global_sel_line'][:7] + \
  4322. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4323. def on_sf_color_slider(self):
  4324. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4325. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4326. def on_sl_color_entry(self):
  4327. self.defaults['global_sel_line'] = \
  4328. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4329. self.defaults['global_sel_line'][7:9]
  4330. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4331. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4332. def on_sl_color_button(self):
  4333. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4334. c_dialog = QtWidgets.QColorDialog()
  4335. plot_line_color = c_dialog.getColor(initial=current_color)
  4336. if plot_line_color.isValid() is False:
  4337. return
  4338. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4339. "background-color:%s" % str(plot_line_color.name()))
  4340. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4341. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4342. self.defaults['global_sel_line'] = new_val_line
  4343. # Setting selection colors (right - left) handlers
  4344. def on_alt_sf_color_entry(self):
  4345. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4346. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4347. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4348. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4349. def on_alt_sf_color_button(self):
  4350. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4351. c_dialog = QtWidgets.QColorDialog()
  4352. plot_fill_color = c_dialog.getColor(initial=current_color)
  4353. if plot_fill_color.isValid() is False:
  4354. return
  4355. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4356. "background-color:%s" % str(plot_fill_color.name()))
  4357. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4358. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4359. self.defaults['global_alt_sel_fill'] = new_val
  4360. def on_alt_sf_color_spinner(self):
  4361. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4362. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4363. self.defaults['global_alt_sel_fill'] = \
  4364. self.defaults['global_alt_sel_fill'][:7] + \
  4365. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4366. self.defaults['global_alt_sel_line'] = \
  4367. self.defaults['global_alt_sel_line'][:7] + \
  4368. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4369. def on_alt_sf_color_slider(self):
  4370. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4371. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4372. def on_alt_sl_color_entry(self):
  4373. self.defaults['global_alt_sel_line'] = \
  4374. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4375. self.defaults['global_alt_sel_line'][7:9]
  4376. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4377. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4378. def on_alt_sl_color_button(self):
  4379. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4380. c_dialog = QtWidgets.QColorDialog()
  4381. plot_line_color = c_dialog.getColor(initial=current_color)
  4382. if plot_line_color.isValid() is False:
  4383. return
  4384. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4385. "background-color:%s" % str(plot_line_color.name()))
  4386. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4387. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4388. self.defaults['global_alt_sel_line'] = new_val_line
  4389. # Setting Editor colors
  4390. def on_draw_color_entry(self):
  4391. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4392. .draw_color_entry.get_value()
  4393. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4394. "background-color:%s" % str(self.defaults['global_draw_color']))
  4395. def on_draw_color_button(self):
  4396. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4397. c_dialog = QtWidgets.QColorDialog()
  4398. draw_color = c_dialog.getColor(initial=current_color)
  4399. if draw_color.isValid() is False:
  4400. return
  4401. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4402. "background-color:%s" % str(draw_color.name()))
  4403. new_val = str(draw_color.name())
  4404. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4405. self.defaults['global_draw_color'] = new_val
  4406. def on_sel_draw_color_entry(self):
  4407. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4408. .sel_draw_color_entry.get_value()
  4409. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4410. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4411. def on_sel_draw_color_button(self):
  4412. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4413. c_dialog = QtWidgets.QColorDialog()
  4414. sel_draw_color = c_dialog.getColor(initial=current_color)
  4415. if sel_draw_color.isValid() is False:
  4416. return
  4417. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4418. "background-color:%s" % str(sel_draw_color.name()))
  4419. new_val_sel = str(sel_draw_color.name())
  4420. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4421. self.defaults['global_sel_draw_color'] = new_val_sel
  4422. def on_proj_color_entry(self):
  4423. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4424. .proj_color_entry.get_value()
  4425. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4426. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4427. def on_proj_color_button(self):
  4428. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4429. c_dialog = QtWidgets.QColorDialog()
  4430. proj_color = c_dialog.getColor(initial=current_color)
  4431. if proj_color.isValid() is False:
  4432. return
  4433. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4434. "background-color:%s" % str(proj_color.name()))
  4435. new_val_sel = str(proj_color.name())
  4436. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4437. self.defaults['global_proj_item_color'] = new_val_sel
  4438. def on_proj_color_dis_entry(self):
  4439. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4440. .proj_color_dis_entry.get_value()
  4441. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4442. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4443. def on_proj_color_dis_button(self):
  4444. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  4445. c_dialog = QtWidgets.QColorDialog()
  4446. proj_color = c_dialog.getColor(initial=current_color)
  4447. if proj_color.isValid() is False:
  4448. return
  4449. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4450. "background-color:%s" % str(proj_color.name()))
  4451. new_val_sel = str(proj_color.name())
  4452. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  4453. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4454. def on_annotation_fontcolor_entry(self):
  4455. self.defaults['cncjob_annotation_fontcolor'] = \
  4456. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  4457. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4458. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  4459. def on_annotation_fontcolor_button(self):
  4460. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  4461. c_dialog = QtWidgets.QColorDialog()
  4462. annotation_color = c_dialog.getColor(initial=current_color)
  4463. if annotation_color.isValid() is False:
  4464. return
  4465. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4466. "background-color:%s" % str(annotation_color.name()))
  4467. new_val_sel = str(annotation_color.name())
  4468. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  4469. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4470. def on_notebook_tab_rmb_click(self, checked):
  4471. self.ui.notebook.set_detachable(val=checked)
  4472. self.defaults["global_tabs_detachable"] = checked
  4473. self.ui.plot_tab_area.set_detachable(val=checked)
  4474. self.defaults["global_tabs_detachable"] = checked
  4475. def on_deselect_all(self):
  4476. self.collection.set_all_inactive()
  4477. self.delete_selection_shape()
  4478. def on_workspace_modified(self):
  4479. self.save_defaults(silent=True)
  4480. self.plotcanvas.draw_workspace()
  4481. def on_workspace(self):
  4482. self.report_usage("on_workspace()")
  4483. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4484. self.plotcanvas.restore_workspace()
  4485. else:
  4486. self.plotcanvas.delete_workspace()
  4487. self.save_defaults(silent=True)
  4488. def on_workspace_menu(self):
  4489. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4490. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  4491. else:
  4492. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  4493. self.on_workspace()
  4494. def on_layout(self, index=None, lay=None):
  4495. self.report_usage("on_layout()")
  4496. if lay:
  4497. current_layout = lay
  4498. else:
  4499. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  4500. settings = QSettings("Open Source", "FlatCAM")
  4501. settings.setValue('layout', current_layout)
  4502. # This will write the setting to the platform specific storage.
  4503. del settings
  4504. # first remove the toolbars:
  4505. try:
  4506. self.ui.removeToolBar(self.ui.toolbarfile)
  4507. self.ui.removeToolBar(self.ui.toolbargeo)
  4508. self.ui.removeToolBar(self.ui.toolbarview)
  4509. self.ui.removeToolBar(self.ui.toolbarshell)
  4510. self.ui.removeToolBar(self.ui.toolbartools)
  4511. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  4512. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  4513. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  4514. self.ui.removeToolBar(self.ui.snap_toolbar)
  4515. self.ui.removeToolBar(self.ui.toolbarshell)
  4516. except Exception as e:
  4517. pass
  4518. if current_layout == 'standard':
  4519. # ## TOOLBAR INSTALLATION # ##
  4520. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4521. self.ui.toolbarfile.setObjectName('File_TB')
  4522. self.ui.addToolBar(self.ui.toolbarfile)
  4523. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4524. self.ui.toolbargeo.setObjectName('Edit_TB')
  4525. self.ui.addToolBar(self.ui.toolbargeo)
  4526. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4527. self.ui.toolbarview.setObjectName('View_TB')
  4528. self.ui.addToolBar(self.ui.toolbarview)
  4529. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4530. self.ui.toolbarshell.setObjectName('Shell_TB')
  4531. self.ui.addToolBar(self.ui.toolbarshell)
  4532. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4533. self.ui.toolbartools.setObjectName('Tools_TB')
  4534. self.ui.addToolBar(self.ui.toolbartools)
  4535. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4536. self.ui.exc_edit_toolbar.setVisible(False)
  4537. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4538. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  4539. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4540. self.ui.geo_edit_toolbar.setVisible(False)
  4541. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4542. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  4543. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4544. self.ui.grb_edit_toolbar.setVisible(False)
  4545. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4546. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  4547. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4548. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4549. # self.ui.snap_toolbar.setMaximumHeight(30)
  4550. self.ui.addToolBar(self.ui.snap_toolbar)
  4551. self.ui.corner_snap_btn.setVisible(False)
  4552. self.ui.snap_magnet.setVisible(False)
  4553. elif current_layout == 'compact':
  4554. # ## TOOLBAR INSTALLATION # ##
  4555. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4556. self.ui.toolbarfile.setObjectName('File_TB')
  4557. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4558. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4559. self.ui.toolbargeo.setObjectName('Edit_TB')
  4560. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4561. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4562. self.ui.toolbarview.setObjectName('View_TB')
  4563. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  4564. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4565. self.ui.toolbarshell.setObjectName('Shell_TB')
  4566. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4567. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4568. self.ui.toolbartools.setObjectName('Tools_TB')
  4569. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4570. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4571. # self.ui.geo_edit_toolbar.setVisible(False)
  4572. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4573. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4574. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4575. # self.ui.grb_edit_toolbar.setVisible(False)
  4576. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4577. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4578. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4579. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4580. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4581. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4582. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4583. self.ui.snap_toolbar.setMaximumHeight(30)
  4584. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4585. self.ui.corner_snap_btn.setVisible(True)
  4586. self.ui.snap_magnet.setVisible(True)
  4587. # add all the actions to the toolbars
  4588. self.ui.populate_toolbars()
  4589. # reconnect all the signals to the toolbar actions
  4590. self.connect_toolbar_signals()
  4591. self.ui.grid_snap_btn.setChecked(True)
  4592. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4593. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4594. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4595. self.ui.grid_gap_link_cb.setChecked(True)
  4596. def on_cnc_custom_parameters(self, signal_text):
  4597. if signal_text == 'Parameters':
  4598. return
  4599. else:
  4600. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4601. def on_save_button(self):
  4602. log.debug("App.on_save_button() --> Saving preferences to file.")
  4603. self.preferences_changed_flag = False
  4604. self.save_defaults(silent=False)
  4605. # load the defaults so they are updated into the app
  4606. self.load_defaults(filename='current_defaults')
  4607. # Re-fresh project options
  4608. self.on_options_app2project()
  4609. # save the notebook font size
  4610. settings = QSettings("Open Source", "FlatCAM")
  4611. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4612. settings.setValue('notebook_font_size', fsize)
  4613. # save the axis font size
  4614. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4615. settings.setValue('axis_font_size', g_fsize)
  4616. # This will write the setting to the platform specific storage.
  4617. del settings
  4618. def handlePrint(self):
  4619. self.report_usage("handlePrint()")
  4620. dialog = QtPrintSupport.QPrintDialog()
  4621. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4622. self.ui.code_editor.document().print_(dialog.printer())
  4623. def handlePreview(self):
  4624. self.report_usage("handlePreview()")
  4625. dialog = QtPrintSupport.QPrintPreviewDialog()
  4626. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4627. dialog.exec_()
  4628. def handleTextChanged(self):
  4629. # enable = not self.ui.code_editor.document().isEmpty()
  4630. # self.ui.buttonPrint.setEnabled(enable)
  4631. # self.ui.buttonPreview.setEnabled(enable)
  4632. pass
  4633. def handleOpen(self, filt=None):
  4634. self.report_usage("handleOpen()")
  4635. if filt:
  4636. _filter_ = filt
  4637. else:
  4638. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4639. "All Files (*.*)"
  4640. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4641. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4642. if path:
  4643. file = QtCore.QFile(path)
  4644. if file.open(QtCore.QIODevice.ReadOnly):
  4645. stream = QtCore.QTextStream(file)
  4646. self.gcode_edited = stream.readAll()
  4647. self.ui.code_editor.setPlainText(self.gcode_edited)
  4648. file.close()
  4649. def handleSaveGCode(self, name=None, filt=None):
  4650. self.report_usage("handleSaveGCode()")
  4651. if filt:
  4652. _filter_ = filt
  4653. else:
  4654. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4655. "All Files (*.*)"
  4656. if name:
  4657. obj_name = name
  4658. else:
  4659. try:
  4660. obj_name = self.collection.get_active().options['name']
  4661. except AttributeError:
  4662. obj_name = 'file'
  4663. if filt is None:
  4664. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4665. try:
  4666. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4667. caption=_("Export G-Code ..."),
  4668. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4669. filter=_filter_
  4670. )[0])
  4671. except TypeError:
  4672. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4673. if filename == "":
  4674. self.inform.emit('[WARNING_NOTCL] %s' %
  4675. _("Export Code cancelled."))
  4676. return
  4677. else:
  4678. try:
  4679. my_gcode = self.ui.code_editor.toPlainText()
  4680. with open(filename, 'w') as f:
  4681. for line in my_gcode:
  4682. f.write(line)
  4683. except FileNotFoundError:
  4684. self.inform.emit('[WARNING] %s' %
  4685. _("No such file or directory"))
  4686. return
  4687. except PermissionError:
  4688. self.inform.emit('[WARNING] %s' %
  4689. _("Permission denied, saving not possible.\n"
  4690. "Most likely another app is holding the file open and not accessible."))
  4691. return
  4692. # Just for adding it to the recent files list.
  4693. if self.defaults["global_open_style"] is False:
  4694. self.file_opened.emit("cncjob", filename)
  4695. self.file_saved.emit("cncjob", filename)
  4696. self.inform.emit(_("Saved to: %s") % filename)
  4697. def handleFindGCode(self):
  4698. self.report_usage("handleFindGCode()")
  4699. flags = QtGui.QTextDocument.FindCaseSensitively
  4700. text_to_be_found = self.ui.entryFind.get_value()
  4701. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4702. if r is False:
  4703. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4704. def handleReplaceGCode(self):
  4705. self.report_usage("handleReplaceGCode()")
  4706. old = self.ui.entryFind.get_value()
  4707. new = self.ui.entryReplace.get_value()
  4708. if self.ui.sel_all_cb.isChecked():
  4709. while True:
  4710. cursor = self.ui.code_editor.textCursor()
  4711. cursor.beginEditBlock()
  4712. flags = QtGui.QTextDocument.FindCaseSensitively
  4713. # self.ui.editor is the QPlainTextEdit
  4714. r = self.ui.code_editor.find(str(old), flags)
  4715. if r:
  4716. qc = self.ui.code_editor.textCursor()
  4717. if qc.hasSelection():
  4718. qc.insertText(new)
  4719. else:
  4720. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4721. break
  4722. # Mark end of undo block
  4723. cursor.endEditBlock()
  4724. else:
  4725. cursor = self.ui.code_editor.textCursor()
  4726. cursor.beginEditBlock()
  4727. qc = self.ui.code_editor.textCursor()
  4728. if qc.hasSelection():
  4729. qc.insertText(new)
  4730. # Mark end of undo block
  4731. cursor.endEditBlock()
  4732. def on_tool_add_keypress(self):
  4733. # ## Current application units in Upper Case
  4734. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4735. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4736. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4737. if notebook_widget_name == 'selected_tab':
  4738. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4739. # Tool add works for Geometry only if Advanced is True in Preferences
  4740. if self.defaults["global_app_level"] == 'a':
  4741. tool_add_popup = FCInputDialog(title="New Tool ...",
  4742. text='Enter a Tool Diameter:',
  4743. min=0.0000, max=99.9999, decimals=4)
  4744. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4745. val, ok = tool_add_popup.get_value()
  4746. if ok:
  4747. if float(val) == 0:
  4748. self.inform.emit('[WARNING_NOTCL] %s' %
  4749. _("Please enter a tool diameter with non-zero value, in Float format."))
  4750. return
  4751. self.collection.get_active().on_tool_add(dia=float(val))
  4752. else:
  4753. self.inform.emit('[WARNING_NOTCL] %s...' %
  4754. _("Adding Tool cancelled"))
  4755. else:
  4756. msgbox = QtWidgets.QMessageBox()
  4757. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4758. "Go to Preferences -> General - Show Advanced Options."))
  4759. msgbox.setWindowTitle("Tool adding ...")
  4760. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  4761. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4762. msgbox.setDefaultButton(bt_ok)
  4763. msgbox.exec_()
  4764. # work only if the notebook tab on focus is the Tools_Tab
  4765. if notebook_widget_name == 'tool_tab':
  4766. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4767. tool_add_popup = FCInputDialog(title="New Tool ...",
  4768. text='Enter a Tool Diameter:',
  4769. min=0.0000, max=99.9999, decimals=4)
  4770. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4771. val, ok = tool_add_popup.get_value()
  4772. # and only if the tool is NCC Tool
  4773. if tool_widget == self.ncclear_tool.toolName:
  4774. if ok:
  4775. if float(val) == 0:
  4776. self.inform.emit('[WARNING_NOTCL] %s' %
  4777. _("Please enter a tool diameter with non-zero value, in Float format."))
  4778. return
  4779. self.ncclear_tool.on_tool_add(dia=float(val))
  4780. else:
  4781. self.inform.emit('[WARNING_NOTCL] %s...' %
  4782. _("Adding Tool cancelled"))
  4783. # and only if the tool is Paint Area Tool
  4784. elif tool_widget == self.paint_tool.toolName:
  4785. if ok:
  4786. if float(val) == 0:
  4787. self.inform.emit('[WARNING_NOTCL] %s' %
  4788. _("Please enter a tool diameter with non-zero value, in Float format."))
  4789. return
  4790. self.paint_tool.on_tool_add(dia=float(val))
  4791. else:
  4792. self.inform.emit(
  4793. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4794. # and only if the tool is Solder Paste Dispensing Tool
  4795. elif tool_widget == self.paste_tool.toolName:
  4796. if ok:
  4797. if float(val) == 0:
  4798. self.inform.emit('[WARNING_NOTCL] %s' %
  4799. _("Please enter a tool diameter with non-zero value, in Float format."))
  4800. return
  4801. self.paste_tool.on_tool_add(dia=float(val))
  4802. else:
  4803. self.inform.emit('[WARNING_NOTCL] %s...' %
  4804. _("Adding Tool cancelled"))
  4805. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4806. # See description bellow.
  4807. def on_delete_keypress(self):
  4808. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4809. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4810. if notebook_widget_name == 'selected_tab':
  4811. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4812. self.collection.get_active().on_tool_delete()
  4813. # work only if the notebook tab on focus is the Tools_Tab
  4814. elif notebook_widget_name == 'tool_tab':
  4815. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4816. # and only if the tool is NCC Tool
  4817. if tool_widget == self.ncclear_tool.toolName:
  4818. self.ncclear_tool.on_tool_delete()
  4819. # and only if the tool is Paint Tool
  4820. elif tool_widget == self.paint_tool.toolName:
  4821. self.paint_tool.on_tool_delete()
  4822. # and only if the tool is Solder Paste Dispensing Tool
  4823. elif tool_widget == self.paste_tool.toolName:
  4824. self.paste_tool.on_tool_delete()
  4825. else:
  4826. self.on_delete()
  4827. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4828. # some screens you have to be careful where you hover with your mouse.
  4829. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4830. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4831. # Complicated, I know :)
  4832. def on_delete(self):
  4833. """
  4834. Delete the currently selected FlatCAMObjs.
  4835. :return: None
  4836. """
  4837. self.report_usage("on_delete()")
  4838. response = None
  4839. bt_ok = None
  4840. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4841. # a geometry object before we update it.
  4842. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4843. and self.grb_editor.editor_active is False:
  4844. if self.defaults["global_delete_confirmation"] is True:
  4845. msgbox = QtWidgets.QMessageBox()
  4846. msgbox.setWindowTitle(_("Delete objects"))
  4847. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  4848. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4849. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4850. "the selected objects?"))
  4851. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4852. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4853. msgbox.setDefaultButton(bt_ok)
  4854. msgbox.exec_()
  4855. response = msgbox.clickedButton()
  4856. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  4857. if self.collection.get_active():
  4858. self.log.debug("App.on_delete()")
  4859. while self.collection.get_active():
  4860. obj_active = self.collection.get_active()
  4861. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  4862. if isinstance(obj_active, FlatCAMGerber):
  4863. for el in obj_active.mark_shapes:
  4864. obj_active.mark_shapes[el].clear(update=True)
  4865. obj_active.mark_shapes[el].enabled = False
  4866. # obj_active.mark_shapes[el] = None
  4867. del el
  4868. elif isinstance(obj_active, FlatCAMCNCjob):
  4869. try:
  4870. obj_active.annotation.clear(update=True)
  4871. obj_active.annotation.enabled = False
  4872. except AttributeError:
  4873. pass
  4874. self.delete_first_selected()
  4875. self.inform.emit('%s...' %
  4876. _("Object(s) deleted"))
  4877. # make sure that the selection shape is deleted, too
  4878. self.delete_selection_shape()
  4879. else:
  4880. self.inform.emit(_("Failed. No object(s) selected..."))
  4881. else:
  4882. self.inform.emit(_("Save the work in Editor and try again ..."))
  4883. def delete_first_selected(self):
  4884. # Keep this for later
  4885. try:
  4886. sel_obj = self.collection.get_active()
  4887. name = sel_obj.options["name"]
  4888. except AttributeError:
  4889. self.log.debug("Nothing selected for deletion")
  4890. return
  4891. # Remove from dictionary
  4892. self.collection.delete_active()
  4893. # Clear form
  4894. self.setup_component_editor()
  4895. self.inform.emit('%s: %s' %
  4896. (_("Object deleted"), name))
  4897. def on_set_origin(self):
  4898. """
  4899. Set the origin to the left mouse click position
  4900. :return: None
  4901. """
  4902. # display the message for the user
  4903. # and ask him to click on the desired position
  4904. self.report_usage("on_set_origin()")
  4905. def origin_replot():
  4906. def worker_task():
  4907. with self.proc_container.new('%s...' % _("Plotting")):
  4908. for obj in self.collection.get_list():
  4909. obj.plot()
  4910. self.plotcanvas.fit_view()
  4911. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4912. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4913. self.inform.emit(_('Click to set the origin ...'))
  4914. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  4915. # first disconnect it as it may have been used by something else
  4916. try:
  4917. self.replot_signal.disconnect()
  4918. except TypeError:
  4919. pass
  4920. self.replot_signal[list].connect(origin_replot)
  4921. def on_set_zero_click(self, event):
  4922. # this function will be available only for mouse left click
  4923. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  4924. if event.button == 1:
  4925. if self.grid_status() == True:
  4926. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4927. else:
  4928. pos = pos_canvas
  4929. x = 0 - pos[0]
  4930. y = 0 - pos[1]
  4931. def worker_task():
  4932. with self.proc_container.new(_("Setting Origin...")):
  4933. for obj in self.collection.get_list():
  4934. obj.offset((x, y))
  4935. self.object_changed.emit(obj)
  4936. # Update the object bounding box options
  4937. a, b, c, d = obj.bounds()
  4938. obj.options['xmin'] = a
  4939. obj.options['ymin'] = b
  4940. obj.options['xmax'] = c
  4941. obj.options['ymax'] = d
  4942. self.inform.emit('[success]%s...' %
  4943. _('Origin set'))
  4944. self.replot_signal.emit([])
  4945. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4946. self.should_we_save = True
  4947. def on_jump_to(self, custom_location=None, fit_center=True):
  4948. """
  4949. Jump to a location by setting the mouse cursor location
  4950. :return:
  4951. """
  4952. self.report_usage("on_jump_to()")
  4953. if not custom_location:
  4954. dia_box = Dialog_box(title=_("Jump to ..."),
  4955. label=_("Enter the coordinates in format X,Y:"),
  4956. icon=QtGui.QIcon('share/jump_to16.png'))
  4957. if dia_box.ok is True:
  4958. try:
  4959. location = eval(dia_box.location)
  4960. if not isinstance(location, tuple):
  4961. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4962. return
  4963. except:
  4964. return
  4965. else:
  4966. return
  4967. else:
  4968. location = custom_location
  4969. if fit_center:
  4970. self.plotcanvas.fit_center(loc=location)
  4971. cursor = QtGui.QCursor()
  4972. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4973. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  4974. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  4975. self.inform.emit('[success] %s' %
  4976. _("Done."))
  4977. return location
  4978. def on_copy_object(self):
  4979. self.report_usage("on_copy_object()")
  4980. def initialize(obj_init, app):
  4981. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4982. try:
  4983. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4984. except AttributeError:
  4985. pass
  4986. try:
  4987. obj_init.apertures = deepcopy(obj.apertures)
  4988. except AttributeError:
  4989. pass
  4990. try:
  4991. if obj.tools:
  4992. obj_init.tools = deepcopy(obj.tools)
  4993. except Exception as e:
  4994. log.debug("App.on_copy_object() --> %s" % str(e))
  4995. def initialize_excellon(obj_init, app):
  4996. obj_init.tools = deepcopy(obj.tools)
  4997. # drills are offset, so they need to be deep copied
  4998. obj_init.drills = deepcopy(obj.drills)
  4999. # slots are offset, so they need to be deep copied
  5000. obj_init.slots = deepcopy(obj.slots)
  5001. obj_init.create_geometry()
  5002. for obj in self.collection.get_selected():
  5003. obj_name = obj.options["name"]
  5004. try:
  5005. if isinstance(obj, FlatCAMExcellon):
  5006. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5007. elif isinstance(obj, FlatCAMGerber):
  5008. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5009. elif isinstance(obj, FlatCAMGeometry):
  5010. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5011. except Exception as e:
  5012. return "Operation failed: %s" % str(e)
  5013. def on_copy_object2(self, custom_name):
  5014. def initialize_geometry(obj_init, app):
  5015. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5016. try:
  5017. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5018. except AttributeError:
  5019. pass
  5020. try:
  5021. obj_init.apertures = deepcopy(obj.apertures)
  5022. except AttributeError:
  5023. pass
  5024. try:
  5025. if obj.tools:
  5026. obj_init.tools = deepcopy(obj.tools)
  5027. except Exception as e:
  5028. log.debug("on_copy_object2() --> %s" % str(e))
  5029. def initialize_gerber(obj_init, app):
  5030. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5031. obj_init.apertures = deepcopy(obj.apertures)
  5032. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5033. def initialize_excellon(obj_init, app):
  5034. obj_init.tools = deepcopy(obj.tools)
  5035. # drills are offset, so they need to be deep copied
  5036. obj_init.drills = deepcopy(obj.drills)
  5037. # slots are offset, so they need to be deep copied
  5038. obj_init.slots = deepcopy(obj.slots)
  5039. obj_init.create_geometry()
  5040. for obj in self.collection.get_selected():
  5041. obj_name = obj.options["name"]
  5042. try:
  5043. if isinstance(obj, FlatCAMExcellon):
  5044. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5045. elif isinstance(obj, FlatCAMGerber):
  5046. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5047. elif isinstance(obj, FlatCAMGeometry):
  5048. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5049. except Exception as e:
  5050. return "Operation failed: %s" % str(e)
  5051. def on_rename_object(self, text):
  5052. self.report_usage("on_rename_object()")
  5053. named_obj = self.collection.get_active()
  5054. for obj in named_obj:
  5055. if obj is list:
  5056. self.on_rename_object(text)
  5057. else:
  5058. try:
  5059. obj.options['name'] = text
  5060. except Exception as e:
  5061. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5062. def convert_any2geo(self):
  5063. self.report_usage("convert_any2geo()")
  5064. def initialize(obj_init, app):
  5065. obj_init.solid_geometry = obj.solid_geometry
  5066. try:
  5067. obj_init.follow_geometry = obj.follow_geometry
  5068. except AttributeError:
  5069. pass
  5070. try:
  5071. obj_init.apertures = obj.apertures
  5072. except AttributeError:
  5073. pass
  5074. try:
  5075. if obj.tools:
  5076. obj_init.tools = obj.tools
  5077. except AttributeError:
  5078. pass
  5079. def initialize_excellon(obj_init, app):
  5080. # objs = self.collection.get_selected()
  5081. # FlatCAMGeometry.merge(objs, obj)
  5082. solid_geo = []
  5083. for tool in obj.tools:
  5084. for geo in obj.tools[tool]['solid_geometry']:
  5085. solid_geo.append(geo)
  5086. obj_init.solid_geometry = deepcopy(solid_geo)
  5087. if not self.collection.get_selected():
  5088. log.warning("App.convert_any2geo --> No object selected")
  5089. self.inform.emit('[WARNING_NOTCL] %s' %
  5090. _("No object is selected. Select an object and try again."))
  5091. return
  5092. for obj in self.collection.get_selected():
  5093. obj_name = obj.options["name"]
  5094. try:
  5095. if isinstance(obj, FlatCAMExcellon):
  5096. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5097. else:
  5098. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5099. except Exception as e:
  5100. return "Operation failed: %s" % str(e)
  5101. def convert_any2gerber(self):
  5102. self.report_usage("convert_any2gerber()")
  5103. def initialize_geometry(obj_init, app):
  5104. apertures = {}
  5105. apid = 0
  5106. apertures[str(apid)] = {}
  5107. apertures[str(apid)]['geometry'] = []
  5108. for obj_orig in obj.solid_geometry:
  5109. new_elem = dict()
  5110. new_elem['solid'] = obj_orig
  5111. new_elem['follow'] = obj_orig.exterior
  5112. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5113. apertures[str(apid)]['size'] = 0.0
  5114. apertures[str(apid)]['type'] = 'C'
  5115. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5116. obj_init.apertures = deepcopy(apertures)
  5117. def initialize_excellon(obj_init, app):
  5118. apertures = {}
  5119. apid = 10
  5120. for tool in obj.tools:
  5121. apertures[str(apid)] = {}
  5122. apertures[str(apid)]['geometry'] = []
  5123. for geo in obj.tools[tool]['solid_geometry']:
  5124. new_el = dict()
  5125. new_el['solid'] = geo
  5126. new_el['follow'] = geo.exterior
  5127. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5128. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5129. apertures[str(apid)]['type'] = 'C'
  5130. apid += 1
  5131. # create solid_geometry
  5132. solid_geometry = []
  5133. for apid in apertures:
  5134. for geo_el in apertures[apid]['geometry']:
  5135. solid_geometry.append(geo_el['solid'])
  5136. solid_geometry = MultiPolygon(solid_geometry)
  5137. solid_geometry = solid_geometry.buffer(0.0000001)
  5138. obj_init.solid_geometry = deepcopy(solid_geometry)
  5139. obj_init.apertures = deepcopy(apertures)
  5140. # clear the working objects (perhaps not necessary due of Python GC)
  5141. apertures.clear()
  5142. if not self.collection.get_selected():
  5143. log.warning("App.convert_any2gerber --> No object selected")
  5144. self.inform.emit('[WARNING_NOTCL] %s' %
  5145. _("No object is selected. Select an object and try again."))
  5146. return
  5147. for obj in self.collection.get_selected():
  5148. obj_name = obj.options["name"]
  5149. try:
  5150. if isinstance(obj, FlatCAMExcellon):
  5151. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5152. elif isinstance(obj, FlatCAMGeometry):
  5153. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5154. else:
  5155. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5156. except Exception as e:
  5157. return "Operation failed: %s" % str(e)
  5158. def abort_all_tasks(self):
  5159. if self.abort_flag is False:
  5160. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5161. self.abort_flag = True
  5162. def app_is_idle(self):
  5163. if self.abort_flag:
  5164. self.inform.emit('[WARNING_NOTCL] %s' %
  5165. _("The current task was gracefully closed on user request..."))
  5166. self.abort_flag = False
  5167. def on_selectall(self):
  5168. self.report_usage("on_selectall()")
  5169. # delete the possible selection box around a possible selected object
  5170. self.delete_selection_shape()
  5171. for name in self.collection.get_names():
  5172. self.collection.set_active(name)
  5173. curr_sel_obj = self.collection.get_by_name(name)
  5174. # create the selection box around the selected object
  5175. if self.defaults['global_selection_shape'] is True:
  5176. self.draw_selection_shape(curr_sel_obj)
  5177. def on_preferences(self):
  5178. # add the tab if it was closed
  5179. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5180. # delete the absolute and relative position and messages in the infobar
  5181. self.ui.position_label.setText("")
  5182. self.ui.rel_position_label.setText("")
  5183. # Switch plot_area to preferences page
  5184. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5185. self.ui.show()
  5186. # this disconnect() is done so the slot will be connected only once
  5187. try:
  5188. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5189. except (TypeError, AttributeError):
  5190. pass
  5191. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5192. # detect changes in the preferences
  5193. for idx in range(self.ui.pref_tab_area.count()):
  5194. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5195. try:
  5196. try:
  5197. tb.textEdited.disconnect(self.on_preferences_edited)
  5198. except (TypeError, AttributeError):
  5199. pass
  5200. tb.textEdited.connect(self.on_preferences_edited)
  5201. except AttributeError:
  5202. pass
  5203. try:
  5204. try:
  5205. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5206. except (TypeError, AttributeError):
  5207. pass
  5208. tb.modificationChanged.connect(self.on_preferences_edited)
  5209. except AttributeError:
  5210. pass
  5211. try:
  5212. try:
  5213. tb.toggled.disconnect(self.on_preferences_edited)
  5214. except (TypeError, AttributeError):
  5215. pass
  5216. tb.toggled.connect(self.on_preferences_edited)
  5217. except AttributeError:
  5218. pass
  5219. try:
  5220. try:
  5221. tb.valueChanged.disconnect(self.on_preferences_edited)
  5222. except (TypeError, AttributeError):
  5223. pass
  5224. tb.valueChanged.connect(self.on_preferences_edited)
  5225. except AttributeError:
  5226. pass
  5227. try:
  5228. try:
  5229. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5230. except (TypeError, AttributeError):
  5231. pass
  5232. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5233. except AttributeError:
  5234. pass
  5235. def on_preferences_edited(self):
  5236. self.inform.emit('[WARNING_NOTCL] %s' %
  5237. _("Preferences edited but not saved."))
  5238. self.preferences_changed_flag = True
  5239. def on_preferences_closed(self):
  5240. # disconnect
  5241. for idx in range(self.ui.pref_tab_area.count()):
  5242. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5243. try:
  5244. tb.textEdited.disconnect(self.on_preferences_edited)
  5245. except (TypeError, AttributeError):
  5246. pass
  5247. try:
  5248. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5249. except (TypeError, AttributeError):
  5250. pass
  5251. try:
  5252. tb.toggled.disconnect(self.on_preferences_edited)
  5253. except (TypeError, AttributeError):
  5254. pass
  5255. try:
  5256. tb.valueChanged.disconnect(self.on_preferences_edited)
  5257. except (TypeError, AttributeError):
  5258. pass
  5259. try:
  5260. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5261. except (TypeError, AttributeError):
  5262. pass
  5263. if self.preferences_changed_flag is True:
  5264. msgbox = QtWidgets.QMessageBox()
  5265. msgbox.setText(_("One or more values are changed.\n"
  5266. "Do you want to save the Preferences?"))
  5267. msgbox.setWindowTitle(_("Save Preferences"))
  5268. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5269. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5270. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5271. msgbox.setDefaultButton(bt_yes)
  5272. msgbox.exec_()
  5273. response = msgbox.clickedButton()
  5274. if response == bt_yes:
  5275. self.on_save_button()
  5276. self.inform.emit('[success] %s' %
  5277. _("Preferences saved."))
  5278. else:
  5279. self.preferences_changed_flag = False
  5280. return
  5281. def on_flipy(self):
  5282. self.report_usage("on_flipy()")
  5283. obj_list = self.collection.get_selected()
  5284. xminlist = []
  5285. yminlist = []
  5286. xmaxlist = []
  5287. ymaxlist = []
  5288. if not obj_list:
  5289. self.inform.emit('[WARNING_NOTCL] %s' %
  5290. _("No object selected to Flip on Y axis."))
  5291. else:
  5292. try:
  5293. # first get a bounding box to fit all
  5294. for obj in obj_list:
  5295. xmin, ymin, xmax, ymax = obj.bounds()
  5296. xminlist.append(xmin)
  5297. yminlist.append(ymin)
  5298. xmaxlist.append(xmax)
  5299. ymaxlist.append(ymax)
  5300. # get the minimum x,y and maximum x,y for all objects selected
  5301. xminimal = min(xminlist)
  5302. yminimal = min(yminlist)
  5303. xmaximal = max(xmaxlist)
  5304. ymaximal = max(ymaxlist)
  5305. px = 0.5 * (xminimal + xmaximal)
  5306. py = 0.5 * (yminimal + ymaximal)
  5307. # execute mirroring
  5308. for obj in obj_list:
  5309. obj.mirror('X', [px, py])
  5310. obj.plot()
  5311. self.object_changed.emit(obj)
  5312. self.inform.emit('[success] %s' %
  5313. _("Flip on Y axis done."))
  5314. except Exception as e:
  5315. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5316. (_("Flip action was not executed."), str(e)))
  5317. return
  5318. def on_flipx(self):
  5319. self.report_usage("on_flipx()")
  5320. obj_list = self.collection.get_selected()
  5321. xminlist = []
  5322. yminlist = []
  5323. xmaxlist = []
  5324. ymaxlist = []
  5325. if not obj_list:
  5326. self.inform.emit('[WARNING_NOTCL] %s' %
  5327. _("No object selected to Flip on X axis."))
  5328. else:
  5329. try:
  5330. # first get a bounding box to fit all
  5331. for obj in obj_list:
  5332. xmin, ymin, xmax, ymax = obj.bounds()
  5333. xminlist.append(xmin)
  5334. yminlist.append(ymin)
  5335. xmaxlist.append(xmax)
  5336. ymaxlist.append(ymax)
  5337. # get the minimum x,y and maximum x,y for all objects selected
  5338. xminimal = min(xminlist)
  5339. yminimal = min(yminlist)
  5340. xmaximal = max(xmaxlist)
  5341. ymaximal = max(ymaxlist)
  5342. px = 0.5 * (xminimal + xmaximal)
  5343. py = 0.5 * (yminimal + ymaximal)
  5344. # execute mirroring
  5345. for obj in obj_list:
  5346. obj.mirror('Y', [px, py])
  5347. obj.plot()
  5348. self.object_changed.emit(obj)
  5349. self.inform.emit('[success] %s' %
  5350. _("Flip on X axis done."))
  5351. except Exception as e:
  5352. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5353. (_("Flip action was not executed."), str(e)))
  5354. return
  5355. def on_rotate(self, silent=False, preset=None):
  5356. self.report_usage("on_rotate()")
  5357. obj_list = self.collection.get_selected()
  5358. xminlist = []
  5359. yminlist = []
  5360. xmaxlist = []
  5361. ymaxlist = []
  5362. if not obj_list:
  5363. self.inform.emit('[WARNING_NOTCL] %s' %
  5364. _("No object selected to Rotate."))
  5365. else:
  5366. if silent is False:
  5367. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5368. min=-360, max=360, decimals=4,
  5369. init_val=float(self.defaults['tools_transform_rotate']))
  5370. num, ok = rotatebox.get_value()
  5371. else:
  5372. num = preset
  5373. ok = True
  5374. if ok:
  5375. try:
  5376. # first get a bounding box to fit all
  5377. for obj in obj_list:
  5378. xmin, ymin, xmax, ymax = obj.bounds()
  5379. xminlist.append(xmin)
  5380. yminlist.append(ymin)
  5381. xmaxlist.append(xmax)
  5382. ymaxlist.append(ymax)
  5383. # get the minimum x,y and maximum x,y for all objects selected
  5384. xminimal = min(xminlist)
  5385. yminimal = min(yminlist)
  5386. xmaximal = max(xmaxlist)
  5387. ymaximal = max(ymaxlist)
  5388. px = 0.5 * (xminimal + xmaximal)
  5389. py = 0.5 * (yminimal + ymaximal)
  5390. for sel_obj in obj_list:
  5391. sel_obj.rotate(-float(num), point=(px, py))
  5392. sel_obj.plot()
  5393. self.object_changed.emit(sel_obj)
  5394. self.inform.emit('[success] %s' %
  5395. _("Rotation done."))
  5396. except Exception as e:
  5397. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5398. (_("Rotation movement was not executed."), str(e)))
  5399. return
  5400. def on_skewx(self):
  5401. self.report_usage("on_skewx()")
  5402. obj_list = self.collection.get_selected()
  5403. xminlist = []
  5404. yminlist = []
  5405. if not obj_list:
  5406. self.inform.emit('[WARNING_NOTCL] %s' %
  5407. _("No object selected to Skew/Shear on X axis."))
  5408. else:
  5409. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5410. min=-360, max=360, decimals=4,
  5411. init_val=float(self.defaults['tools_transform_skew_x']))
  5412. num, ok = skewxbox.get_value()
  5413. if ok:
  5414. # first get a bounding box to fit all
  5415. for obj in obj_list:
  5416. xmin, ymin, xmax, ymax = obj.bounds()
  5417. xminlist.append(xmin)
  5418. yminlist.append(ymin)
  5419. # get the minimum x,y and maximum x,y for all objects selected
  5420. xminimal = min(xminlist)
  5421. yminimal = min(yminlist)
  5422. for obj in obj_list:
  5423. obj.skew(num, 0, point=(xminimal, yminimal))
  5424. obj.plot()
  5425. self.object_changed.emit(obj)
  5426. self.inform.emit('[success] %s' %
  5427. _("Skew on X axis done."))
  5428. def on_skewy(self):
  5429. self.report_usage("on_skewy()")
  5430. obj_list = self.collection.get_selected()
  5431. xminlist = []
  5432. yminlist = []
  5433. if not obj_list:
  5434. self.inform.emit('[WARNING_NOTCL] %s' %
  5435. _("No object selected to Skew/Shear on Y axis."))
  5436. else:
  5437. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5438. min=-360, max=360, decimals=4,
  5439. init_val=float(self.defaults['tools_transform_skew_y']))
  5440. num, ok = skewybox.get_value()
  5441. if ok:
  5442. # first get a bounding box to fit all
  5443. for obj in obj_list:
  5444. xmin, ymin, xmax, ymax = obj.bounds()
  5445. xminlist.append(xmin)
  5446. yminlist.append(ymin)
  5447. # get the minimum x,y and maximum x,y for all objects selected
  5448. xminimal = min(xminlist)
  5449. yminimal = min(yminlist)
  5450. for obj in obj_list:
  5451. obj.skew(0, num, point=(xminimal, yminimal))
  5452. obj.plot()
  5453. self.object_changed.emit(obj)
  5454. self.inform.emit('[success] %s' %
  5455. _("Skew on Y axis done."))
  5456. def on_plots_updated(self):
  5457. """
  5458. Callback used to report when the plots have changed.
  5459. Adjust axes and zooms to fit.
  5460. :return: None
  5461. """
  5462. self.plotcanvas.update() # TODO: Need update canvas?
  5463. self.on_zoom_fit(None)
  5464. self.collection.update_view()
  5465. # self.inform.emit(_("Plots updated ..."))
  5466. # TODO: Rework toolbar 'clear', 'replot' functions
  5467. def on_toolbar_replot(self):
  5468. """
  5469. Callback for toolbar button. Re-plots all objects.
  5470. :return: None
  5471. """
  5472. self.report_usage("on_toolbar_replot")
  5473. self.log.debug("on_toolbar_replot()")
  5474. try:
  5475. self.collection.get_active().read_form()
  5476. except AttributeError:
  5477. self.log.debug("on_toolbar_replot(): AttributeError")
  5478. pass
  5479. self.plot_all()
  5480. def on_row_activated(self, index):
  5481. if index.isValid():
  5482. if index.internalPointer().parent_item != self.collection.root_item:
  5483. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5484. self.collection.on_item_activated(index)
  5485. def grid_status(self):
  5486. if self.ui.grid_snap_btn.isChecked():
  5487. return True
  5488. else:
  5489. return False
  5490. def populate_cmenu_grids(self):
  5491. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5492. self.ui.cmenu_gridmenu.clear()
  5493. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5494. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  5495. grid_toggle.setCheckable(True)
  5496. if self.grid_status() == True:
  5497. grid_toggle.setChecked(True)
  5498. else:
  5499. grid_toggle.setChecked(False)
  5500. self.ui.cmenu_gridmenu.addSeparator()
  5501. for grid in sorted_list:
  5502. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  5503. action.triggered.connect(self.set_grid)
  5504. self.ui.cmenu_gridmenu.addSeparator()
  5505. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  5506. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  5507. grid_add.triggered.connect(self.on_grid_add)
  5508. grid_delete.triggered.connect(self.on_grid_delete)
  5509. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5510. def set_grid(self):
  5511. self.ui.grid_gap_x_entry.setText(self.sender().text())
  5512. self.ui.grid_gap_y_entry.setText(self.sender().text())
  5513. def on_grid_add(self):
  5514. # ## Current application units in lower Case
  5515. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5516. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5517. text=_('Enter a Grid Value:'),
  5518. min=0.0000, max=99.9999, decimals=4)
  5519. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  5520. val, ok = grid_add_popup.get_value()
  5521. if ok:
  5522. if float(val) == 0:
  5523. self.inform.emit('[WARNING_NOTCL] %s' %
  5524. _("Please enter a grid value with non-zero value, in Float format."))
  5525. return
  5526. else:
  5527. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5528. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5529. self.inform.emit('[success] %s...' %
  5530. _("New Grid added"))
  5531. else:
  5532. self.inform.emit('[WARNING_NOTCL] %s...' %
  5533. _("Grid already exists"))
  5534. else:
  5535. self.inform.emit('[WARNING_NOTCL] %s...' %
  5536. _("Adding New Grid cancelled"))
  5537. def on_grid_delete(self):
  5538. # ## Current application units in lower Case
  5539. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5540. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5541. text='Enter a Grid Value:',
  5542. min=0.0000, max=99.9999, decimals=4)
  5543. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  5544. val, ok = grid_del_popup.get_value()
  5545. if ok:
  5546. if float(val) == 0:
  5547. self.inform.emit('[WARNING_NOTCL] %s' %
  5548. _("Please enter a grid value with non-zero value, in Float format."))
  5549. return
  5550. else:
  5551. try:
  5552. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5553. except ValueError:
  5554. self.inform.emit('[ERROR_NOTCL]%s...' %
  5555. _(" Grid Value does not exist"))
  5556. return
  5557. self.inform.emit('[success] %s...' %
  5558. _("Grid Value deleted"))
  5559. else:
  5560. self.inform.emit('[WARNING_NOTCL] %s...' %
  5561. _("Delete Grid value cancelled"))
  5562. def on_shortcut_list(self):
  5563. self.report_usage("on_shortcut_list()")
  5564. # add the tab if it was closed
  5565. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5566. # delete the absolute and relative position and messages in the infobar
  5567. self.ui.position_label.setText("")
  5568. self.ui.rel_position_label.setText("")
  5569. # Switch plot_area to preferences page
  5570. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5571. self.ui.show()
  5572. def on_select_tab(self, name):
  5573. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5574. if self.ui.splitter.sizes()[0] == 0:
  5575. self.ui.splitter.setSizes([1, 1])
  5576. else:
  5577. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5578. self.ui.splitter.setSizes([0, 1])
  5579. if name == 'project':
  5580. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5581. elif name == 'selected':
  5582. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5583. elif name == 'tool':
  5584. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5585. def on_copy_name(self):
  5586. self.report_usage("on_copy_name()")
  5587. obj = self.collection.get_active()
  5588. try:
  5589. name = obj.options["name"]
  5590. except AttributeError:
  5591. log.debug("on_copy_name() --> No object selected to copy it's name")
  5592. self.inform.emit('[WARNING_NOTCL]%s' %
  5593. _(" No object selected to copy it's name"))
  5594. return
  5595. self.clipboard.setText(name)
  5596. self.inform.emit(_("Name copied on clipboard ..."))
  5597. def on_mouse_click_over_plot(self, event):
  5598. """
  5599. Default actions are:
  5600. :param event: Contains information about the event, like which button
  5601. was clicked, the pixel coordinates and the axes coordinates.
  5602. :return: None
  5603. """
  5604. self.pos = []
  5605. # So it can receive key presses
  5606. self.plotcanvas.native.setFocus()
  5607. # Set the mouse button for panning
  5608. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5609. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5610. if self.grid_status() == True:
  5611. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5612. self.app_cursor.enabled = True
  5613. else:
  5614. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5615. self.app_cursor.enabled = False
  5616. try:
  5617. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5618. if event.button == 1:
  5619. # Reset here the relative coordinates so there is a new reference on the click position
  5620. if self.rel_point1 is None:
  5621. self.rel_point1 = self.pos
  5622. else:
  5623. self.rel_point2 = copy(self.rel_point1)
  5624. self.rel_point1 = self.pos
  5625. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5626. if modifiers == QtCore.Qt.ShiftModifier:
  5627. # do not auto open the Project Tab
  5628. self.click_noproject = True
  5629. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5630. self.inform.emit('[success] %s' %
  5631. _("Coordinates copied to clipboard."))
  5632. return
  5633. self.on_mouse_move_over_plot(event, origin_click=True)
  5634. except Exception as e:
  5635. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5636. def on_double_click_over_plot(self, event):
  5637. self.doubleclick = True
  5638. def on_mouse_move_over_plot(self, event, origin_click=None):
  5639. """
  5640. Callback for the mouse motion event over the plot.
  5641. :param event: Contains information about the event.
  5642. :param origin_click
  5643. :return: None
  5644. """
  5645. # So it can receive key presses
  5646. self.plotcanvas.native.setFocus()
  5647. self.pos_jump = event.pos
  5648. self.ui.popMenu.mouse_is_panning = False
  5649. if not origin_click:
  5650. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5651. if event.button == 2 and event.is_dragging == 1:
  5652. self.ui.popMenu.mouse_is_panning = True
  5653. return
  5654. if self.rel_point1 is not None:
  5655. try: # May fail in case mouse not within axes
  5656. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5657. if self.grid_status() == True:
  5658. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5659. self.app_cursor.enabled = True
  5660. # Update cursor
  5661. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5662. else:
  5663. pos = (pos_canvas[0], pos_canvas[1])
  5664. self.app_cursor.enabled = False
  5665. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5666. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5667. dx = pos[0] - self.rel_point1[0]
  5668. dy = pos[1] - self.rel_point1[1]
  5669. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5670. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5671. self.mouse = [pos[0], pos[1]]
  5672. # if the mouse is moved and the LMB is clicked then the action is a selection
  5673. if event.is_dragging == 1 and event.button == 1:
  5674. self.delete_selection_shape()
  5675. if dx < 0:
  5676. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5677. face_color=self.defaults['global_alt_sel_fill'])
  5678. self.selection_type = False
  5679. else:
  5680. self.draw_moving_selection_shape(self.pos, pos)
  5681. self.selection_type = True
  5682. # hover effect - enabled in Preferences -> General -> GUI Settings
  5683. if self.defaults['global_hover']:
  5684. for obj in self.collection.get_list():
  5685. try:
  5686. # select the object(s) only if it is enabled (plotted)
  5687. if obj.options['plot']:
  5688. if obj not in self.collection.get_selected():
  5689. poly_obj = Polygon(
  5690. [(obj.options['xmin'], obj.options['ymin']),
  5691. (obj.options['xmax'], obj.options['ymin']),
  5692. (obj.options['xmax'], obj.options['ymax']),
  5693. (obj.options['xmin'], obj.options['ymax'])]
  5694. )
  5695. if Point(pos).within(poly_obj):
  5696. if obj.isHovering is False:
  5697. obj.isHovering = True
  5698. obj.notHovering = True
  5699. # create the selection box around the selected object
  5700. self.draw_hover_shape(obj, color='#d1e0e0')
  5701. else:
  5702. if obj.notHovering is True:
  5703. obj.notHovering = False
  5704. obj.isHovering = False
  5705. self.delete_hover_shape()
  5706. except:
  5707. # the Exception here will happen if we try to select on screen and we have an
  5708. # newly (and empty) just created Geometry or Excellon object that do not have the
  5709. # xmin, xmax, ymin, ymax options.
  5710. # In this case poly_obj creation (see above) will fail
  5711. pass
  5712. except:
  5713. self.ui.position_label.setText("")
  5714. self.ui.rel_position_label.setText("")
  5715. self.mouse = None
  5716. def on_mouse_click_release_over_plot(self, event):
  5717. """
  5718. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5719. and has been registered in ''self.__init__()''.
  5720. :param event: contains information about the event.
  5721. :return:
  5722. """
  5723. pos = 0, 0
  5724. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5725. if self.grid_status() == True:
  5726. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5727. else:
  5728. pos = (pos_canvas[0], pos_canvas[1])
  5729. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5730. # canvas menu
  5731. if event.button == 2: # right click
  5732. if self.ui.popMenu.mouse_is_panning is False:
  5733. self.cursor = QtGui.QCursor()
  5734. self.populate_cmenu_grids()
  5735. self.ui.popMenu.popup(self.cursor.pos())
  5736. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5737. # selection and then select a type of selection ("enclosing" or "touching")
  5738. try:
  5739. if event.button == 1: # left click
  5740. if self.doubleclick is True:
  5741. self.doubleclick = False
  5742. if self.collection.get_selected():
  5743. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5744. if self.ui.splitter.sizes()[0] == 0:
  5745. self.ui.splitter.setSizes([1, 1])
  5746. # delete the selection shape(S) as it may be in the way
  5747. self.delete_selection_shape()
  5748. self.delete_hover_shape()
  5749. else:
  5750. if self.selection_type is not None:
  5751. self.selection_area_handler(self.pos, pos, self.selection_type)
  5752. self.selection_type = None
  5753. else:
  5754. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5755. if key_modifier == QtCore.Qt.ShiftModifier:
  5756. mod_key = 'Shift'
  5757. elif key_modifier == QtCore.Qt.ControlModifier:
  5758. mod_key = 'Control'
  5759. else:
  5760. mod_key = None
  5761. if mod_key == self.defaults["global_mselect_key"]:
  5762. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5763. # deselect, and if it's not selected then it will be selected
  5764. # If there is no active command (self.command_active is None) then we check if we clicked
  5765. # on a object by checking the bounding limits against mouse click position
  5766. if self.command_active is None:
  5767. self.select_objects(key='CTRL')
  5768. self.delete_hover_shape()
  5769. else:
  5770. # If there is no active command (self.command_active is None) then we check if we clicked
  5771. # on a object by checking the bounding limits against mouse click position
  5772. if self.command_active is None:
  5773. self.select_objects()
  5774. self.delete_hover_shape()
  5775. except Exception as e:
  5776. log.warning("Error: %s" % str(e))
  5777. return
  5778. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5779. """
  5780. :param start_pos: mouse position when the selection LMB click was done
  5781. :param end_pos: mouse position when the left mouse button is released
  5782. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5783. :return:
  5784. """
  5785. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5786. self.delete_selection_shape()
  5787. for obj in self.collection.get_list():
  5788. try:
  5789. # select the object(s) only if it is enabled (plotted)
  5790. if obj.options['plot']:
  5791. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5792. (obj.options['xmax'], obj.options['ymin']),
  5793. (obj.options['xmax'], obj.options['ymax']),
  5794. (obj.options['xmin'], obj.options['ymax'])])
  5795. if sel_type is True:
  5796. if poly_obj.within(poly_selection):
  5797. # create the selection box around the selected object
  5798. if self.defaults['global_selection_shape'] is True:
  5799. self.draw_selection_shape(obj)
  5800. self.collection.set_active(obj.options['name'])
  5801. else:
  5802. if poly_selection.intersects(poly_obj):
  5803. # create the selection box around the selected object
  5804. if self.defaults['global_selection_shape'] is True:
  5805. self.draw_selection_shape(obj)
  5806. self.collection.set_active(obj.options['name'])
  5807. except Exception as e:
  5808. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5809. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5810. # In this case poly_obj creation (see above) will fail
  5811. log.debug("App.selection_area_handler() --> %s" % str(e))
  5812. def select_objects(self, key=None):
  5813. # list where we store the overlapped objects under our mouse left click position
  5814. objects_under_the_click_list = []
  5815. # Populate the list with the overlapped objects on the click position
  5816. curr_x, curr_y = self.pos
  5817. for obj in self.all_objects_list:
  5818. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5819. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5820. if obj.options['name'] not in objects_under_the_click_list:
  5821. if obj.options['plot']:
  5822. # add objects to the objects_under_the_click list only if the object is plotted
  5823. # (active and not disabled)
  5824. objects_under_the_click_list.append(obj.options['name'])
  5825. try:
  5826. # If there is no element in the overlapped objects list then make everyone inactive
  5827. # because we selected "nothing"
  5828. if not objects_under_the_click_list:
  5829. self.collection.set_all_inactive()
  5830. # delete the possible selection box around a possible selected object
  5831. self.delete_selection_shape()
  5832. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5833. # only when working on App
  5834. if self.call_source == 'app':
  5835. if self.click_noproject is False:
  5836. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5837. else:
  5838. # restore auto open the Project Tab
  5839. self.click_noproject = False
  5840. # delete any text in the status bar, implicitly the last object name that was selected
  5841. self.inform.emit("")
  5842. else:
  5843. self.call_source = 'app'
  5844. else:
  5845. # case when there is only an object under the click and we toggle it
  5846. if len(objects_under_the_click_list) == 1:
  5847. if self.collection.get_active() is None:
  5848. self.collection.set_active(objects_under_the_click_list[0])
  5849. # create the selection box around the selected object
  5850. curr_sel_obj = self.collection.get_active()
  5851. if self.defaults['global_selection_shape'] is True:
  5852. self.draw_selection_shape(curr_sel_obj)
  5853. # self.inform.emit('[selected] %s: %s selected' %
  5854. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5855. if curr_sel_obj.kind == 'gerber':
  5856. self.inform.emit(
  5857. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5858. color='green', name=str(curr_sel_obj.options['name'])))
  5859. elif curr_sel_obj.kind == 'excellon':
  5860. self.inform.emit(
  5861. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5862. color='brown', name=str(curr_sel_obj.options['name'])))
  5863. elif curr_sel_obj.kind == 'cncjob':
  5864. self.inform.emit(
  5865. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5866. color='blue', name=str(curr_sel_obj.options['name'])))
  5867. elif curr_sel_obj.kind == 'geometry':
  5868. self.inform.emit(
  5869. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5870. color='red', name=str(curr_sel_obj.options['name'])))
  5871. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  5872. self.collection.set_all_inactive()
  5873. self.delete_selection_shape()
  5874. self.collection.set_active(objects_under_the_click_list[0])
  5875. # create the selection box around the selected object
  5876. curr_sel_obj = self.collection.get_active()
  5877. if self.defaults['global_selection_shape'] is True:
  5878. self.draw_selection_shape(curr_sel_obj)
  5879. # self.inform.emit('[selected] %s: %s selected' %
  5880. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5881. if curr_sel_obj.kind == 'gerber':
  5882. self.inform.emit(
  5883. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5884. color='green', name=str(curr_sel_obj.options['name'])))
  5885. elif curr_sel_obj.kind == 'excellon':
  5886. self.inform.emit(
  5887. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5888. color='brown', name=str(curr_sel_obj.options['name'])))
  5889. elif curr_sel_obj.kind == 'cncjob':
  5890. self.inform.emit(
  5891. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5892. color='blue', name=str(curr_sel_obj.options['name'])))
  5893. elif curr_sel_obj.kind == 'geometry':
  5894. self.inform.emit(
  5895. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5896. color='red', name=str(curr_sel_obj.options['name'])))
  5897. else:
  5898. self.collection.set_all_inactive()
  5899. self.delete_selection_shape()
  5900. if self.call_source == 'app':
  5901. # delete any text in the status bar, implicitly the last object name that was selected
  5902. self.inform.emit("")
  5903. else:
  5904. self.call_source = 'app'
  5905. else:
  5906. # If there is no selected object
  5907. # make active the first element of the overlapped objects list
  5908. if self.collection.get_active() is None:
  5909. self.collection.set_active(objects_under_the_click_list[0])
  5910. name_sel_obj = self.collection.get_active().options['name']
  5911. # In case that there is a selected object but it is not in the overlapped object list
  5912. # make that object inactive and activate the first element in the overlapped object list
  5913. if name_sel_obj not in objects_under_the_click_list:
  5914. self.collection.set_inactive(name_sel_obj)
  5915. name_sel_obj = objects_under_the_click_list[0]
  5916. self.collection.set_active(name_sel_obj)
  5917. else:
  5918. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  5919. self.collection.set_all_inactive()
  5920. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  5921. len(objects_under_the_click_list)])
  5922. curr_sel_obj = self.collection.get_active()
  5923. # delete the possible selection box around a possible selected object
  5924. self.delete_selection_shape()
  5925. # create the selection box around the selected object
  5926. if self.defaults['global_selection_shape'] is True:
  5927. self.draw_selection_shape(curr_sel_obj)
  5928. # self.inform.emit('[selected] %s: %s selected' %
  5929. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5930. if curr_sel_obj.kind == 'gerber':
  5931. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5932. color='green', name=str(curr_sel_obj.options['name'])))
  5933. elif curr_sel_obj.kind == 'excellon':
  5934. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5935. color='brown', name=str(curr_sel_obj.options['name'])))
  5936. elif curr_sel_obj.kind == 'cncjob':
  5937. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5938. color='blue', name=str(curr_sel_obj.options['name'])))
  5939. elif curr_sel_obj.kind == 'geometry':
  5940. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5941. color='red', name=str(curr_sel_obj.options['name'])))
  5942. # for obj in self.collection.get_list():
  5943. # obj.plot()
  5944. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  5945. # TODO: on selected objects change the object colors and do not draw the selection box
  5946. # self.plotcanvas.update() # this updates the canvas
  5947. except Exception as e:
  5948. log.error("[ERROR] Something went bad. %s" % str(e))
  5949. return
  5950. def delete_hover_shape(self):
  5951. self.hover_shapes.clear()
  5952. self.hover_shapes.redraw()
  5953. def draw_hover_shape(self, sel_obj, color=None):
  5954. """
  5955. :param sel_obj: the object for which the hover shape must be drawn
  5956. :return:
  5957. """
  5958. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5959. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5960. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5961. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5962. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5963. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5964. hover_rect = hover_rect.buffer(-0.1)
  5965. hover_rect = hover_rect.buffer(0.2)
  5966. else:
  5967. hover_rect = hover_rect.buffer(-0.00393)
  5968. hover_rect = hover_rect.buffer(0.00787)
  5969. if color:
  5970. face = Color(color)
  5971. face.alpha = 0.2
  5972. outline = Color(color, alpha=0.8)
  5973. else:
  5974. face = Color(self.defaults['global_sel_fill'])
  5975. face.alpha = 0.2
  5976. outline = self.defaults['global_sel_line']
  5977. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5978. def delete_selection_shape(self):
  5979. self.move_tool.sel_shapes.clear()
  5980. self.move_tool.sel_shapes.redraw()
  5981. def draw_selection_shape(self, sel_obj, color=None):
  5982. """
  5983. :param sel_obj: the object for which the selection shape must be drawn
  5984. :return:
  5985. """
  5986. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5987. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5988. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5989. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5990. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5991. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5992. sel_rect = sel_rect.buffer(-0.1)
  5993. sel_rect = sel_rect.buffer(0.2)
  5994. else:
  5995. sel_rect = sel_rect.buffer(-0.00393)
  5996. sel_rect = sel_rect.buffer(0.00787)
  5997. if color:
  5998. face = Color(color, alpha=0.2)
  5999. outline = Color(color, alpha=0.8)
  6000. else:
  6001. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6002. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6003. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6004. color=outline,
  6005. face_color=face,
  6006. update=True,
  6007. layer=0,
  6008. tolerance=None))
  6009. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6010. """
  6011. :param old_coords: old coordinates
  6012. :param coords: new coordinates
  6013. :return:
  6014. """
  6015. if 'color' in kwargs:
  6016. color = kwargs['color']
  6017. else:
  6018. color = self.defaults['global_sel_line']
  6019. if 'face_color' in kwargs:
  6020. face_color = kwargs['face_color']
  6021. else:
  6022. face_color = self.defaults['global_sel_fill']
  6023. if 'face_alpha' in kwargs:
  6024. face_alpha = kwargs['face_alpha']
  6025. else:
  6026. face_alpha = 0.3
  6027. x0, y0 = old_coords
  6028. x1, y1 = coords
  6029. pt1 = (x0, y0)
  6030. pt2 = (x1, y0)
  6031. pt3 = (x1, y1)
  6032. pt4 = (x0, y1)
  6033. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6034. color_t = Color(face_color)
  6035. color_t.alpha = face_alpha
  6036. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6037. layer=0, tolerance=None)
  6038. def on_file_new_click(self):
  6039. if self.collection.get_list() and self.should_we_save:
  6040. msgbox = QtWidgets.QMessageBox()
  6041. # msgbox.setText("<B>Save changes ...</B>")
  6042. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6043. "Creating a New project will delete them.\n"
  6044. "Do you want to Save the project?"))
  6045. msgbox.setWindowTitle(_("Save changes"))
  6046. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6047. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6048. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6049. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6050. msgbox.setDefaultButton(bt_yes)
  6051. msgbox.exec_()
  6052. response = msgbox.clickedButton()
  6053. if response == bt_yes:
  6054. self.on_file_saveprojectas()
  6055. elif response == bt_cancel:
  6056. return
  6057. elif response == bt_no:
  6058. self.on_file_new()
  6059. else:
  6060. self.on_file_new()
  6061. self.inform.emit('[success] %s...' %
  6062. _("New Project created"))
  6063. def on_file_new(self):
  6064. """
  6065. Callback for menu item File->New. Returns the application to its
  6066. startup state. This method is thread-safe.
  6067. :return: None
  6068. """
  6069. self.report_usage("on_file_new")
  6070. # Remove everything from memory
  6071. App.log.debug("on_file_new()")
  6072. if self.call_source != 'app':
  6073. self.editor2object(cleanup=True)
  6074. # ## EDITOR section
  6075. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6076. self.exc_editor = FlatCAMExcEditor(self)
  6077. self.grb_editor = FlatCAMGrbEditor(self)
  6078. # Clear pool
  6079. self.clear_pool()
  6080. for obj in self.collection.get_list():
  6081. # delete shapes left drawn from mark shape_collections, if any
  6082. if isinstance(obj, FlatCAMGerber):
  6083. try:
  6084. obj.mark_shapes.enabled = False
  6085. obj.mark_shapes.clear(update=True)
  6086. except AttributeError:
  6087. pass
  6088. # also delete annotation shapes, if any
  6089. elif isinstance(obj, FlatCAMCNCjob):
  6090. try:
  6091. obj.annotation.enabled = False
  6092. obj.annotation.clear(update=True)
  6093. except AttributeError:
  6094. pass
  6095. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6096. self.init_tcl()
  6097. self.delete_selection_shape()
  6098. self.collection.delete_all()
  6099. self.setup_component_editor()
  6100. # Clear project filename
  6101. self.project_filename = None
  6102. # Load the application defaults
  6103. self.load_defaults(filename='current_defaults')
  6104. # Re-fresh project options
  6105. self.on_options_app2project()
  6106. # Init Tools
  6107. self.init_tools()
  6108. # Close any Tabs opened in the Plot Tab Area section
  6109. for index in range(self.ui.plot_tab_area.count()):
  6110. self.ui.plot_tab_area.closeTab(index)
  6111. # for whatever reason previous command does not close the last tab so I do it manually
  6112. self.ui.plot_tab_area.closeTab(0)
  6113. # # And then add again the Plot Area
  6114. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6115. self.ui.plot_tab_area.protectTab(0)
  6116. # take the focus of the Notebook on Project Tab.
  6117. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6118. self.set_ui_title(name=_("New Project - Not saved"))
  6119. def obj_properties(self):
  6120. self.report_usage("obj_properties()")
  6121. self.properties_tool.run(toggle=False)
  6122. def on_project_context_save(self):
  6123. obj = self.collection.get_active()
  6124. if type(obj) == FlatCAMGeometry:
  6125. self.on_file_exportdxf()
  6126. elif type(obj) == FlatCAMExcellon:
  6127. self.on_file_saveexcellon()
  6128. elif type(obj) == FlatCAMCNCjob:
  6129. obj.on_exportgcode_button_click()
  6130. elif type(obj) == FlatCAMGerber:
  6131. self.on_file_savegerber()
  6132. def obj_move(self):
  6133. self.report_usage("obj_move()")
  6134. self.move_tool.run(toggle=False)
  6135. def on_fileopengerber(self, checked=None, name=None):
  6136. """
  6137. File menu callback for opening a Gerber.
  6138. :return: None
  6139. """
  6140. self.report_usage("on_fileopengerber")
  6141. App.log.debug("on_fileopengerber()")
  6142. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6143. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6144. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6145. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6146. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6147. "*.mil);;" \
  6148. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6149. "Allegro Files (*.art);;" \
  6150. "Mentor Files (*.pho *.gdo);;" \
  6151. "All Files (*.*)"
  6152. if name is None:
  6153. try:
  6154. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6155. directory=self.get_last_folder(),
  6156. filter=_filter_)
  6157. except TypeError:
  6158. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6159. filenames = [str(filename) for filename in filenames]
  6160. else:
  6161. filenames = [name]
  6162. if len(filenames) == 0:
  6163. self.inform.emit('[WARNING_NOTCL] %s' %
  6164. _("Open Gerber cancelled."))
  6165. else:
  6166. for filename in filenames:
  6167. if filename != '':
  6168. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6169. def on_fileopenexcellon(self, checked=None, name=None):
  6170. """
  6171. File menu callback for opening an Excellon file.
  6172. :return: None
  6173. """
  6174. self.report_usage("on_fileopenexcellon")
  6175. App.log.debug("on_fileopenexcellon()")
  6176. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6177. "All Files (*.*)"
  6178. if name is None:
  6179. try:
  6180. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6181. directory=self.get_last_folder(),
  6182. filter=_filter_)
  6183. except TypeError:
  6184. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6185. filenames = [str(filename) for filename in filenames]
  6186. else:
  6187. filenames = [str(name)]
  6188. if len(filenames) == 0:
  6189. self.inform.emit('[WARNING_NOTCL]%s' %
  6190. _(" Open Excellon cancelled."))
  6191. else:
  6192. for filename in filenames:
  6193. if filename != '':
  6194. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6195. def on_fileopengcode(self, checked=None, name=None):
  6196. """
  6197. File menu call back for opening gcode.
  6198. :return: None
  6199. """
  6200. self.report_usage("on_fileopengcode")
  6201. App.log.debug("on_fileopengcode()")
  6202. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6203. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6204. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6205. "All Files (*.*)"
  6206. if name is None:
  6207. try:
  6208. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6209. directory=self.get_last_folder(),
  6210. filter=_filter_)
  6211. except TypeError:
  6212. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6213. filenames = [str(filename) for filename in filenames]
  6214. else:
  6215. filenames = [name]
  6216. if len(filenames) == 0:
  6217. self.inform.emit('[WARNING_NOTCL] %s' %
  6218. _("Open G-Code cancelled."))
  6219. else:
  6220. for filename in filenames:
  6221. if filename != '':
  6222. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6223. def on_file_openproject(self, checked=None):
  6224. """
  6225. File menu callback for opening a project.
  6226. :return: None
  6227. """
  6228. self.report_usage("on_file_openproject")
  6229. App.log.debug("on_file_openproject()")
  6230. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6231. try:
  6232. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6233. directory=self.get_last_folder(), filter=_filter_)
  6234. except TypeError:
  6235. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6236. # The Qt methods above will return a QString which can cause problems later.
  6237. # So far json.dump() will fail to serialize it.
  6238. # TODO: Improve the serialization methods and remove this fix.
  6239. filename = str(filename)
  6240. if filename == "":
  6241. self.inform.emit('[WARNING_NOTCL] %s' %
  6242. _("Open Project cancelled."))
  6243. else:
  6244. # self.worker_task.emit({'fcn': self.open_project,
  6245. # 'params': [filename]})
  6246. # The above was failing because open_project() is not
  6247. # thread safe. The new_project()
  6248. self.open_project(filename)
  6249. def on_file_openconfig(self, checked=None):
  6250. """
  6251. File menu callback for opening a config file.
  6252. :return: None
  6253. """
  6254. self.report_usage("on_file_openconfig")
  6255. App.log.debug("on_file_openconfig()")
  6256. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6257. try:
  6258. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6259. directory=self.data_path, filter=_filter_)
  6260. except TypeError:
  6261. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6262. filter=_filter_)
  6263. if filename == "":
  6264. self.inform.emit('[WARNING_NOTCL] %s' %
  6265. _("Open Config cancelled."))
  6266. else:
  6267. self.open_config_file(filename)
  6268. def on_file_exportsvg(self):
  6269. """
  6270. Callback for menu item File->Export SVG.
  6271. :return: None
  6272. """
  6273. self.report_usage("on_file_exportsvg")
  6274. App.log.debug("on_file_exportsvg()")
  6275. obj = self.collection.get_active()
  6276. if obj is None:
  6277. self.inform.emit('[WARNING_NOTCL] %s' %
  6278. _("No object selected."))
  6279. msg = _("Please Select a Geometry object to export")
  6280. msgbox = QtWidgets.QMessageBox()
  6281. msgbox.setInformativeText(msg)
  6282. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6283. msgbox.setDefaultButton(bt_ok)
  6284. msgbox.exec_()
  6285. return
  6286. # Check for more compatible types and add as required
  6287. if (not isinstance(obj, FlatCAMGeometry)
  6288. and not isinstance(obj, FlatCAMGerber)
  6289. and not isinstance(obj, FlatCAMCNCjob)
  6290. and not isinstance(obj, FlatCAMExcellon)):
  6291. msg = '[ERROR_NOTCL] %s' % \
  6292. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6293. msgbox = QtWidgets.QMessageBox()
  6294. msgbox.setInformativeText(msg)
  6295. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6296. msgbox.setDefaultButton(bt_ok)
  6297. msgbox.exec_()
  6298. return
  6299. name = obj.options["name"]
  6300. _filter = "SVG File (*.svg);;All Files (*.*)"
  6301. try:
  6302. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6303. caption=_("Export SVG"),
  6304. directory=self.get_last_save_folder() + '/' + str(name),
  6305. filter=_filter)
  6306. except TypeError:
  6307. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6308. filename = str(filename)
  6309. if filename == "":
  6310. self.inform.emit('[WARNING_NOTCL]%s' %
  6311. _(" Export SVG cancelled."))
  6312. return
  6313. else:
  6314. self.export_svg(name, filename)
  6315. if self.defaults["global_open_style"] is False:
  6316. self.file_opened.emit("SVG", filename)
  6317. self.file_saved.emit("SVG", filename)
  6318. def on_file_exportpng(self):
  6319. self.report_usage("on_file_exportpng")
  6320. App.log.debug("on_file_exportpng()")
  6321. self.date = str(datetime.today()).rpartition('.')[0]
  6322. self.date = ''.join(c for c in self.date if c not in ':-')
  6323. self.date = self.date.replace(' ', '_')
  6324. image = _screenshot()
  6325. data = np.asarray(image)
  6326. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6327. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6328. _('Data must be a 3D array with last dimension 3 or 4'))
  6329. return
  6330. filter_ = "PNG File (*.png);;All Files (*.*)"
  6331. try:
  6332. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6333. caption=_("Export PNG Image"),
  6334. directory=self.get_last_save_folder() + '/png_' + self.date,
  6335. filter=filter_)
  6336. except TypeError:
  6337. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6338. filename = str(filename)
  6339. if filename == "":
  6340. self.inform.emit(_("Export PNG cancelled."))
  6341. return
  6342. else:
  6343. write_png(filename, data)
  6344. if self.defaults["global_open_style"] is False:
  6345. self.file_opened.emit("png", filename)
  6346. self.file_saved.emit("png", filename)
  6347. def on_file_savegerber(self):
  6348. """
  6349. Callback for menu item in Project context menu.
  6350. :return: None
  6351. """
  6352. self.report_usage("on_file_savegerber")
  6353. App.log.debug("on_file_savegerber()")
  6354. obj = self.collection.get_active()
  6355. if obj is None:
  6356. self.inform.emit('[WARNING_NOTCL] %s' %
  6357. _("No object selected. Please select an Gerber object to export."))
  6358. return
  6359. # Check for more compatible types and add as required
  6360. if not isinstance(obj, FlatCAMGerber):
  6361. self.inform.emit('[ERROR_NOTCL] %s' %
  6362. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6363. return
  6364. name = self.collection.get_active().options["name"]
  6365. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6366. try:
  6367. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6368. caption="Save Gerber source file",
  6369. directory=self.get_last_save_folder() + '/' + name,
  6370. filter=_filter)
  6371. except TypeError:
  6372. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  6373. filename = str(filename)
  6374. if filename == "":
  6375. self.inform.emit('[WARNING_NOTCL] %s' %
  6376. _("Save Gerber source file cancelled."))
  6377. return
  6378. else:
  6379. self.save_source_file(name, filename)
  6380. if self.defaults["global_open_style"] is False:
  6381. self.file_opened.emit("Gerber", filename)
  6382. self.file_saved.emit("Gerber", filename)
  6383. def on_file_saveexcellon(self):
  6384. """
  6385. Callback for menu item in project context menu.
  6386. :return: None
  6387. """
  6388. self.report_usage("on_file_saveexcellon")
  6389. App.log.debug("on_file_saveexcellon()")
  6390. obj = self.collection.get_active()
  6391. if obj is None:
  6392. self.inform.emit('[WARNING_NOTCL] %s' %
  6393. _("No object selected. Please select an Excellon object to export."))
  6394. return
  6395. # Check for more compatible types and add as required
  6396. if not isinstance(obj, FlatCAMExcellon):
  6397. self.inform.emit('[ERROR_NOTCL] %s' %
  6398. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6399. return
  6400. name = self.collection.get_active().options["name"]
  6401. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6402. try:
  6403. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6404. caption=_("Save Excellon source file"),
  6405. directory=self.get_last_save_folder() + '/' + name,
  6406. filter=_filter)
  6407. except TypeError:
  6408. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  6409. filename = str(filename)
  6410. if filename == "":
  6411. self.inform.emit('[WARNING_NOTCL] %s' %
  6412. _("Saving Excellon source file cancelled."))
  6413. return
  6414. else:
  6415. self.save_source_file(name, filename)
  6416. if self.defaults["global_open_style"] is False:
  6417. self.file_opened.emit("Excellon", filename)
  6418. self.file_saved.emit("Excellon", filename)
  6419. def on_file_exportexcellon(self):
  6420. """
  6421. Callback for menu item File->Export->Excellon.
  6422. :return: None
  6423. """
  6424. self.report_usage("on_file_exportexcellon")
  6425. App.log.debug("on_file_exportexcellon()")
  6426. obj = self.collection.get_active()
  6427. if obj is None:
  6428. self.inform.emit('[WARNING_NOTCL] %s' %
  6429. _("No object selected. Please Select an Excellon object to export."))
  6430. return
  6431. # Check for more compatible types and add as required
  6432. if not isinstance(obj, FlatCAMExcellon):
  6433. self.inform.emit('[ERROR_NOTCL] %s' %
  6434. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6435. return
  6436. name = self.collection.get_active().options["name"]
  6437. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6438. try:
  6439. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6440. caption=_("Export Excellon"),
  6441. directory=self.get_last_save_folder() + '/' + name,
  6442. filter=_filter)
  6443. except TypeError:
  6444. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  6445. filename = str(filename)
  6446. if filename == "":
  6447. self.inform.emit('[WARNING_NOTCL] %s' %
  6448. _("Export Excellon cancelled."))
  6449. return
  6450. else:
  6451. self.export_excellon(name, filename)
  6452. if self.defaults["global_open_style"] is False:
  6453. self.file_opened.emit("Excellon", filename)
  6454. self.file_saved.emit("Excellon", filename)
  6455. def on_file_exportgerber(self):
  6456. """
  6457. Callback for menu item File->Export->Gerber.
  6458. :return: None
  6459. """
  6460. self.report_usage("on_file_exportgerber")
  6461. App.log.debug("on_file_exportgerber()")
  6462. obj = self.collection.get_active()
  6463. if obj is None:
  6464. self.inform.emit('[WARNING_NOTCL] %s' %
  6465. _("No object selected. Please Select an Gerber object to export."))
  6466. return
  6467. # Check for more compatible types and add as required
  6468. if not isinstance(obj, FlatCAMGerber):
  6469. self.inform.emit('[ERROR_NOTCL] %s' %
  6470. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6471. return
  6472. name = self.collection.get_active().options["name"]
  6473. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  6474. try:
  6475. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6476. caption=_("Export Gerber"),
  6477. directory=self.get_last_save_folder() + '/' + name,
  6478. filter=_filter_)
  6479. except TypeError:
  6480. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  6481. filename = str(filename)
  6482. if filename == "":
  6483. self.inform.emit('[WARNING_NOTCL] %s' %
  6484. _("Export Gerber cancelled."))
  6485. return
  6486. else:
  6487. self.export_gerber(name, filename)
  6488. if self.defaults["global_open_style"] is False:
  6489. self.file_opened.emit("Gerber", filename)
  6490. self.file_saved.emit("Gerber", filename)
  6491. def on_file_exportdxf(self):
  6492. """
  6493. Callback for menu item File->Export DXF.
  6494. :return: None
  6495. """
  6496. self.report_usage("on_file_exportdxf")
  6497. App.log.debug("on_file_exportdxf()")
  6498. obj = self.collection.get_active()
  6499. if obj is None:
  6500. self.inform.emit('[WARNING_NOTCL] %s' %
  6501. _("No object selected."))
  6502. msg = _("Please Select a Geometry object to export")
  6503. msgbox = QtWidgets.QMessageBox()
  6504. msgbox.setInformativeText(msg)
  6505. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6506. msgbox.setDefaultButton(bt_ok)
  6507. msgbox.exec_()
  6508. return
  6509. # Check for more compatible types and add as required
  6510. if not isinstance(obj, FlatCAMGeometry):
  6511. msg = '[ERROR_NOTCL] %s' % \
  6512. _("Only Geometry objects can be used.")
  6513. msgbox = QtWidgets.QMessageBox()
  6514. msgbox.setInformativeText(msg)
  6515. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6516. msgbox.setDefaultButton(bt_ok)
  6517. msgbox.exec_()
  6518. return
  6519. name = self.collection.get_active().options["name"]
  6520. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6521. try:
  6522. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6523. caption=_("Export DXF"),
  6524. directory=self.get_last_save_folder() + '/' + name,
  6525. filter=_filter_)
  6526. except TypeError:
  6527. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  6528. filter=_filter_)
  6529. filename = str(filename)
  6530. if filename == "":
  6531. self.inform.emit('[WARNING_NOTCL] %s' %
  6532. _("Export DXF cancelled."))
  6533. return
  6534. else:
  6535. self.export_dxf(name, filename)
  6536. if self.defaults["global_open_style"] is False:
  6537. self.file_opened.emit("DXF", filename)
  6538. self.file_saved.emit("DXF", filename)
  6539. def on_file_importsvg(self, type_of_obj):
  6540. """
  6541. Callback for menu item File->Import SVG.
  6542. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6543. :type type_of_obj: str
  6544. :return: None
  6545. """
  6546. self.report_usage("on_file_importsvg")
  6547. App.log.debug("on_file_importsvg()")
  6548. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  6549. try:
  6550. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6551. directory=self.get_last_folder(), filter=_filter_)
  6552. except TypeError:
  6553. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6554. filter=_filter_)
  6555. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6556. type_of_obj = "geometry"
  6557. filenames = [str(filename) for filename in filenames]
  6558. if len(filenames) == 0:
  6559. self.inform.emit('[WARNING_NOTCL] %s' %
  6560. _("Open SVG cancelled."))
  6561. else:
  6562. for filename in filenames:
  6563. if filename != '':
  6564. self.worker_task.emit({'fcn': self.import_svg,
  6565. 'params': [filename, type_of_obj]})
  6566. def on_file_importdxf(self, type_of_obj):
  6567. """
  6568. Callback for menu item File->Import DXF.
  6569. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6570. :type type_of_obj: str
  6571. :return: None
  6572. """
  6573. self.report_usage("on_file_importdxf")
  6574. App.log.debug("on_file_importdxf()")
  6575. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6576. try:
  6577. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6578. directory=self.get_last_folder(),
  6579. filter=_filter_)
  6580. except TypeError:
  6581. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6582. filter=_filter_)
  6583. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6584. type_of_obj = "geometry"
  6585. filenames = [str(filename) for filename in filenames]
  6586. if len(filenames) == 0:
  6587. self.inform.emit('[WARNING_NOTCL] %s' %
  6588. _("Open DXF cancelled."))
  6589. else:
  6590. for filename in filenames:
  6591. if filename != '':
  6592. self.worker_task.emit({'fcn': self.import_dxf,
  6593. 'params': [filename, type_of_obj]})
  6594. # ###############################################################################################################
  6595. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6596. # ###############################################################################################################
  6597. def init_code_editor(self, name):
  6598. # Signals section
  6599. # Disconnect the old signals
  6600. try:
  6601. self.ui.buttonOpen.clicked.disconnect()
  6602. except TypeError:
  6603. pass
  6604. try:
  6605. self.ui.buttonSave.clicked.disconnect()
  6606. except TypeError:
  6607. pass
  6608. # add the tab if it was closed
  6609. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  6610. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  6611. # delete the absolute and relative position and messages in the infobar
  6612. self.ui.position_label.setText("")
  6613. self.ui.rel_position_label.setText("")
  6614. # first clear previous text in text editor (if any)
  6615. self.ui.code_editor.clear()
  6616. self.ui.code_editor.setReadOnly(False)
  6617. self.toggle_codeeditor = True
  6618. self.ui.code_editor.completer_enable = False
  6619. # Switch plot_area to CNCJob tab
  6620. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6621. def on_view_source(self):
  6622. self.inform.emit('%s' %
  6623. _("Viewing the source code of the selected object."))
  6624. self.proc_container.view.set_busy(_("Loading..."))
  6625. try:
  6626. obj = self.collection.get_active()
  6627. except Exception as e:
  6628. log.debug("App.on_view_source() --> %s" % str(e))
  6629. self.inform.emit('[WARNING_NOTCL] %s' %
  6630. _("Select an Gerber or Excellon file to view it's source file."))
  6631. return 'fail'
  6632. if obj.kind == 'gerber':
  6633. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  6634. else:
  6635. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  6636. self.init_code_editor(name=_("Source Editor"))
  6637. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6638. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6639. # then append the text from GCode to the text editor
  6640. try:
  6641. file = StringIO(obj.source_file)
  6642. except AttributeError:
  6643. self.inform.emit('[WARNING_NOTCL] %s' %
  6644. _("There is no selected object for which to see it's source file code."))
  6645. return 'fail'
  6646. self.ui.cncjob_frame.hide()
  6647. try:
  6648. for line in file:
  6649. QtWidgets.QApplication.processEvents()
  6650. proc_line = str(line).strip('\n')
  6651. self.ui.code_editor.append(proc_line)
  6652. except Exception as e:
  6653. log.debug('App.on_view_source() -->%s' % str(e))
  6654. self.inform.emit('[ERROR] %s: %s' %
  6655. (_('Failed to load the source code for the selected object'), str(e)))
  6656. return
  6657. self.handleTextChanged()
  6658. self.ui.cncjob_frame.show()
  6659. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6660. self.proc_container.view.set_idle()
  6661. # self.ui.show()
  6662. def on_toggle_code_editor(self):
  6663. self.report_usage("on_toggle_code_editor()")
  6664. if self.toggle_codeeditor is False:
  6665. self.init_code_editor(name=_("Code Editor"))
  6666. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  6667. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  6668. else:
  6669. for idx in range(self.ui.plot_tab_area.count()):
  6670. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  6671. self.ui.plot_tab_area.closeTab(idx)
  6672. break
  6673. self.toggle_codeeditor = False
  6674. def on_filenewscript(self):
  6675. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6676. self.init_code_editor(name=_("Script Editor"))
  6677. self.ui.code_editor.completer_enable = True
  6678. self.ui.code_editor.append(_(
  6679. "#\n"
  6680. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  6681. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  6682. "#\n\n"
  6683. "# FlatCAM commands list:\n"
  6684. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  6685. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  6686. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  6687. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  6688. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  6689. "# WriteGCode\n"
  6690. "#\n\n"
  6691. ))
  6692. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6693. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6694. self.handleTextChanged()
  6695. self.ui.code_editor.show()
  6696. def on_fileopenscript(self):
  6697. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6698. try:
  6699. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  6700. directory=self.get_last_folder(), filter=_filter_)
  6701. except TypeError:
  6702. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  6703. # The Qt methods above will return a QString which can cause problems later.
  6704. # So far json.dump() will fail to serialize it.
  6705. # TODO: Improve the serialization methods and remove this fix.
  6706. filename = str(filename)
  6707. if filename == "":
  6708. self.inform.emit('[WARNING_NOTCL] %s' %
  6709. _("Open TCL script cancelled."))
  6710. else:
  6711. self.on_filenewscript()
  6712. try:
  6713. with open(filename, "r") as opened_script:
  6714. try:
  6715. for line in opened_script:
  6716. proc_line = str(line).strip('\n')
  6717. self.ui.code_editor.append(proc_line)
  6718. except Exception as e:
  6719. log.debug('App.on_fileopenscript() -->%s' % str(e))
  6720. self.inform.emit('[ERROR] %s %s' %
  6721. (_('App.on_fileopenscript() -->'), str(e)))
  6722. return
  6723. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6724. self.handleTextChanged()
  6725. self.ui.show()
  6726. except Exception as e:
  6727. log.debug("App.on_fileopenscript() -> %s" % str(e))
  6728. def on_filerunscript(self, name=None):
  6729. """
  6730. File menu callback for loading and running a TCL script.
  6731. :return: None
  6732. """
  6733. self.report_usage("on_filerunscript")
  6734. App.log.debug("on_file_runscript()")
  6735. if name:
  6736. filename = name
  6737. else:
  6738. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6739. try:
  6740. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6741. directory=self.get_last_folder(), filter=_filter_)
  6742. except TypeError:
  6743. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6744. # The Qt methods above will return a QString which can cause problems later.
  6745. # So far json.dump() will fail to serialize it.
  6746. # TODO: Improve the serialization methods and remove this fix.
  6747. filename = str(filename)
  6748. if filename == "":
  6749. self.inform.emit('[WARNING_NOTCL] %s' %
  6750. _("Run TCL script cancelled."))
  6751. else:
  6752. try:
  6753. with open(filename, "r") as tcl_script:
  6754. cmd_line_shellfile_content = tcl_script.read()
  6755. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  6756. except Exception as e:
  6757. log.debug("App.on_filerunscript() -> %s" % str(e))
  6758. sys.exit(2)
  6759. def on_file_saveproject(self):
  6760. """
  6761. Callback for menu item File->Save Project. Saves the project to
  6762. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6763. if set to None. The project is saved by calling ``self.save_project()``.
  6764. :return: None
  6765. """
  6766. self.report_usage("on_file_saveproject")
  6767. if self.project_filename is None:
  6768. self.on_file_saveprojectas()
  6769. else:
  6770. self.worker_task.emit({'fcn': self.save_project,
  6771. 'params': [self.project_filename]})
  6772. if self.defaults["global_open_style"] is False:
  6773. self.file_opened.emit("project", self.project_filename)
  6774. self.file_saved.emit("project", self.project_filename)
  6775. self.set_ui_title(name=self.project_filename)
  6776. self.should_we_save = False
  6777. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6778. """
  6779. Callback for menu item File->Save Project As... Opens a file
  6780. chooser and saves the project to the given file via
  6781. ``self.save_project()``.
  6782. :param make_copy if to be create a copy of the project; boolean
  6783. :param use_thread: if to be run in a separate thread; boolean
  6784. :param quit_action: if to be followed by quiting the application; boolean
  6785. :return: None
  6786. """
  6787. self.report_usage("on_file_saveprojectas")
  6788. self.date = str(datetime.today()).rpartition('.')[0]
  6789. self.date = ''.join(c for c in self.date if c not in ':-')
  6790. self.date = self.date.replace(' ', '_')
  6791. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  6792. try:
  6793. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6794. caption=_("Save Project As ..."),
  6795. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  6796. filter=filter_)
  6797. except TypeError:
  6798. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  6799. filename = str(filename)
  6800. if filename == '':
  6801. self.inform.emit('[WARNING_NOTCL] %s' %
  6802. _("Save Project cancelled."))
  6803. return
  6804. try:
  6805. f = open(filename, 'r')
  6806. f.close()
  6807. except IOError:
  6808. pass
  6809. if use_thread is True:
  6810. self.worker_task.emit({'fcn': self.save_project,
  6811. 'params': [filename, quit_action]})
  6812. else:
  6813. self.save_project(filename, quit_action)
  6814. # self.save_project(filename)
  6815. if self.defaults["global_open_style"] is False:
  6816. self.file_opened.emit("project", filename)
  6817. self.file_saved.emit("project", filename)
  6818. if not make_copy:
  6819. self.project_filename = filename
  6820. self.set_ui_title(name=self.project_filename)
  6821. self.should_we_save = False
  6822. def export_svg(self, obj_name, filename, scale_factor=0.00):
  6823. """
  6824. Exports a Geometry Object to an SVG file.
  6825. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6826. :param filename: Path to the SVG file to save to.
  6827. :param scale_factor: factor by which to change/scale the thickness of the features
  6828. :return:
  6829. """
  6830. self.report_usage("export_svg()")
  6831. if filename is None:
  6832. filename = self.defaults["global_last_save_folder"]
  6833. self.log.debug("export_svg()")
  6834. try:
  6835. obj = self.collection.get_by_name(str(obj_name))
  6836. except:
  6837. # TODO: The return behavior has not been established... should raise exception?
  6838. return "Could not retrieve object: %s" % obj_name
  6839. with self.proc_container.new(_("Exporting SVG")) as proc:
  6840. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6841. # Determine bounding area for svg export
  6842. bounds = obj.bounds()
  6843. size = obj.size()
  6844. # Convert everything to strings for use in the xml doc
  6845. svgwidth = str(size[0])
  6846. svgheight = str(size[1])
  6847. minx = str(bounds[0])
  6848. miny = str(bounds[1] - size[1])
  6849. uom = obj.units.lower()
  6850. # Add a SVG Header and footer to the svg output from shapely
  6851. # The transform flips the Y Axis so that everything renders
  6852. # properly within svg apps such as inkscape
  6853. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6854. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6855. svg_header += 'width="' + svgwidth + uom + '" '
  6856. svg_header += 'height="' + svgheight + uom + '" '
  6857. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6858. svg_header += '<g transform="scale(1,-1)">'
  6859. svg_footer = '</g> </svg>'
  6860. svg_elem = svg_header + exported_svg + svg_footer
  6861. # Parse the xml through a xml parser just to add line feeds
  6862. # and to make it look more pretty for the output
  6863. svgcode = parse_xml_string(svg_elem)
  6864. try:
  6865. with open(filename, 'w') as fp:
  6866. fp.write(svgcode.toprettyxml())
  6867. except PermissionError:
  6868. self.inform.emit('[WARNING] %s' %
  6869. _("Permission denied, saving not possible.\n"
  6870. "Most likely another app is holding the file open and not accessible."))
  6871. return 'fail'
  6872. if self.defaults["global_open_style"] is False:
  6873. self.file_opened.emit("SVG", filename)
  6874. self.file_saved.emit("SVG", filename)
  6875. self.inform.emit('[success] %s: %s' %
  6876. (_("SVG file exported to"), filename))
  6877. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  6878. """
  6879. Exports a Geometry Object to an SVG file in negative.
  6880. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6881. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6882. :param filename: Path to the SVG file to save to.
  6883. :param boundary: thickness of a black border to surround all the features
  6884. :param scale_factor: factor by which to change/scale the thickness of the features
  6885. :param use_thread: if to be run in a separate thread; boolean
  6886. :return:
  6887. """
  6888. self.report_usage("export_negative()")
  6889. if filename is None:
  6890. filename = self.defaults["global_last_save_folder"]
  6891. self.log.debug("export_svg() negative")
  6892. try:
  6893. obj = self.collection.get_by_name(str(obj_name))
  6894. except:
  6895. # TODO: The return behavior has not been established... should raise exception?
  6896. return "Could not retrieve object: %s" % obj_name
  6897. try:
  6898. box = self.collection.get_by_name(str(box_name))
  6899. except:
  6900. # TODO: The return behavior has not been established... should raise exception?
  6901. return "Could not retrieve object: %s" % box_name
  6902. if box is None:
  6903. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  6904. (_("No object Box. Using instead"), obj))
  6905. box = obj
  6906. def make_negative_film():
  6907. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6908. self.progress.emit(40)
  6909. # Determine bounding area for svg export
  6910. bounds = box.bounds()
  6911. size = box.size()
  6912. uom = obj.units.lower()
  6913. # Convert everything to strings for use in the xml doc
  6914. svgwidth = str(size[0] + (2 * boundary))
  6915. svgheight = str(size[1] + (2 * boundary))
  6916. minx = str(bounds[0] - boundary)
  6917. miny = str(bounds[1] + boundary + size[1])
  6918. miny_rect = str(bounds[1] - boundary)
  6919. # Add a SVG Header and footer to the svg output from shapely
  6920. # The transform flips the Y Axis so that everything renders
  6921. # properly within svg apps such as inkscape
  6922. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6923. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6924. svg_header += 'width="' + svgwidth + uom + '" '
  6925. svg_header += 'height="' + svgheight + uom + '" '
  6926. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6927. svg_header += '>'
  6928. svg_header += '<g transform="scale(1,-1)">'
  6929. svg_footer = '</g> </svg>'
  6930. self.progress.emit(60)
  6931. # Change the attributes of the exported SVG
  6932. # We don't need stroke-width - wrong, we do when we have lines with certain width
  6933. # We set opacity to maximum
  6934. # We set the color to WHITE
  6935. root = ET.fromstring(exported_svg)
  6936. for child in root:
  6937. child.set('fill', '#FFFFFF')
  6938. child.set('opacity', '1.0')
  6939. child.set('stroke', '#FFFFFF')
  6940. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  6941. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  6942. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  6943. first_svg_elem_tag = 'rect'
  6944. first_svg_elem_attribs = {
  6945. 'x': minx,
  6946. 'y': miny_rect,
  6947. 'width': svgwidth,
  6948. 'height': svgheight,
  6949. 'id': 'neg_rect',
  6950. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  6951. }
  6952. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  6953. exported_svg = ET.tostring(root)
  6954. svg_elem = svg_header + str(exported_svg) + svg_footer
  6955. self.progress.emit(80)
  6956. # Parse the xml through a xml parser just to add line feeds
  6957. # and to make it look more pretty for the output
  6958. doc = parse_xml_string(svg_elem)
  6959. try:
  6960. with open(filename, 'w') as fp:
  6961. fp.write(doc.toprettyxml())
  6962. except PermissionError:
  6963. self.inform.emit('[WARNING] %s' %
  6964. _("Permission denied, saving not possible.\n"
  6965. "Most likely another app is holding the file open and not accessible."))
  6966. return 'fail'
  6967. self.progress.emit(100)
  6968. if self.defaults["global_open_style"] is False:
  6969. self.file_opened.emit("SVG", filename)
  6970. self.file_saved.emit("SVG", filename)
  6971. self.inform.emit('[success] %s: %s' %
  6972. (_("SVG file exported to"), filename))
  6973. if use_thread is True:
  6974. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6975. def job_thread_film(app_obj):
  6976. try:
  6977. make_negative_film()
  6978. except Exception as e:
  6979. proc.done()
  6980. return
  6981. proc.done()
  6982. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6983. else:
  6984. make_negative_film()
  6985. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  6986. """
  6987. Exports a Geometry Object to an SVG file in positive black.
  6988. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6989. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6990. :param filename: Path to the SVG file to save to.
  6991. :param scale_factor: factor by which to change/scale the thickness of the features
  6992. :param use_thread: if to be run in a separate thread; boolean
  6993. :return:
  6994. """
  6995. self.report_usage("export_svg_black()")
  6996. if filename is None:
  6997. filename = self.defaults["global_last_save_folder"]
  6998. self.log.debug("export_svg() black")
  6999. try:
  7000. obj = self.collection.get_by_name(str(obj_name))
  7001. except:
  7002. # TODO: The return behavior has not been established... should raise exception?
  7003. return "Could not retrieve object: %s" % obj_name
  7004. try:
  7005. box = self.collection.get_by_name(str(box_name))
  7006. except:
  7007. # TODO: The return behavior has not been established... should raise exception?
  7008. return "Could not retrieve object: %s" % box_name
  7009. if box is None:
  7010. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7011. (_("No object Box. Using instead"), obj))
  7012. box = obj
  7013. def make_black_film():
  7014. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7015. self.progress.emit(40)
  7016. # Change the attributes of the exported SVG
  7017. # We don't need stroke-width
  7018. # We set opacity to maximum
  7019. # We set the colour to WHITE
  7020. root = ET.fromstring(exported_svg)
  7021. for child in root:
  7022. child.set('fill', '#000000')
  7023. child.set('opacity', '1.0')
  7024. child.set('stroke', '#000000')
  7025. exported_svg = ET.tostring(root)
  7026. # Determine bounding area for svg export
  7027. bounds = box.bounds()
  7028. size = box.size()
  7029. # This contain the measure units
  7030. uom = obj.units.lower()
  7031. # Define a boundary around SVG of about 1.0mm (~39mils)
  7032. if uom in "mm":
  7033. boundary = 1.0
  7034. else:
  7035. boundary = 0.0393701
  7036. self.progress.emit(80)
  7037. # Convert everything to strings for use in the xml doc
  7038. svgwidth = str(size[0] + (2 * boundary))
  7039. svgheight = str(size[1] + (2 * boundary))
  7040. minx = str(bounds[0] - boundary)
  7041. miny = str(bounds[1] + boundary + size[1])
  7042. self.log.debug(minx)
  7043. self.log.debug(miny)
  7044. # Add a SVG Header and footer to the svg output from shapely
  7045. # The transform flips the Y Axis so that everything renders
  7046. # properly within svg apps such as inkscape
  7047. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7048. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7049. svg_header += 'width="' + svgwidth + uom + '" '
  7050. svg_header += 'height="' + svgheight + uom + '" '
  7051. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7052. svg_header += '>'
  7053. svg_header += '<g transform="scale(1,-1)">'
  7054. svg_footer = '</g> </svg>'
  7055. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7056. self.progress.emit(90)
  7057. # Parse the xml through a xml parser just to add line feeds
  7058. # and to make it look more pretty for the output
  7059. doc = parse_xml_string(svg_elem)
  7060. try:
  7061. with open(filename, 'w') as fp:
  7062. fp.write(doc.toprettyxml())
  7063. except PermissionError:
  7064. self.inform.emit('[WARNING] %s' %
  7065. _("Permission denied, saving not possible.\n"
  7066. "Most likely another app is holding the file open and not accessible."))
  7067. return 'fail'
  7068. self.progress.emit(100)
  7069. if self.defaults["global_open_style"] is False:
  7070. self.file_opened.emit("SVG", filename)
  7071. self.file_saved.emit("SVG", filename)
  7072. self.inform.emit('[success] %s: %s' %
  7073. (_("SVG file exported to"), filename))
  7074. if use_thread is True:
  7075. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7076. def job_thread_film(app_obj):
  7077. try:
  7078. make_black_film()
  7079. except Exception as e:
  7080. proc.done()
  7081. return
  7082. proc.done()
  7083. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7084. else:
  7085. make_black_film()
  7086. def save_source_file(self, obj_name, filename, use_thread=True):
  7087. """
  7088. Exports a FlatCAM Object to an Gerber/Excellon file.
  7089. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7090. :param filename: Path to the Gerber file to save to.
  7091. :param use_thread: if to be run in a separate thread
  7092. :return:
  7093. """
  7094. self.report_usage("save source file()")
  7095. if filename is None:
  7096. filename = self.defaults["global_last_save_folder"]
  7097. self.log.debug("save source file()")
  7098. obj = self.collection.get_by_name(obj_name)
  7099. file_string = StringIO(obj.source_file)
  7100. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7101. try:
  7102. with open(filename, 'w') as file:
  7103. file.writelines('G04*\n')
  7104. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7105. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7106. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7107. file.writelines('G04 Created on : %s*\n' % time_string)
  7108. for line in file_string:
  7109. file.writelines(line)
  7110. except PermissionError:
  7111. self.inform.emit('[WARNING] %s' %
  7112. _("Permission denied, saving not possible.\n"
  7113. "Most likely another app is holding the file open and not accessible."))
  7114. return 'fail'
  7115. def export_excellon(self, obj_name, filename, use_thread=True):
  7116. """
  7117. Exports a Excellon Object to an Excellon file.
  7118. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7119. :param filename: Path to the Excellon file to save to.
  7120. :param use_thread: if to be run in a separate thread
  7121. :return:
  7122. """
  7123. self.report_usage("export_excellon()")
  7124. if filename is None:
  7125. filename = self.defaults["global_last_save_folder"]
  7126. self.log.debug("export_excellon()")
  7127. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7128. self.defaults["excellon_exp_decimals"]
  7129. )
  7130. units = ''
  7131. try:
  7132. obj = self.collection.get_by_name(str(obj_name))
  7133. except:
  7134. # TODO: The return behavior has not been established... should raise exception?
  7135. return "Could not retrieve object: %s" % obj_name
  7136. # updated units
  7137. eunits = self.defaults["excellon_exp_units"]
  7138. ewhole = self.defaults["excellon_exp_integer"]
  7139. efract = self.defaults["excellon_exp_decimals"]
  7140. ezeros = self.defaults["excellon_exp_zeros"]
  7141. eformat = self.defaults["excellon_exp_format"]
  7142. slot_type = self.defaults["excellon_exp_slot_type"]
  7143. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7144. if fc_units == 'MM':
  7145. factor = 1 if eunits == 'METRIC' else 0.03937
  7146. else:
  7147. factor = 25.4 if eunits == 'METRIC' else 1
  7148. def make_excellon():
  7149. try:
  7150. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7151. header = 'M48\n'
  7152. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7153. (str(self.version), str(self.version_date))
  7154. header += ';Filename: %s' % str(obj_name) + '\n'
  7155. header += ';Created on : %s' % time_str + '\n'
  7156. if eformat == 'dec':
  7157. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7158. header += eunits + '\n'
  7159. for tool in obj.tools:
  7160. if eunits == 'METRIC':
  7161. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7162. tool=str(tool),
  7163. dec=2)
  7164. else:
  7165. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7166. tool=str(tool),
  7167. dec=4)
  7168. else:
  7169. if ezeros == 'LZ':
  7170. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7171. form='ndec', e_zeros='LZ', factor=factor,
  7172. slot_type=slot_type)
  7173. header += '%s,%s\n' % (eunits, 'LZ')
  7174. header += format_exc
  7175. for tool in obj.tools:
  7176. if eunits == 'METRIC':
  7177. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7178. tool=str(tool),
  7179. dec=2)
  7180. else:
  7181. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7182. tool=str(tool),
  7183. dec=4)
  7184. else:
  7185. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7186. form='ndec', e_zeros='TZ', factor=factor,
  7187. slot_type=slot_type)
  7188. header += '%s,%s\n' % (eunits, 'TZ')
  7189. header += format_exc
  7190. for tool in obj.tools:
  7191. if eunits == 'METRIC':
  7192. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7193. tool=str(tool),
  7194. dec=2)
  7195. else:
  7196. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7197. tool=str(tool),
  7198. dec=4)
  7199. header += '%\n'
  7200. footer = 'M30\n'
  7201. exported_excellon = header
  7202. exported_excellon += excellon_code
  7203. exported_excellon += footer
  7204. try:
  7205. with open(filename, 'w') as fp:
  7206. fp.write(exported_excellon)
  7207. except PermissionError:
  7208. self.inform.emit('[WARNING] %s' %
  7209. _("Permission denied, saving not possible.\n"
  7210. "Most likely another app is holding the file open and not accessible."))
  7211. return 'fail'
  7212. if self.defaults["global_open_style"] is False:
  7213. self.file_opened.emit("Excellon", filename)
  7214. self.file_saved.emit("Excellon", filename)
  7215. self.inform.emit('[success] %s: %s' %
  7216. (_("Excellon file exported to"), filename))
  7217. except Exception as e:
  7218. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7219. return 'fail'
  7220. if use_thread is True:
  7221. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7222. def job_thread_exc(app_obj):
  7223. ret = make_excellon()
  7224. if ret == 'fail':
  7225. self.inform.emit('[ERROR_NOTCL] %s' %
  7226. _('Could not export Excellon file.'))
  7227. return
  7228. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7229. else:
  7230. ret = make_excellon()
  7231. if ret == 'fail':
  7232. self.inform.emit('[ERROR_NOTCL] %s' %
  7233. _('Could not export Excellon file.'))
  7234. return
  7235. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7236. """
  7237. Exports a Gerber Object to an Gerber file.
  7238. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7239. :param filename: Path to the Gerber file to save to.
  7240. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7241. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7242. :param use_thread: if to be run in a separate thread
  7243. :return:
  7244. """
  7245. self.report_usage("export_gerber()")
  7246. if filename is None:
  7247. filename = self.defaults["global_last_save_folder"]
  7248. self.log.debug("export_gerber()")
  7249. if local_use is None:
  7250. try:
  7251. obj = self.collection.get_by_name(str(obj_name))
  7252. except:
  7253. # TODO: The return behavior has not been established... should raise exception?
  7254. return "Could not retrieve object: %s" % obj_name
  7255. else:
  7256. obj = local_use
  7257. # updated units
  7258. gunits = self.defaults["gerber_exp_units"]
  7259. gwhole = self.defaults["gerber_exp_integer"]
  7260. gfract = self.defaults["gerber_exp_decimals"]
  7261. gzeros = self.defaults["gerber_exp_zeros"]
  7262. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7263. if fc_units == 'MM':
  7264. factor = 1 if gunits == 'MM' else 0.03937
  7265. else:
  7266. factor = 25.4 if gunits == 'MM' else 1
  7267. def make_gerber():
  7268. try:
  7269. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7270. header = 'G04*\n'
  7271. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7272. (str(self.version), str(self.version_date))
  7273. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7274. header += 'G04 Created on : %s*' % time_str + '\n'
  7275. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7276. header += "%MO{units}*%\n".format(units=gunits)
  7277. for apid in obj.apertures:
  7278. if obj.apertures[apid]['type'] == 'C':
  7279. header += "%ADD{apid}{type},{size}*%\n".format(
  7280. apid=str(apid),
  7281. type='C',
  7282. size=(factor * obj.apertures[apid]['size'])
  7283. )
  7284. elif obj.apertures[apid]['type'] == 'R':
  7285. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7286. apid=str(apid),
  7287. type='R',
  7288. width=(factor * obj.apertures[apid]['width']),
  7289. height=(factor * obj.apertures[apid]['height'])
  7290. )
  7291. elif obj.apertures[apid]['type'] == 'O':
  7292. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7293. apid=str(apid),
  7294. type='O',
  7295. width=(factor * obj.apertures[apid]['width']),
  7296. height=(factor * obj.apertures[apid]['height'])
  7297. )
  7298. header += '\n'
  7299. # obsolete units but some software may need it
  7300. if gunits == 'IN':
  7301. header += 'G70*\n'
  7302. else:
  7303. header += 'G71*\n'
  7304. # Absolute Mode
  7305. header += 'G90*\n'
  7306. header += 'G01*\n'
  7307. # positive polarity
  7308. header += '%LPD*%\n'
  7309. footer = 'M02*\n'
  7310. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7311. exported_gerber = header
  7312. exported_gerber += gerber_code
  7313. exported_gerber += footer
  7314. if local_use is None:
  7315. try:
  7316. with open(filename, 'w') as fp:
  7317. fp.write(exported_gerber)
  7318. except PermissionError:
  7319. self.inform.emit('[WARNING] %s' %
  7320. _("Permission denied, saving not possible.\n"
  7321. "Most likely another app is holding the file open and not accessible."))
  7322. return 'fail'
  7323. if self.defaults["global_open_style"] is False:
  7324. self.file_opened.emit("Gerber", filename)
  7325. self.file_saved.emit("Gerber", filename)
  7326. self.inform.emit('[success] %s: %s' %
  7327. (_("Gerber file exported to"), filename))
  7328. else:
  7329. return exported_gerber
  7330. except Exception as e:
  7331. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7332. return 'fail'
  7333. if use_thread is True:
  7334. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7335. def job_thread_grb(app_obj):
  7336. ret = make_gerber()
  7337. if ret == 'fail':
  7338. self.inform.emit('[ERROR_NOTCL] %s' %
  7339. _('Could not export Gerber file.'))
  7340. return
  7341. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7342. else:
  7343. ret = make_gerber()
  7344. if ret == 'fail':
  7345. self.inform.emit('[ERROR_NOTCL] %s' %
  7346. _('Could not export Gerber file.'))
  7347. return 'fail'
  7348. if local_use is not None:
  7349. return ret
  7350. def export_dxf(self, obj_name, filename, use_thread=True):
  7351. """
  7352. Exports a Geometry Object to an DXF file.
  7353. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7354. :param filename: Path to the DXF file to save to.
  7355. :param use_thread: if to be run in a separate thread
  7356. :return:
  7357. """
  7358. self.report_usage("export_dxf()")
  7359. if filename is None:
  7360. filename = self.defaults["global_last_save_folder"]
  7361. self.log.debug("export_dxf()")
  7362. format_exc = ''
  7363. units = ''
  7364. try:
  7365. obj = self.collection.get_by_name(str(obj_name))
  7366. except:
  7367. # TODO: The return behavior has not been established... should raise exception?
  7368. return "Could not retrieve object: %s" % obj_name
  7369. # updated units
  7370. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7371. if units == 'IN' or units == 'INCH':
  7372. units = 'INCH'
  7373. elif units == 'MM' or units == 'METIRC':
  7374. units ='METRIC'
  7375. def make_dxf():
  7376. try:
  7377. dxf_code = obj.export_dxf()
  7378. dxf_code.saveas(filename)
  7379. if self.defaults["global_open_style"] is False:
  7380. self.file_opened.emit("DXF", filename)
  7381. self.file_saved.emit("DXF", filename)
  7382. self.inform.emit('[success] %s: %s' %
  7383. (_("DXF file exported to"), filename))
  7384. except:
  7385. return 'fail'
  7386. if use_thread is True:
  7387. with self.proc_container.new(_("Exporting DXF")) as proc:
  7388. def job_thread_exc(app_obj):
  7389. ret = make_dxf()
  7390. if ret == 'fail':
  7391. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  7392. _('Could not export DXF file.'))
  7393. return
  7394. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7395. else:
  7396. ret = make_dxf()
  7397. if ret == 'fail':
  7398. self.inform.emit('[WARNING_NOTCL] %s' %
  7399. _('Could not export DXF file.'))
  7400. return
  7401. def import_svg(self, filename, geo_type='geometry', outname=None):
  7402. """
  7403. Adds a new Geometry Object to the projects and populates
  7404. it with shapes extracted from the SVG file.
  7405. :param filename: Path to the SVG file.
  7406. :param outname:
  7407. :return:
  7408. """
  7409. self.report_usage("import_svg()")
  7410. obj_type = ""
  7411. if geo_type is None or geo_type == "geometry":
  7412. obj_type = "geometry"
  7413. elif geo_type == "gerber":
  7414. obj_type = geo_type
  7415. else:
  7416. self.inform.emit('[ERROR_NOTCL] %s' %
  7417. _("Not supported type is picked as parameter. "
  7418. "Only Geometry and Gerber are supported"))
  7419. return
  7420. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7421. def obj_init(geo_obj, app_obj):
  7422. geo_obj.import_svg(filename, obj_type, units=units)
  7423. geo_obj.multigeo = False
  7424. with self.proc_container.new(_("Importing SVG")) as proc:
  7425. # Object name
  7426. name = outname or filename.split('/')[-1].split('\\')[-1]
  7427. self.new_object(obj_type, name, obj_init, autoselected=False)
  7428. self.progress.emit(20)
  7429. # Register recent file
  7430. self.file_opened.emit("svg", filename)
  7431. # GUI feedback
  7432. self.inform.emit('[success] %s: %s' %
  7433. (_("Opened"), filename))
  7434. self.progress.emit(100)
  7435. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7436. """
  7437. Adds a new Geometry Object to the projects and populates
  7438. it with shapes extracted from the DXF file.
  7439. :param filename: Path to the DXF file.
  7440. :param outname:
  7441. :type putname: str
  7442. :return:
  7443. """
  7444. self.report_usage("import_dxf()")
  7445. obj_type = ""
  7446. if geo_type is None or geo_type == "geometry":
  7447. obj_type = "geometry"
  7448. elif geo_type == "gerber":
  7449. obj_type = geo_type
  7450. else:
  7451. self.inform.emit('[ERROR_NOTCL] %s' %
  7452. _("Not supported type is picked as parameter. "
  7453. "Only Geometry and Gerber are supported"))
  7454. return
  7455. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7456. def obj_init(geo_obj, app_obj):
  7457. geo_obj.import_dxf(filename, obj_type, units=units)
  7458. geo_obj.multigeo = False
  7459. with self.proc_container.new(_("Importing DXF")) as proc:
  7460. # Object name
  7461. name = outname or filename.split('/')[-1].split('\\')[-1]
  7462. self.new_object(obj_type, name, obj_init, autoselected=False)
  7463. self.progress.emit(20)
  7464. # Register recent file
  7465. self.file_opened.emit("dxf", filename)
  7466. # GUI feedback
  7467. self.inform.emit('[success] %s: %s' %
  7468. (_("Opened"), filename))
  7469. self.progress.emit(100)
  7470. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  7471. """
  7472. Adds a new Geometry Object to the projects and populates
  7473. it with shapes extracted from the SVG file.
  7474. :param filename: Path to the SVG file.
  7475. :param o_type: type of FlatCAM objeect
  7476. :param dpi: dot per inch
  7477. :param mode: black or color
  7478. :param mask: dictate the level of detail
  7479. :param outname: name for the resulting file
  7480. :return:
  7481. """
  7482. self.report_usage("import_image()")
  7483. if o_type is None or o_type == "geometry":
  7484. obj_type = "geometry"
  7485. elif o_type == "gerber":
  7486. obj_type = o_type
  7487. else:
  7488. self.inform.emit('[ERROR_NOTCL] %s' %
  7489. _("Not supported type is picked as parameter. "
  7490. "Only Geometry and Gerber are supported"))
  7491. return
  7492. def obj_init(geo_obj, app_obj):
  7493. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  7494. geo_obj.multigeo = False
  7495. with self.proc_container.new(_("Importing Image")) as proc:
  7496. # Object name
  7497. name = outname or filename.split('/')[-1].split('\\')[-1]
  7498. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  7499. self.new_object(obj_type, name, obj_init)
  7500. self.progress.emit(20)
  7501. # Register recent file
  7502. self.file_opened.emit("image", filename)
  7503. # GUI feedback
  7504. self.inform.emit('[success] %s: %s' %
  7505. (_("Opened"), filename))
  7506. self.progress.emit(100)
  7507. def open_gerber(self, filename, outname=None):
  7508. """
  7509. Opens a Gerber file, parses it and creates a new object for
  7510. it in the program. Thread-safe.
  7511. :param outname: Name of the resulting object. None causes the
  7512. name to be that of the file.
  7513. :param filename: Gerber file filename
  7514. :type filename: str
  7515. :param follow: If true, the parser will not create polygons, just lines
  7516. following the gerber path.
  7517. :type follow: bool
  7518. :return: None
  7519. """
  7520. # How the object should be initialized
  7521. def obj_init(gerber_obj, app_obj):
  7522. assert isinstance(gerber_obj, FlatCAMGerber), \
  7523. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  7524. # Opening the file happens here
  7525. self.progress.emit(30)
  7526. try:
  7527. gerber_obj.parse_file(filename)
  7528. except IOError:
  7529. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7530. (_("Failed to open file"), filename))
  7531. app_obj.progress.emit(0)
  7532. return "fail"
  7533. except ParseError as err:
  7534. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  7535. (_("Failed to parse file"), filename, str(err)))
  7536. app_obj.progress.emit(0)
  7537. self.log.error(str(err))
  7538. return "fail"
  7539. except Exception as e:
  7540. log.debug("App.open_gerber() --> %s" % str(e))
  7541. msg = '[ERROR] %s' % \
  7542. _("An internal error has occurred. See shell.\n")
  7543. msg += traceback.format_exc()
  7544. app_obj.inform.emit(msg)
  7545. return "fail"
  7546. if gerber_obj.is_empty():
  7547. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  7548. # self.collection.set_active(gerber_obj.options["name"])
  7549. # self.collection.delete_active()
  7550. self.inform.emit('[ERROR_NOTCL] %s' %
  7551. _("Object is not Gerber file or empty. Aborting object creation."))
  7552. return "fail"
  7553. # Further parsing
  7554. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  7555. App.log.debug("open_gerber()")
  7556. with self.proc_container.new(_("Opening Gerber")) as proc:
  7557. self.progress.emit(10)
  7558. # Object name
  7559. name = outname or filename.split('/')[-1].split('\\')[-1]
  7560. # # ## Object creation # ##
  7561. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7562. if ret == 'fail':
  7563. self.inform.emit('[ERROR_NOTCL]%s' %
  7564. _(' Open Gerber failed. Probable not a Gerber file.'))
  7565. return
  7566. # Register recent file
  7567. self.file_opened.emit("gerber", filename)
  7568. self.progress.emit(100)
  7569. # GUI feedback
  7570. self.inform.emit('[success] %s: %s' %
  7571. (_("Opened"), filename))
  7572. def open_excellon(self, filename, outname=None):
  7573. """
  7574. Opens an Excellon file, parses it and creates a new object for
  7575. it in the program. Thread-safe.
  7576. :param outname: Name of the resulting object. None causes the
  7577. name to be that of the file.
  7578. :param filename: Excellon file filename
  7579. :type filename: str
  7580. :return: None
  7581. """
  7582. App.log.debug("open_excellon()")
  7583. # How the object should be initialized
  7584. def obj_init(excellon_obj, app_obj):
  7585. # self.progress.emit(20)
  7586. try:
  7587. ret = excellon_obj.parse_file(filename=filename)
  7588. if ret == "fail":
  7589. log.debug("Excellon parsing failed.")
  7590. self.inform.emit('[ERROR_NOTCL] %s' %
  7591. _("This is not Excellon file."))
  7592. return "fail"
  7593. except IOError:
  7594. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7595. (_("Cannot open file"), filename))
  7596. log.debug("Could not open Excellon object.")
  7597. self.progress.emit(0) # TODO: self and app_bjj mixed
  7598. return "fail"
  7599. except:
  7600. msg = '[ERROR_NOTCL] %s' % \
  7601. _("An internal error has occurred. See shell.\n")
  7602. msg += traceback.format_exc()
  7603. app_obj.inform.emit(msg)
  7604. return "fail"
  7605. ret = excellon_obj.create_geometry()
  7606. if ret == 'fail':
  7607. log.debug("Could not create geometry for Excellon object.")
  7608. return "fail"
  7609. for tool in excellon_obj.tools:
  7610. if excellon_obj.tools[tool]['solid_geometry']:
  7611. return
  7612. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7613. (_("No geometry found in file"), filename))
  7614. return "fail"
  7615. with self.proc_container.new(_("Opening Excellon.")):
  7616. # Object name
  7617. name = outname or filename.split('/')[-1].split('\\')[-1]
  7618. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  7619. if ret_val == 'fail':
  7620. self.inform.emit('[ERROR_NOTCL] %s' %
  7621. _('Open Excellon file failed. Probable not an Excellon file.'))
  7622. return
  7623. # Register recent file
  7624. self.file_opened.emit("excellon", filename)
  7625. # GUI feedback
  7626. self.inform.emit('[success] %s: %s' %
  7627. (_("Opened"), filename))
  7628. def open_gcode(self, filename, outname=None):
  7629. """
  7630. Opens a G-gcode file, parses it and creates a new object for
  7631. it in the program. Thread-safe.
  7632. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7633. :param filename: G-code file filename
  7634. :type filename: str
  7635. :return: None
  7636. """
  7637. App.log.debug("open_gcode()")
  7638. # How the object should be initialized
  7639. def obj_init(job_obj, app_obj_):
  7640. """
  7641. :param job_obj: the resulting object
  7642. :type app_obj_: App
  7643. """
  7644. assert isinstance(app_obj_, App), \
  7645. "Initializer expected App, got %s" % type(app_obj_)
  7646. self.progress.emit(10)
  7647. try:
  7648. f = open(filename)
  7649. gcode = f.read()
  7650. f.close()
  7651. except IOError:
  7652. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  7653. (_("Failed to open"), filename))
  7654. self.progress.emit(0)
  7655. return "fail"
  7656. job_obj.gcode = gcode
  7657. self.progress.emit(20)
  7658. ret = job_obj.gcode_parse()
  7659. if ret == "fail":
  7660. self.inform.emit('[ERROR_NOTCL] %s' %
  7661. _("This is not GCODE"))
  7662. return "fail"
  7663. self.progress.emit(60)
  7664. job_obj.create_geometry()
  7665. with self.proc_container.new(_("Opening G-Code.")):
  7666. # Object name
  7667. name = outname or filename.split('/')[-1].split('\\')[-1]
  7668. # New object creation and file processing
  7669. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  7670. if ret == 'fail':
  7671. self.inform.emit('[ERROR_NOTCL] %s' %
  7672. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  7673. "Attempting to create a FlatCAM CNCJob Object from "
  7674. "G-Code file failed during processing"))
  7675. return "fail"
  7676. # Register recent file
  7677. self.file_opened.emit("cncjob", filename)
  7678. # GUI feedback
  7679. self.inform.emit('[success] %s: %s' %
  7680. (_("Opened"), filename))
  7681. self.progress.emit(100)
  7682. def open_config_file(self, filename, run_from_arg=None):
  7683. """
  7684. Loads a config file from the specified file.
  7685. :param filename: Name of the file from which to load.
  7686. :type filename: str
  7687. :return: None
  7688. """
  7689. App.log.debug("Opening config file: " + filename)
  7690. # add the tab if it was closed
  7691. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  7692. # first clear previous text in text editor (if any)
  7693. self.ui.code_editor.clear()
  7694. # Switch plot_area to CNCJob tab
  7695. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7696. try:
  7697. if filename:
  7698. f = QtCore.QFile(filename)
  7699. if f.open(QtCore.QIODevice.ReadOnly):
  7700. stream = QtCore.QTextStream(f)
  7701. gcode_edited = stream.readAll()
  7702. self.ui.code_editor.setPlainText(gcode_edited)
  7703. f.close()
  7704. except IOError:
  7705. App.log.error("Failed to open config file: %s" % filename)
  7706. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7707. (_("Failed to open config file"), filename))
  7708. return
  7709. def open_project(self, filename, run_from_arg=None):
  7710. """
  7711. Loads a project from the specified file.
  7712. 1) Loads and parses file
  7713. 2) Registers the file as recently opened.
  7714. 3) Calls on_file_new()
  7715. 4) Updates options
  7716. 5) Calls new_object() with the object's from_dict() as init method.
  7717. 6) Calls plot_all()
  7718. :param filename: Name of the file from which to load.
  7719. :type filename: str
  7720. :param run_from_arg: True if run for arguments
  7721. :return: None
  7722. """
  7723. App.log.debug("Opening project: " + filename)
  7724. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7725. # Open and parse an uncompressed Project file
  7726. try:
  7727. f = open(filename, 'r')
  7728. except IOError:
  7729. App.log.error("Failed to open project file: %s" % filename)
  7730. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7731. (_("Failed to open project file"), filename))
  7732. return
  7733. try:
  7734. d = json.load(f, object_hook=dict2obj)
  7735. except Exception as e:
  7736. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7737. (filename, str(e)))
  7738. f.close()
  7739. # Open and parse a compressed Project file
  7740. try:
  7741. with lzma.open(filename) as f:
  7742. file_content = f.read().decode('utf-8')
  7743. d = json.loads(file_content, object_hook=dict2obj)
  7744. except Exception as e:
  7745. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7746. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7747. (_("Failed to open project file"), filename))
  7748. return
  7749. # Clear the current project
  7750. # # NOT THREAD SAFE # ##
  7751. if run_from_arg is True:
  7752. pass
  7753. else:
  7754. self.on_file_new()
  7755. # Project options
  7756. self.options.update(d['options'])
  7757. self.project_filename = filename
  7758. self.set_screen_units(self.options["units"])
  7759. # Re create objects
  7760. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7761. for obj in d['objs']:
  7762. def obj_init(obj_inst, app_inst):
  7763. obj_inst.from_dict(obj)
  7764. App.log.debug("Recreating from opened project an %s object: %s" %
  7765. (obj['kind'].capitalize(), obj['options']['name']))
  7766. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7767. obj['kind'].upper(),
  7768. obj['options']['name']
  7769. )
  7770. )
  7771. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  7772. # self.plot_all()
  7773. self.inform.emit('[success] %s: %s' %
  7774. (_("Project loaded from"), filename))
  7775. self.should_we_save = False
  7776. self.file_opened.emit("project", filename)
  7777. self.set_ui_title(name=self.project_filename)
  7778. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7779. def propagate_defaults(self, silent=False):
  7780. """
  7781. This method is used to set default values in classes. It's
  7782. an alternative to project options but allows the use
  7783. of values invisible to the user.
  7784. :return: None
  7785. """
  7786. if silent is False:
  7787. self.log.debug("propagate_defaults()")
  7788. # Which objects to update the given parameters.
  7789. routes = {
  7790. "global_zdownrate": CNCjob,
  7791. "excellon_zeros": Excellon,
  7792. "excellon_format_upper_in": Excellon,
  7793. "excellon_format_lower_in": Excellon,
  7794. "excellon_format_upper_mm": Excellon,
  7795. "excellon_format_lower_mm": Excellon,
  7796. "excellon_units": Excellon,
  7797. "gerber_use_buffer_for_union": Gerber,
  7798. "geometry_multidepth": Geometry
  7799. }
  7800. for param in routes:
  7801. if param in routes[param].defaults:
  7802. try:
  7803. routes[param].defaults[param] = self.defaults[param]
  7804. if silent is False:
  7805. self.log.debug(" " + param + " OK")
  7806. except KeyError:
  7807. if silent is False:
  7808. self.log.debug(" ERROR: " + param + " not in defaults.")
  7809. else:
  7810. # Try extracting the name:
  7811. # classname_param here is param in the object
  7812. if param.find(routes[param].__name__.lower() + "_") == 0:
  7813. p = param[len(routes[param].__name__) + 1:]
  7814. if p in routes[param].defaults:
  7815. routes[param].defaults[p] = self.defaults[param]
  7816. if silent is False:
  7817. self.log.debug(" " + param + " OK!")
  7818. def restore_main_win_geom(self):
  7819. try:
  7820. self.ui.setGeometry(self.defaults["global_def_win_x"],
  7821. self.defaults["global_def_win_y"],
  7822. self.defaults["global_def_win_w"],
  7823. self.defaults["global_def_win_h"])
  7824. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  7825. settings = QSettings("Open Source", "FlatCAM")
  7826. if settings.contains("maximized_gui"):
  7827. maximized_ui = settings.value('maximized_gui', type=bool)
  7828. if maximized_ui is True:
  7829. self.ui.showMaximized()
  7830. except KeyError as e:
  7831. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  7832. def plot_all(self, zoom=True):
  7833. """
  7834. Re-generates all plots from all objects.
  7835. :return: None
  7836. """
  7837. self.log.debug("Plot_all()")
  7838. for obj in self.collection.get_list():
  7839. def worker_task(obj):
  7840. with self.proc_container.new("Plotting"):
  7841. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7842. if zoom:
  7843. self.object_plotted.emit(obj)
  7844. # Send to worker
  7845. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  7846. def register_folder(self, filename):
  7847. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7848. def register_save_folder(self, filename):
  7849. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7850. def set_progress_bar(self, percentage, text=""):
  7851. self.ui.progress_bar.setValue(int(percentage))
  7852. def setup_shell(self):
  7853. """
  7854. Creates shell functions. Runs once at startup.
  7855. :return: None
  7856. """
  7857. self.log.debug("setup_shell()")
  7858. def shelp(p=None):
  7859. if not p:
  7860. return _("Available commands:\n") + \
  7861. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  7862. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  7863. if p not in commands:
  7864. return "Unknown command: %s" % p
  7865. return commands[p]["help"]
  7866. # --- Migrated to new architecture ---
  7867. # def options(name):
  7868. # ops = self.collection.get_by_name(str(name)).options
  7869. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  7870. def h(*args):
  7871. """
  7872. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  7873. and standalone parameters into list.
  7874. """
  7875. kwa = {}
  7876. a = []
  7877. n = len(args)
  7878. name = None
  7879. for i in range(n):
  7880. match = re.search(r'^-([a-zA-Z].*)', args[i])
  7881. if match:
  7882. assert name is None
  7883. name = match.group(1)
  7884. continue
  7885. if name is None:
  7886. a.append(args[i])
  7887. else:
  7888. kwa[name] = args[i]
  7889. name = None
  7890. return a, kwa
  7891. @contextmanager
  7892. def wait_signal(signal, timeout=10000):
  7893. """
  7894. Block loop until signal emitted, timeout (ms) elapses
  7895. or unhandled exception happens in a thread.
  7896. :param timeout: time after which the loop is exited
  7897. :param signal: Signal to wait for.
  7898. """
  7899. loop = QtCore.QEventLoop()
  7900. # Normal termination
  7901. signal.connect(loop.quit)
  7902. # Termination by exception in thread
  7903. self.thread_exception.connect(loop.quit)
  7904. status = {'timed_out': False}
  7905. def report_quit():
  7906. status['timed_out'] = True
  7907. loop.quit()
  7908. yield
  7909. # Temporarily change how exceptions are managed.
  7910. oeh = sys.excepthook
  7911. ex = []
  7912. def except_hook(type_, value, traceback_):
  7913. ex.append(value)
  7914. oeh(type_, value, traceback_)
  7915. sys.excepthook = except_hook
  7916. # Terminate on timeout
  7917. if timeout is not None:
  7918. QtCore.QTimer.singleShot(timeout, report_quit)
  7919. # # ## Block ## ##
  7920. loop.exec_()
  7921. # Restore exception management
  7922. sys.excepthook = oeh
  7923. if ex:
  7924. self.raiseTclError(str(ex[0]))
  7925. if status['timed_out']:
  7926. raise Exception('Timed out!')
  7927. def make_docs():
  7928. output = ''
  7929. import collections
  7930. od = collections.OrderedDict(sorted(commands.items()))
  7931. for cmd_, val in od.items():
  7932. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  7933. t = val['help']
  7934. usage_i = t.find('>')
  7935. if usage_i < 0:
  7936. expl = t
  7937. output += expl + '\n\n'
  7938. continue
  7939. expl = t[:usage_i - 1]
  7940. output += expl + '\n\n'
  7941. end_usage_i = t[usage_i:].find('\n')
  7942. if end_usage_i < 0:
  7943. end_usage_i = len(t[usage_i:])
  7944. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  7945. else:
  7946. extras = t[usage_i+end_usage_i+1:]
  7947. parts = [s.strip() for s in extras.split('\n')]
  7948. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  7949. for p in parts:
  7950. output += ' ' + p + '\n\n'
  7951. return output
  7952. '''
  7953. Howto implement TCL shell commands:
  7954. All parameters passed to command should be possible to set as None and test it afterwards.
  7955. This is because we need to see error caused in tcl,
  7956. if None value as default parameter is not allowed TCL will return empty error.
  7957. Use:
  7958. def mycommand(name=None,...):
  7959. Test it like this:
  7960. if name is None:
  7961. self.raise_tcl_error('Argument name is missing.')
  7962. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  7963. otherwise we will miss it and processing will silently continue.
  7964. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  7965. which is catched in exec_command and displayed in TCL shell console with red background.
  7966. Error in console is displayed with TCL trace.
  7967. This behavior works only within main thread,
  7968. errors with promissed tasks can be catched and detected only with log.
  7969. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  7970. TCL shell.
  7971. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  7972. '''
  7973. commands = {
  7974. 'help': {
  7975. 'fcn': shelp,
  7976. 'help': _("Shows list of commands.")
  7977. },
  7978. }
  7979. # Import/overwrite tcl commands as objects of TclCommand descendants
  7980. # This modifies the variable 'commands'.
  7981. tclCommands.register_all_commands(self, commands)
  7982. # Add commands to the tcl interpreter
  7983. for cmd in commands:
  7984. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  7985. # Make the tcl puts function return instead of print to stdout
  7986. self.tcl.eval('''
  7987. rename puts original_puts
  7988. proc puts {args} {
  7989. if {[llength $args] == 1} {
  7990. return "[lindex $args 0]"
  7991. } else {
  7992. eval original_puts $args
  7993. }
  7994. }
  7995. ''')
  7996. def setup_recent_items(self):
  7997. # TODO: Move this to constructor
  7998. icons = {
  7999. "gerber": "share/flatcam_icon16.png",
  8000. "excellon": "share/drill16.png",
  8001. 'geometry': "share/geometry16.png",
  8002. "cncjob": "share/cnc16.png",
  8003. "project": "share/project16.png",
  8004. "svg": "share/geometry16.png",
  8005. "dxf": "share/dxf16.png",
  8006. "pdf": "share/pdf32.png",
  8007. "image": "share/image16.png"
  8008. }
  8009. openers = {
  8010. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8011. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8012. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8013. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8014. 'project': self.open_project,
  8015. 'svg': self.import_svg,
  8016. 'dxf': self.import_dxf,
  8017. 'image': self.import_image,
  8018. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8019. }
  8020. # Open recent file for files
  8021. try:
  8022. f = open(self.data_path + '/recent.json')
  8023. except IOError:
  8024. App.log.error("Failed to load recent item list.")
  8025. self.inform.emit('[ERROR_NOTCL] %s' %
  8026. _("Failed to load recent item list."))
  8027. return
  8028. try:
  8029. self.recent = json.load(f)
  8030. except json.scanner.JSONDecodeError:
  8031. App.log.error("Failed to parse recent item list.")
  8032. self.inform.emit('[ERROR_NOTCL] %s' %
  8033. _("Failed to parse recent item list."))
  8034. f.close()
  8035. return
  8036. f.close()
  8037. # Open recent file for projects
  8038. try:
  8039. fp = open(self.data_path + '/recent_projects.json')
  8040. except IOError:
  8041. App.log.error("Failed to load recent project item list.")
  8042. self.inform.emit('[ERROR_NOTCL] %s' %
  8043. _("Failed to load recent projects item list."))
  8044. return
  8045. try:
  8046. self.recent_projects = json.load(fp)
  8047. except json.scanner.JSONDecodeError:
  8048. App.log.error("Failed to parse recent project item list.")
  8049. self.inform.emit('[ERROR_NOTCL] %s' %
  8050. _("Failed to parse recent project item list."))
  8051. fp.close()
  8052. return
  8053. fp.close()
  8054. # Closure needed to create callbacks in a loop.
  8055. # Otherwise late binding occurs.
  8056. def make_callback(func, fname):
  8057. def opener():
  8058. func(fname)
  8059. return opener
  8060. def reset_recent_files():
  8061. # Reset menu
  8062. self.ui.recent.clear()
  8063. self.recent = []
  8064. try:
  8065. f = open(self.data_path + '/recent.json', 'w')
  8066. except IOError:
  8067. App.log.error("Failed to open recent items file for writing.")
  8068. return
  8069. json.dump(self.recent, f)
  8070. def reset_recent_projects():
  8071. # Reset menu
  8072. self.ui.recent_projects.clear()
  8073. self.recent_projects = []
  8074. try:
  8075. fp = open(self.data_path + '/recent_projects.json', 'w')
  8076. except IOError:
  8077. App.log.error("Failed to open recent projects items file for writing.")
  8078. return
  8079. json.dump(self.recent, fp)
  8080. # Reset menu
  8081. self.ui.recent.clear()
  8082. self.ui.recent_projects.clear()
  8083. # Create menu items for projects
  8084. for recent in self.recent_projects:
  8085. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8086. if recent['kind'] == 'project':
  8087. try:
  8088. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8089. # Attach callback
  8090. o = make_callback(openers[recent["kind"]], recent['filename'])
  8091. action.triggered.connect(o)
  8092. self.ui.recent_projects.addAction(action)
  8093. except KeyError:
  8094. App.log.error("Unsupported file type: %s" % recent["kind"])
  8095. # Last action in Recent Files menu is one that Clear the content
  8096. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8097. clear_action_proj.triggered.connect(reset_recent_projects)
  8098. self.ui.recent_projects.addSeparator()
  8099. self.ui.recent_projects.addAction(clear_action_proj)
  8100. # Create menu items for files
  8101. for recent in self.recent:
  8102. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8103. if recent['kind'] != 'project':
  8104. try:
  8105. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8106. # Attach callback
  8107. o = make_callback(openers[recent["kind"]], recent['filename'])
  8108. action.triggered.connect(o)
  8109. self.ui.recent.addAction(action)
  8110. except KeyError:
  8111. App.log.error("Unsupported file type: %s" % recent["kind"])
  8112. # Last action in Recent Files menu is one that Clear the content
  8113. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8114. clear_action.triggered.connect(reset_recent_files)
  8115. self.ui.recent.addSeparator()
  8116. self.ui.recent.addAction(clear_action)
  8117. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8118. # self.ui.menufilerecent.set_submenu(recent_menu)
  8119. # recent_menu.show_all()
  8120. # self.ui.recent.show()
  8121. self.log.debug("Recent items list has been populated.")
  8122. def setup_component_editor(self):
  8123. # label = QtWidgets.QLabel("Choose an item from Project")
  8124. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8125. sel_title = QtWidgets.QTextEdit(
  8126. _('<b>Shortcut Key List</b>'))
  8127. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8128. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8129. settings = QSettings("Open Source", "FlatCAM")
  8130. if settings.contains("notebook_font_size"):
  8131. fsize = settings.value('notebook_font_size', type=int)
  8132. else:
  8133. fsize = 12
  8134. tsize = fsize + int(fsize / 2)
  8135. selected_text = (_('''
  8136. <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8137. <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8138. The normal flow when working in FlatCAM is the following:</span></p>
  8139. <ol>
  8140. <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 />
  8141. <br />
  8142. 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 />
  8143. &nbsp;</li>
  8144. <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 />
  8145. <br />
  8146. 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 />
  8147. <br />
  8148. You can change the parameters in this screen and the flow direction is like this:<br />
  8149. <br />
  8150. <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>
  8151. </ol>
  8152. <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>
  8153. ''').format(fsize=fsize, tsize=tsize))
  8154. sel_title.setText(selected_text)
  8155. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8156. self.ui.selected_scroll_area.setWidget(sel_title)
  8157. def setup_obj_classes(self):
  8158. """
  8159. Sets up application specifics on the FlatCAMObj class.
  8160. :return: None
  8161. """
  8162. FlatCAMObj.app = self
  8163. ObjectCollection.app = self
  8164. Gerber.app = self
  8165. Excellon.app = self
  8166. Geometry.app = self
  8167. CNCjob.app = self
  8168. FCProcess.app = self
  8169. FCProcessContainer.app = self
  8170. def version_check(self):
  8171. """
  8172. Checks for the latest version of the program. Alerts the
  8173. user if theirs is outdated. This method is meant to be run
  8174. in a separate thread.
  8175. :return: None
  8176. """
  8177. self.log.debug("version_check()")
  8178. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8179. full_url = App.version_url + \
  8180. "?s=" + str(self.defaults['global_serial']) + \
  8181. "&v=" + str(self.version) + \
  8182. "&os=" + str(self.os) + \
  8183. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8184. else:
  8185. # no_stats dict; just so it won't break things on website
  8186. no_ststs_dict = {}
  8187. no_ststs_dict["global_ststs"] = {}
  8188. full_url = App.version_url + \
  8189. "?s=" + str(self.defaults['global_serial']) + \
  8190. "&v=" + str(self.version) + \
  8191. "&os=" + str(self.os) + \
  8192. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8193. App.log.debug("Checking for updates @ %s" % full_url)
  8194. # ## Get the data
  8195. try:
  8196. f = urllib.request.urlopen(full_url)
  8197. except:
  8198. # App.log.warning("Failed checking for latest version. Could not connect.")
  8199. self.log.warning("Failed checking for latest version. Could not connect.")
  8200. self.inform.emit('[WARNING_NOTCL] %s' %
  8201. _("Failed checking for latest version. Could not connect."))
  8202. return
  8203. try:
  8204. data = json.load(f)
  8205. except Exception as e:
  8206. App.log.error("Could not parse information about latest version.")
  8207. self.inform.emit('[ERROR_NOTCL] %s' %
  8208. _("Could not parse information about latest version."))
  8209. App.log.debug("json.load(): %s" % str(e))
  8210. f.close()
  8211. return
  8212. f.close()
  8213. # ## Latest version?
  8214. if self.version >= data["version"]:
  8215. App.log.debug("FlatCAM is up to date!")
  8216. self.inform.emit('[success] %s' %
  8217. _("FlatCAM is up to date!"))
  8218. return
  8219. App.log.debug("Newer version available.")
  8220. self.message.emit(
  8221. _("Newer Version Available"),
  8222. _("There is a newer version of FlatCAM available for download:\n\n") +
  8223. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  8224. _("info")
  8225. )
  8226. def on_plotcanvas_setup(self, container=None):
  8227. """
  8228. This is doing the setup for the plot area (VisPy canvas)
  8229. :param container: widget where to install the canvas
  8230. :return: None
  8231. """
  8232. if container:
  8233. plot_container = container
  8234. else:
  8235. plot_container = self.ui.right_layout
  8236. self.plotcanvas = PlotCanvas(plot_container, self)
  8237. # So it can receive key presses
  8238. self.plotcanvas.native.setFocus()
  8239. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  8240. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  8241. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8242. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  8243. # Keys over plot enabled
  8244. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  8245. self.app_cursor = self.plotcanvas.new_cursor()
  8246. self.app_cursor.enabled = False
  8247. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8248. def on_zoom_fit(self, event):
  8249. """
  8250. Callback for zoom-out request. This can be either from the corresponding
  8251. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8252. with axes limits from the geometry bounds of all objects.
  8253. :param event: Ignored.
  8254. :return: None
  8255. """
  8256. self.plotcanvas.fit_view()
  8257. def on_zoom_in(self):
  8258. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8259. def on_zoom_out(self):
  8260. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8261. def disable_all_plots(self):
  8262. self.report_usage("disable_all_plots()")
  8263. self.disable_plots(self.collection.get_list())
  8264. self.inform.emit('[success] %s' %
  8265. _("All plots disabled."))
  8266. def disable_other_plots(self):
  8267. self.report_usage("disable_other_plots()")
  8268. self.disable_plots(self.collection.get_non_selected())
  8269. self.inform.emit('[success] %s' %
  8270. _("All non selected plots disabled."))
  8271. def enable_all_plots(self):
  8272. self.report_usage("enable_all_plots()")
  8273. self.enable_plots(self.collection.get_list())
  8274. self.inform.emit('[success] %s' %
  8275. _("All plots enabled."))
  8276. def on_enable_sel_plots(self):
  8277. log.debug("App.on_enable_sel_plot()")
  8278. object_list = self.collection.get_selected()
  8279. self.enable_plots(objects=object_list)
  8280. self.inform.emit('[success] %s' %
  8281. _("Selected plots enabled..."))
  8282. def on_disable_sel_plots(self):
  8283. log.debug("App.on_disable_sel_plot()")
  8284. # self.inform.emit(_("Disabling plots ..."))
  8285. object_list = self.collection.get_selected()
  8286. self.disable_plots(objects=object_list)
  8287. self.inform.emit('[success] %s' %
  8288. _("Selected plots disabled..."))
  8289. def enable_plots(self, objects):
  8290. """
  8291. Disables plots
  8292. :param objects: list of Objects to be enabled
  8293. :return:
  8294. """
  8295. log.debug("Enabling plots ...")
  8296. # self.inform.emit(_("Working ..."))
  8297. for obj in objects:
  8298. if obj.options['plot'] is False:
  8299. obj.options.set_change_callback(lambda x: None)
  8300. obj.options['plot'] = True
  8301. obj.options.set_change_callback(obj.on_options_change)
  8302. def worker_task(objects):
  8303. with self.proc_container.new(_("Enabling plots ...")):
  8304. for obj in objects:
  8305. # obj.options['plot'] = True
  8306. if isinstance(obj, FlatCAMCNCjob):
  8307. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8308. else:
  8309. obj.plot(visible=True)
  8310. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8311. # self.plots_updated.emit()
  8312. def disable_plots(self, objects):
  8313. """
  8314. Disables plots
  8315. :param objects: list of Objects to be disabled
  8316. :return:
  8317. """
  8318. # if no objects selected then do nothing
  8319. if not self.collection.get_selected():
  8320. return
  8321. log.debug("Disabling plots ...")
  8322. # self.inform.emit(_("Working ..."))
  8323. for obj in objects:
  8324. if obj.options['plot'] is True:
  8325. obj.options.set_change_callback(lambda x: None)
  8326. obj.options['plot'] = False
  8327. obj.options.set_change_callback(obj.on_options_change)
  8328. try:
  8329. self.delete_selection_shape()
  8330. except Exception as e:
  8331. log.debug("App.disable_plots() --> %s" % str(e))
  8332. # self.plots_updated.emit()
  8333. def worker_task(objects):
  8334. with self.proc_container.new(_("Disabling plots ...")):
  8335. for obj in objects:
  8336. # obj.options['plot'] = True
  8337. if isinstance(obj, FlatCAMCNCjob):
  8338. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8339. else:
  8340. obj.plot(visible=False)
  8341. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8342. def toggle_plots(self, objects):
  8343. """
  8344. Toggle plots visibility
  8345. :param objects: list of Objects for which to be toggled the visibility
  8346. :return:
  8347. """
  8348. # if no objects selected then do nothing
  8349. if not self.collection.get_selected():
  8350. return
  8351. log.debug("Toggling plots ...")
  8352. self.inform.emit(_("Working ..."))
  8353. for obj in objects:
  8354. if obj.options['plot'] is False:
  8355. obj.options['plot'] = True
  8356. else:
  8357. obj.options['plot'] = False
  8358. self.plots_updated.emit()
  8359. def clear_plots(self):
  8360. objects = self.collection.get_list()
  8361. for obj in objects:
  8362. obj.clear(obj == objects[-1])
  8363. # Clear pool to free memory
  8364. self.clear_pool()
  8365. def generate_cnc_job(self, objects):
  8366. self.report_usage("generate_cnc_job()")
  8367. # for obj in objects:
  8368. # obj.generatecncjob()
  8369. for obj in objects:
  8370. obj.on_generatecnc_button_click()
  8371. def save_project(self, filename, quit_action=False):
  8372. """
  8373. Saves the current project to the specified file.
  8374. :param filename: Name of the file in which to save.
  8375. :type filename: str
  8376. :param quit_action: if the project saving will be followed by an app quit; boolean
  8377. :return: None
  8378. """
  8379. self.log.debug("save_project()")
  8380. self.save_in_progress = True
  8381. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  8382. # Capture the latest changes
  8383. # Current object
  8384. try:
  8385. self.collection.get_active().read_form()
  8386. except:
  8387. self.log.debug("There was no active object")
  8388. pass
  8389. # Project options
  8390. self.options_read_form()
  8391. # Serialize the whole project
  8392. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8393. "options": self.options,
  8394. "version": self.version}
  8395. if self.defaults["global_save_compressed"] is True:
  8396. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8397. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8398. # # Write
  8399. f.write(g)
  8400. self.inform.emit('[success] %s: %s' %
  8401. (_("Project saved to"), filename))
  8402. else:
  8403. # Open file
  8404. try:
  8405. f = open(filename, 'w')
  8406. except IOError:
  8407. App.log.error("Failed to open file for saving: %s", filename)
  8408. return
  8409. # Write
  8410. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8411. f.close()
  8412. # verification of the saved project
  8413. # Open and parse
  8414. try:
  8415. saved_f = open(filename, 'r')
  8416. except IOError:
  8417. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8418. (_("Failed to verify project file"), filename, _("Retry to save it."))
  8419. )
  8420. return
  8421. try:
  8422. saved_d = json.load(saved_f, object_hook=dict2obj)
  8423. except:
  8424. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8425. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8426. )
  8427. f.close()
  8428. return
  8429. saved_f.close()
  8430. if 'version' in saved_d:
  8431. self.inform.emit('[success] %s: %s' %
  8432. (_("Project saved to"), filename))
  8433. else:
  8434. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8435. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8436. )
  8437. settings = QSettings("Open Source", "FlatCAM")
  8438. lock_state = self.ui.lock_action.isChecked()
  8439. settings.setValue('toolbar_lock', lock_state)
  8440. # This will write the setting to the platform specific storage.
  8441. del settings
  8442. # if quit:
  8443. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8444. # t.start()
  8445. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8446. def start_delayed_quit(self, delay, filename, should_quit=None):
  8447. """
  8448. :param delay: period of checking if project file size is more than zero; in seconds
  8449. :param filename: the name of the project file to be checked periodically for size more than zero
  8450. :param should_quit: if the task finished will be followed by an app quit; boolean
  8451. :return:
  8452. """
  8453. to_quit = should_quit
  8454. self.save_timer = QtCore.QTimer()
  8455. self.save_timer.setInterval(delay)
  8456. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8457. self.save_timer.start()
  8458. def check_project_file_size(self, filename, should_quit=None):
  8459. """
  8460. :param filename: the name of the project file to be checked periodically for size more than zero
  8461. :param should_quit: will quit the app if True; boolean
  8462. :return:
  8463. """
  8464. try:
  8465. if os.stat(filename).st_size > 0:
  8466. self.save_in_progress = False
  8467. self.save_timer.stop()
  8468. if should_quit:
  8469. self.app_quit.emit()
  8470. except Exception as e:
  8471. traceback.print_exc()
  8472. def on_options_app2project(self):
  8473. """
  8474. Callback for Options->Transfer Options->App=>Project. Copies options
  8475. from application defaults to project defaults.
  8476. :return: None
  8477. """
  8478. self.report_usage("on_options_app2project")
  8479. self.defaults_read_form()
  8480. self.options.update(self.defaults)
  8481. self.options_write_form()
  8482. def on_options_project2app(self):
  8483. """
  8484. Callback for Options->Transfer Options->Project=>App. Copies options
  8485. from project defaults to application defaults.
  8486. :return: None
  8487. """
  8488. self.report_usage("on_options_project2app")
  8489. self.options_read_form()
  8490. self.defaults.update(self.options)
  8491. self.defaults_write_form()
  8492. def on_options_project2object(self):
  8493. """
  8494. Callback for Options->Transfer Options->Project=>Object. Copies options
  8495. from project defaults to the currently selected object.
  8496. :return: None
  8497. """
  8498. self.report_usage("on_options_project2object")
  8499. self.options_read_form()
  8500. obj = self.collection.get_active()
  8501. if obj is None:
  8502. self.inform.emit('[WARNING_NOTCL] %s' %
  8503. _("No object selected."))
  8504. return
  8505. for option in self.options:
  8506. if option.find(obj.kind + "_") == 0:
  8507. oname = option[len(obj.kind) + 1:]
  8508. obj.options[oname] = self.options[option]
  8509. obj.to_form() # Update UI
  8510. def on_options_object2project(self):
  8511. """
  8512. Callback for Options->Transfer Options->Object=>Project. Copies options
  8513. from the currently selected object to project defaults.
  8514. :return: None
  8515. """
  8516. self.report_usage("on_options_object2project")
  8517. obj = self.collection.get_active()
  8518. if obj is None:
  8519. self.inform.emit('[WARNING_NOTCL] %s' %
  8520. _("No object selected."))
  8521. return
  8522. obj.read_form()
  8523. for option in obj.options:
  8524. if option in ['name']: # TODO: Handle this better...
  8525. continue
  8526. self.options[obj.kind + "_" + option] = obj.options[option]
  8527. self.options_write_form()
  8528. def on_options_object2app(self):
  8529. """
  8530. Callback for Options->Transfer Options->Object=>App. Copies options
  8531. from the currently selected object to application defaults.
  8532. :return: None
  8533. """
  8534. self.report_usage("on_options_object2app")
  8535. obj = self.collection.get_active()
  8536. if obj is None:
  8537. self.inform.emit('[WARNING_NOTCL] %s' %
  8538. _("No object selected."))
  8539. return
  8540. obj.read_form()
  8541. for option in obj.options:
  8542. if option in ['name']: # TODO: Handle this better...
  8543. continue
  8544. self.defaults[obj.kind + "_" + option] = obj.options[option]
  8545. self.defaults_write_form()
  8546. def on_options_app2object(self):
  8547. """
  8548. Callback for Options->Transfer Options->App=>Object. Copies options
  8549. from application defaults to the currently selected object.
  8550. :return: None
  8551. """
  8552. self.report_usage("on_options_app2object")
  8553. self.defaults_read_form()
  8554. obj = self.collection.get_active()
  8555. if obj is None:
  8556. self.inform.emit('[WARNING_NOTCL] %s' %
  8557. _("No object selected."))
  8558. return
  8559. for option in self.defaults:
  8560. if option.find(obj.kind + "_") == 0:
  8561. oname = option[len(obj.kind) + 1:]
  8562. obj.options[oname] = self.defaults[option]
  8563. obj.to_form() # Update UI
  8564. class ArgsThread(QtCore.QObject):
  8565. open_signal = pyqtSignal(list)
  8566. start = pyqtSignal()
  8567. if sys.platform == 'win32':
  8568. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8569. else:
  8570. address = ('/tmp/testipc', 'AF_UNIX')
  8571. def __init__(self):
  8572. super(ArgsThread, self).__init__()
  8573. self.start.connect(self.run)
  8574. def my_loop(self, address):
  8575. try:
  8576. listener = Listener(*address)
  8577. while True:
  8578. conn = listener.accept()
  8579. self.serve(conn)
  8580. except socket.error as e:
  8581. conn = Client(*address)
  8582. conn.send(sys.argv)
  8583. conn.send('close')
  8584. # close the current instance only if there are args
  8585. if len(sys.argv) > 1:
  8586. sys.exit()
  8587. def serve(self, conn):
  8588. while True:
  8589. msg = conn.recv()
  8590. if msg == 'close':
  8591. break
  8592. self.open_signal.emit(msg)
  8593. conn.close()
  8594. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8595. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8596. @pyqtSlot()
  8597. def run(self):
  8598. self.my_loop(self.address)
  8599. class GracefulException(Exception):
  8600. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  8601. def __init__(self):
  8602. super().__init__()
  8603. def __str__(self):
  8604. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  8605. # end of file