FlatCAMApp.py 354 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079
  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, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. import threading
  14. from stat import S_IREAD, S_IRGRP, S_IROTH
  15. import subprocess
  16. import tkinter as tk
  17. from PyQt5 import QtPrintSupport
  18. import urllib.request, urllib.parse, urllib.error
  19. from contextlib import contextmanager
  20. import gc
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. ########################################
  23. ## Imports part of FlatCAM ##
  24. ########################################
  25. from ObjectCollection import *
  26. from FlatCAMObj import *
  27. from flatcamGUI.PlotCanvas import *
  28. from flatcamGUI.FlatCAMGUI import *
  29. from FlatCAMCommon import LoudDict
  30. from FlatCAMPostProc import load_postprocessors
  31. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  32. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  33. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  34. from FlatCAMProcess import *
  35. from FlatCAMWorkerStack import WorkerStack
  36. from flatcamGUI.VisPyVisuals import Color
  37. from vispy.gloo.util import _screenshot
  38. from vispy.io import write_png
  39. from flatcamTools import *
  40. from multiprocessing import Pool
  41. import tclCommands
  42. import gettext
  43. import FlatCAMTranslation as fcTranslate
  44. fcTranslate.apply_language('strings')
  45. import builtins
  46. if '_' not in builtins.__dict__:
  47. _ = gettext.gettext
  48. ########################################
  49. ## App ##
  50. ########################################
  51. class App(QtCore.QObject):
  52. """
  53. The main application class. The constructor starts the GUI.
  54. """
  55. # Get Cmd Line Options
  56. cmd_line_shellfile = ''
  57. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  58. try:
  59. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  60. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  61. except getopt.GetoptError:
  62. print(cmd_line_help)
  63. sys.exit(2)
  64. for opt, arg in cmd_line_options:
  65. if opt == '-h':
  66. print(cmd_line_help)
  67. sys.exit()
  68. elif opt == '--shellfile':
  69. cmd_line_shellfile = arg
  70. # Logging ##
  71. log = logging.getLogger('base')
  72. log.setLevel(logging.DEBUG)
  73. # log.setLevel(logging.WARNING)
  74. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  75. handler = logging.StreamHandler()
  76. handler.setFormatter(formatter)
  77. log.addHandler(handler)
  78. # Version
  79. version = 8.913
  80. version_date = "2019/03/25"
  81. beta = True
  82. # current date now
  83. date = str(datetime.today()).rpartition('.')[0]
  84. date = ''.join(c for c in date if c not in ':-')
  85. date = date.replace(' ', '_')
  86. # URL for update checks and statistics
  87. version_url = "http://flatcam.org/version"
  88. # App URL
  89. app_url = "http://flatcam.org"
  90. # Manual URL
  91. manual_url = "http://flatcam.org/manual/index.html"
  92. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  93. # this variable will hold the project status
  94. # if True it will mean that the project was modified and not saved
  95. should_we_save = False
  96. # flag is True if saving action has been triggered
  97. save_in_progress = False
  98. ##################
  99. ## Signals ##
  100. ##################
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. app_quit = QtCore.pyqtSignal()
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added or deleted from/to the collection
  132. object_status_changed = QtCore.pyqtSignal(object, str)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. ###################
  149. ### OS-specific ###
  150. ###################
  151. # Folder for user settings.
  152. if sys.platform == 'win32':
  153. from win32com.shell import shell, shellcon
  154. if platform.architecture()[0] == '32bit':
  155. App.log.debug("Win32!")
  156. else:
  157. App.log.debug("Win64!")
  158. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  159. self.os = 'windows'
  160. else: # Linux/Unix/MacOS
  161. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  162. self.os = 'unix'
  163. ###############################
  164. ### Setup folders and files ###
  165. ###############################
  166. if not os.path.exists(self.data_path):
  167. os.makedirs(self.data_path)
  168. App.log.debug('Created data folder: ' + self.data_path)
  169. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  170. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  171. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  172. if not os.path.exists(self.postprocessorpaths):
  173. os.makedirs(self.postprocessorpaths)
  174. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  175. # create current_defaults.FlatConfig file if there is none
  176. try:
  177. f = open(self.data_path + '/current_defaults.FlatConfig')
  178. f.close()
  179. except IOError:
  180. App.log.debug('Creating empty current_defaults.FlatConfig')
  181. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  182. json.dump({}, f)
  183. f.close()
  184. # create factory_defaults.FlatConfig file if there is none
  185. try:
  186. f = open(self.data_path + '/factory_defaults.FlatConfig')
  187. f.close()
  188. except IOError:
  189. App.log.debug('Creating empty factory_defaults.FlatConfig')
  190. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  191. json.dump({}, f)
  192. f.close()
  193. try:
  194. f = open(self.data_path + '/recent.json')
  195. f.close()
  196. except IOError:
  197. App.log.debug('Creating empty recent.json')
  198. f = open(self.data_path + '/recent.json', 'w')
  199. json.dump([], f)
  200. f.close()
  201. # Application directory. CHDIR to it. Otherwise, trying to load
  202. # GUI icons will fail as their path is relative.
  203. # This will fail under cx_freeze ...
  204. self.app_home = os.path.dirname(os.path.realpath(__file__))
  205. App.log.debug("Application path is " + self.app_home)
  206. App.log.debug("Started in " + os.getcwd())
  207. # cx_freeze workaround
  208. if os.path.isfile(self.app_home):
  209. self.app_home = os.path.dirname(self.app_home)
  210. os.chdir(self.app_home)
  211. # Create multiprocessing pool
  212. self.pool = Pool()
  213. # variable to store mouse coordinates
  214. self.mouse = [0, 0]
  215. ####################
  216. ## Initialize GUI ##
  217. ####################
  218. # FlatCAM colors used in plotting
  219. self.FC_light_green = '#BBF268BF'
  220. self.FC_dark_green = '#006E20BF'
  221. self.FC_light_blue = '#a5a5ffbf'
  222. self.FC_dark_blue = '#0000ffbf'
  223. QtCore.QObject.__init__(self)
  224. self.ui = FlatCAMGUI(self.version, self.beta, self)
  225. # self.connect(self.ui,
  226. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  227. # self.save_geometry) PyQt4
  228. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  229. self.ui.final_save.connect(self.final_save)
  230. ##############
  231. #### Data ####
  232. ##############
  233. self.recent = []
  234. self.clipboard = QtWidgets.QApplication.clipboard()
  235. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  236. self.project_filename = None
  237. self.toggle_units_ignore = False
  238. # self.defaults_form = PreferencesUI()
  239. # when adding entries here read the comments in the method found bellow named:
  240. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  241. self.defaults_form_fields = {
  242. # General App
  243. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  244. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  245. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  246. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  247. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  248. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  249. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  250. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  251. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  252. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  253. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  254. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  255. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  256. # General GUI Preferences
  257. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  258. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  259. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  260. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  261. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  262. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  263. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  264. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  265. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  266. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  267. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  268. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  269. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  270. # General GUI Settings
  271. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  272. # Gerber General
  273. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  274. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  275. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  276. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  277. # Gerber Options
  278. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  279. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  280. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  281. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  282. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  283. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  284. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  285. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  286. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  287. # Gerber Advanced Options
  288. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  289. "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  290. "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  291. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  292. # Excellon General
  293. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  294. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  295. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  296. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  297. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  298. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  299. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  300. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  301. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  302. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  303. # Excellon Options
  304. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  305. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  306. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  307. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  308. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  309. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  310. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  311. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  312. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  313. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  314. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  315. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  316. # Excellon Advanced Options
  317. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  318. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  319. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  320. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  321. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  322. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  323. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  324. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  325. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  326. # Excellon Export
  327. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  328. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  329. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  330. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  331. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  332. # Geometry General
  333. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  334. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  335. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  336. # Geometry Options
  337. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  338. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  339. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  340. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  341. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  342. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  343. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  344. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  345. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  346. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  347. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  348. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  349. # Geometry Advanced Options
  350. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  351. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  352. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  353. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  354. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  355. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  356. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  357. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  358. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  359. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  360. # CNCJob General
  361. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  362. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  363. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  364. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  365. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  366. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  367. # CNC Job Options
  368. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  369. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  370. # CNC Job Advanced Options
  371. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  372. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  373. # NCC Tool
  374. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  375. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  376. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  377. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  378. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  379. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  380. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  381. # CutOut Tool
  382. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  383. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  384. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  385. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  386. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  387. # Paint Area Tool
  388. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  389. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  390. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  391. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  392. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  393. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  394. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  395. # 2-sided Tool
  396. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  397. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  398. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  399. # Film Tool
  400. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  401. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  402. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  403. # Panelize Tool
  404. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  405. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  406. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  407. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  408. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  409. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  410. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  411. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  412. # Calculators Tool
  413. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  414. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  415. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  416. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  417. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  418. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  419. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  420. # Transformations Tool
  421. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  422. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  423. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  424. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  425. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  426. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  427. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  428. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  429. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  430. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  431. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  432. # SolderPaste Dispensing Tool
  433. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  434. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  435. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  436. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  437. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  438. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  439. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  440. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  441. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  442. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  443. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  444. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  445. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  446. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  447. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  448. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  449. }
  450. #############################
  451. #### LOAD POSTPROCESSORS ####
  452. #############################
  453. self.postprocessors = load_postprocessors(self)
  454. for name in list(self.postprocessors.keys()):
  455. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  456. if name.partition('_')[0] == 'Paste':
  457. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  458. continue
  459. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  460. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  461. if name == 'hpgl':
  462. continue
  463. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  464. #############################
  465. #### LOAD LANGUAGES ####
  466. #############################
  467. self.languages = fcTranslate.load_languages()
  468. for name in sorted(self.languages.values()):
  469. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  470. self.defaults = LoudDict()
  471. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  472. self.defaults.update({
  473. # Global APP Preferences
  474. "global_serial": 0,
  475. "global_stats": {},
  476. "units": "IN",
  477. "global_app_level": 'b',
  478. "global_language": 'English',
  479. "global_version_check": True,
  480. "global_send_stats": True,
  481. "global_pan_button": '2',
  482. "global_mselect_key": 'Control',
  483. "global_project_at_startup": False,
  484. "global_project_autohide": True,
  485. "global_toggle_tooltips": True,
  486. "global_compression_level": 3,
  487. "global_save_compressed": True,
  488. # Global GUI Preferences
  489. "global_gridx": 0.0393701,
  490. "global_gridy": 0.0393701,
  491. "global_snap_max": 0.001968504,
  492. "global_workspace": False,
  493. "global_workspaceT": "A4P",
  494. "global_grid_context_menu": {
  495. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  496. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  497. },
  498. "global_plot_fill": '#BBF268BF',
  499. "global_plot_line": '#006E20BF',
  500. "global_sel_fill": '#a5a5ffbf',
  501. "global_sel_line": '#0000ffbf',
  502. "global_alt_sel_fill": '#BBF268BF',
  503. "global_alt_sel_line": '#006E20BF',
  504. "global_draw_color": '#FF0000',
  505. "global_sel_draw_color": '#0000FF',
  506. "global_toolbar_view": 511,
  507. "global_background_timeout": 300000, # Default value is 5 minutes
  508. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  509. # (python trace only for unknown errors),
  510. # 1 = show trace(show trace allways),
  511. # 2 = (For the future).
  512. # Persistence
  513. "global_last_folder": None,
  514. "global_last_save_folder": None,
  515. # Default window geometry
  516. "global_def_win_x": 100,
  517. "global_def_win_y": 100,
  518. "global_def_win_w": 1024,
  519. "global_def_win_h": 650,
  520. # Constants...
  521. "global_defaults_save_period_ms": 20000, # Time between default saves.
  522. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  523. "global_shell_at_startup": False, # Show the shell at startup.
  524. "global_recent_limit": 10, # Max. items in recent list.
  525. "fit_key": 'V',
  526. "zoom_out_key": '-',
  527. "zoom_in_key": '=',
  528. "grid_toggle_key": 'G',
  529. "zoom_ratio": 1.5,
  530. "global_point_clipboard_format": "(%.4f, %.4f)",
  531. "global_zdownrate": None,
  532. # General GUI Settings
  533. "global_hover": True,
  534. # Gerber General
  535. "gerber_plot": True,
  536. "gerber_solid": True,
  537. "gerber_multicolored": False,
  538. "gerber_isotooldia": 0.016,
  539. "gerber_isopasses": 1,
  540. "gerber_isooverlap": 0.15,
  541. # Gerber Options
  542. "gerber_combine_passes": False,
  543. "gerber_milling_type": "cl",
  544. "gerber_noncoppermargin": 0.1,
  545. "gerber_noncopperrounded": False,
  546. "gerber_bboxmargin": 0.1,
  547. "gerber_bboxrounded": False,
  548. "gerber_circle_steps": 64,
  549. "gerber_use_buffer_for_union": True,
  550. # Gerber Advanced Options
  551. "gerber_aperture_display": False,
  552. "gerber_aperture_scale_factor": 1.0,
  553. "gerber_aperture_buffer_factor": 0.0,
  554. "gerber_follow": False,
  555. # Excellon General
  556. "excellon_plot": True,
  557. "excellon_solid": True,
  558. "excellon_format_upper_in": 2,
  559. "excellon_format_lower_in": 4,
  560. "excellon_format_upper_mm": 3,
  561. "excellon_format_lower_mm": 3,
  562. "excellon_zeros": "L",
  563. "excellon_units": "INCH",
  564. "excellon_optimization_type": 'B',
  565. "excellon_search_time": 3,
  566. # Excellon Options
  567. "excellon_drillz": -0.1,
  568. "excellon_travelz": 0.1,
  569. "excellon_feedrate": 3.0,
  570. "excellon_spindlespeed": None,
  571. "excellon_dwell": False,
  572. "excellon_dwelltime": 1,
  573. "excellon_toolchange": False,
  574. "excellon_toolchangez": 1.0,
  575. "excellon_ppname_e": 'default',
  576. "excellon_tooldia": 0.016,
  577. "excellon_slot_tooldia": 0.016,
  578. "excellon_gcode_type": "drills",
  579. # Excellon Advanced Options
  580. "excellon_offset": 0.0,
  581. "excellon_toolchangexy": "0.0, 0.0",
  582. "excellon_startz": None,
  583. "excellon_endz": 2.0,
  584. "excellon_feedrate_rapid": 3.0,
  585. "excellon_z_pdepth": -0.02,
  586. "excellon_feedrate_probe": 3.0,
  587. "excellon_f_plunge": False,
  588. "excellon_f_retract": False,
  589. # Excellon Export
  590. "excellon_exp_units": 'INCH',
  591. "excellon_exp_format": 'ndec',
  592. "excellon_exp_integer": 2,
  593. "excellon_exp_decimals": 4,
  594. "excellon_exp_zeros": 'LZ',
  595. # Geometry General
  596. "geometry_plot": True,
  597. "geometry_circle_steps": 64,
  598. "geometry_cnctooldia": 0.016,
  599. # Geometry Options
  600. "geometry_cutz": -0.002,
  601. "geometry_multidepth": False,
  602. "geometry_depthperpass": 0.002,
  603. "geometry_travelz": 0.1,
  604. "geometry_toolchange": False,
  605. "geometry_toolchangez": 1.0,
  606. "geometry_feedrate": 3.0,
  607. "geometry_feedrate_z": 3.0,
  608. "geometry_spindlespeed": None,
  609. "geometry_dwell": False,
  610. "geometry_dwelltime": 1,
  611. "geometry_ppname_g": 'default',
  612. # Geometry Advanced Options
  613. "geometry_toolchangexy": "0.0, 0.0",
  614. "geometry_startz": None,
  615. "geometry_endz": 2.0,
  616. "geometry_feedrate_rapid": 3.0,
  617. "geometry_extracut": False,
  618. "geometry_z_pdepth": -0.02,
  619. "geometry_f_plunge": False,
  620. "geometry_feedrate_probe": 3.0,
  621. "geometry_segx": 0.0,
  622. "geometry_segy": 0.0,
  623. # CNC Job General
  624. "cncjob_plot": True,
  625. "cncjob_plot_kind": 'all',
  626. "cncjob_tooldia": 0.0393701,
  627. "cncjob_coords_decimals": 4,
  628. "cncjob_fr_decimals": 2,
  629. "cncjob_steps_per_circle": 64,
  630. # CNC Job Options
  631. "cncjob_prepend": "",
  632. "cncjob_append": "",
  633. # CNC Job Advanced Options
  634. "cncjob_toolchange_macro": "",
  635. "cncjob_toolchange_macro_enable": False,
  636. "tools_ncctools": "0.0393701, 0.019685",
  637. "tools_nccoverlap": 0.015748,
  638. "tools_nccmargin": 0.00393701,
  639. "tools_nccmethod": "seed",
  640. "tools_nccconnect": True,
  641. "tools_ncccontour": True,
  642. "tools_nccrest": False,
  643. "tools_cutouttooldia": 0.00393701,
  644. "tools_cutoutmargin": 0.00393701,
  645. "tools_cutoutgapsize": 0.005905512,
  646. "tools_gaps_ff": "8",
  647. "tools_cutout_convexshape": False,
  648. "tools_painttooldia": 0.07,
  649. "tools_paintoverlap": 0.15,
  650. "tools_paintmargin": 0.0,
  651. "tools_paintmethod": "seed",
  652. "tools_selectmethod": "single",
  653. "tools_pathconnect": True,
  654. "tools_paintcontour": True,
  655. "tools_2sided_mirror_axis": "X",
  656. "tools_2sided_axis_loc": "point",
  657. "tools_2sided_drilldia": 0.0393701,
  658. "tools_film_type": 'neg',
  659. "tools_film_boundary": 0.0393701,
  660. "tools_film_scale": 0,
  661. "tools_panelize_spacing_columns": 0,
  662. "tools_panelize_spacing_rows": 0,
  663. "tools_panelize_columns": 1,
  664. "tools_panelize_rows": 1,
  665. "tools_panelize_constrain": False,
  666. "tools_panelize_constrainx": 0.0,
  667. "tools_panelize_constrainy": 0.0,
  668. "tools_panelize_panel_type": 'gerber',
  669. "tools_calc_vshape_tip_dia": 0.007874,
  670. "tools_calc_vshape_tip_angle": 30,
  671. "tools_calc_vshape_cut_z": 0.000787,
  672. "tools_calc_electro_length": 10.0,
  673. "tools_calc_electro_width": 10.0,
  674. "tools_calc_electro_cdensity":13.0,
  675. "tools_calc_electro_growth": 10.0,
  676. "tools_transform_rotate": 90,
  677. "tools_transform_skew_x": 0.0,
  678. "tools_transform_skew_y": 0.0,
  679. "tools_transform_scale_x": 1.0,
  680. "tools_transform_scale_y": 1.0,
  681. "tools_transform_scale_link": True,
  682. "tools_transform_scale_reference": True,
  683. "tools_transform_offset_x": 0.0,
  684. "tools_transform_offset_y": 0.0,
  685. "tools_transform_mirror_reference": False,
  686. "tools_transform_mirror_point": (0, 0),
  687. "tools_solderpaste_tools": "0.0393701, 0.011811",
  688. "tools_solderpaste_new": 0.011811,
  689. "tools_solderpaste_z_start": 0.00019685039,
  690. "tools_solderpaste_z_dispense": 0.00393701,
  691. "tools_solderpaste_z_stop": 0.00019685039,
  692. "tools_solderpaste_z_travel": 0.00393701,
  693. "tools_solderpaste_z_toolchange": 0.0393701,
  694. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  695. "tools_solderpaste_frxy": 3.0,
  696. "tools_solderpaste_frz": 3.0,
  697. "tools_solderpaste_frz_dispense": 0.0393701,
  698. "tools_solderpaste_speedfwd": 20,
  699. "tools_solderpaste_dwellfwd": 1,
  700. "tools_solderpaste_speedrev": 10,
  701. "tools_solderpaste_dwellrev": 1,
  702. "tools_solderpaste_pp": 'Paste_1'
  703. })
  704. ###############################
  705. ### Load defaults from file ###
  706. ###############################
  707. if user_defaults:
  708. self.load_defaults(filename='current_defaults')
  709. ############################
  710. ##### APPLY APP LANGUAGE ###
  711. ############################
  712. ret_val = fcTranslate.apply_language('strings')
  713. if ret_val == "no language":
  714. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  715. log.debug("Could not find the Language files. The App strings are missing.")
  716. else:
  717. # make the current language the current selection on the language combobox
  718. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  719. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  720. ###################################
  721. ### CREATE UNIQUE SERIAL NUMBER ###
  722. ###################################
  723. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  724. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  725. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  726. self.save_defaults(silent=True)
  727. self.propagate_defaults(silent=True)
  728. self.restore_main_win_geom()
  729. def auto_save_defaults():
  730. try:
  731. self.save_defaults(silent=True)
  732. self.propagate_defaults(silent=True)
  733. finally:
  734. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  735. # the following lines activates automatic defaults save
  736. # if user_defaults:
  737. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  738. # self.options_form = PreferencesUI()
  739. self.options_form_fields = {
  740. "units": self.ui.general_options_form.general_app_group.units_radio,
  741. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  742. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  743. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  744. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  745. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  746. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  747. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  748. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  749. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  750. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  751. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  752. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  753. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  754. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  755. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  756. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  757. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  758. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  759. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  760. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  761. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  762. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  763. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  764. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  765. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  766. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  767. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  768. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  769. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  770. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  771. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  772. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  773. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  774. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  775. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  776. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  777. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  778. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  779. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  780. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  781. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  782. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  783. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  784. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  785. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  786. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  787. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  788. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  789. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  790. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  791. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  792. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  793. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  794. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  795. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  796. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  797. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  798. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  799. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  800. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  801. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  802. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  803. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  804. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  805. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  806. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  807. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  808. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  809. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  810. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  811. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  812. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  813. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  814. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  815. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  816. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  817. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  818. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  819. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  820. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  821. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  822. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  823. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  824. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  825. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  826. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  827. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  828. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  829. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  830. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  831. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  832. }
  833. for name in list(self.postprocessors.keys()):
  834. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  835. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  836. self.options = LoudDict()
  837. self.options.set_change_callback(self.on_options_dict_change)
  838. self.options.update({
  839. "units": "IN",
  840. "global_gridx": 1.0,
  841. "global_gridy": 1.0,
  842. "global_snap_max": 0.05,
  843. "global_background_timeout": 300000, # Default value is 5 minutes
  844. "global_verbose_error_level": 0, # Shell verbosity:
  845. # 0 = default(python trace only for unknown errors),
  846. # 1 = show trace(show trace allways), 2 = (For the future).
  847. "gerber_plot": True,
  848. "gerber_solid": True,
  849. "gerber_multicolored": False,
  850. "gerber_isotooldia": 0.016,
  851. "gerber_isopasses": 1,
  852. "gerber_isooverlap": 0.15,
  853. "gerber_combine_passes": True,
  854. "gerber_noncoppermargin": 0.0,
  855. "gerber_noncopperrounded": False,
  856. "gerber_bboxmargin": 0.0,
  857. "gerber_bboxrounded": False,
  858. "excellon_plot": True,
  859. "excellon_solid": False,
  860. "excellon_format_upper_in": 2,
  861. "excellon_format_lower_in": 4,
  862. "excellon_format_upper_mm": 3,
  863. "excellon_format_lower_mm": 3,
  864. "excellon_units": 'INCH',
  865. "excellon_optimization_type": 'B',
  866. "excellon_search_time": 3,
  867. "excellon_zeros": "L",
  868. "excellon_drillz": -0.1,
  869. "excellon_travelz": 0.1,
  870. "excellon_feedrate": 3.0,
  871. "excellon_feedrate_rapid": 3.0,
  872. "excellon_spindlespeed": None,
  873. "excellon_dwell": True,
  874. "excellon_dwelltime": 1000,
  875. "excellon_toolchange": False,
  876. "excellon_toolchangez": 1.0,
  877. "excellon_toolchangexy": "0.0, 0.0",
  878. "excellon_tooldia": 0.016,
  879. "excellon_ppname_e": 'default',
  880. "excellon_f_plunge": False,
  881. "excellon_startz": None,
  882. "excellon_endz": 2.0,
  883. "geometry_plot": True,
  884. "geometry_segx": 0.0,
  885. "geometry_segy": 0.0,
  886. "geometry_cutz": -0.002,
  887. "geometry_travelz": 0.1,
  888. "geometry_feedrate": 3.0,
  889. "geometry_feedrate_z": 3.0,
  890. "geometry_feedrate_rapid": 3.0,
  891. "geometry_spindlespeed": None,
  892. "geometry_dwell": True,
  893. "geometry_dwelltime": 1000,
  894. "geometry_cnctooldia": 0.016,
  895. "geometry_toolchange": False,
  896. "geometry_toolchangez": 2.0,
  897. "geometry_toolchangexy": "0.0, 0.0",
  898. "geometry_startz": None,
  899. "geometry_endz": 2.0,
  900. "geometry_ppname_g": "default",
  901. "geometry_f_plunge": False,
  902. "geometry_depthperpass": 0.002,
  903. "geometry_multidepth": False,
  904. "geometry_extracut": False,
  905. "cncjob_plot": True,
  906. "cncjob_tooldia": 0.016,
  907. "cncjob_prepend": "",
  908. "cncjob_append": "",
  909. "tools_ncctools": "1.0, 0.5",
  910. "tools_nccoverlap": 0.4,
  911. "tools_nccmargin": 1,
  912. "tools_cutouttooldia": 0.07,
  913. "tools_cutoutmargin": 0.1,
  914. "tools_cutoutgapsize": 0.15,
  915. "tools_gaps_ff": "8",
  916. "tools_painttooldia": 0.07,
  917. "tools_paintoverlap": 0.15,
  918. "tools_paintmargin": 0.0,
  919. "tools_paintmethod": "seed",
  920. "tools_selectmethod": "single",
  921. "tools_pathconnect": True,
  922. "tools_paintcontour": True,
  923. "tools_2sided_mirror_axis": "X",
  924. "tools_2sided_axis_loc": 'point',
  925. "tools_2sided_drilldia": 1,
  926. "tools_film_type": 'neg',
  927. "tools_film_boundary": 1,
  928. "tools_film_scale": 0,
  929. "tools_panelize_spacing_columns": 0,
  930. "tools_panelize_spacing_rows": 0,
  931. "tools_panelize_columns": 1,
  932. "tools_panelize_rows": 1,
  933. "tools_panelize_constrain": False,
  934. "tools_panelize_constrainx": 0.0,
  935. "tools_panelize_constrainy": 0.0
  936. })
  937. self.options.update(self.defaults) # Copy app defaults to project options
  938. self.gen_form = None
  939. self.ger_form = None
  940. self.exc_form = None
  941. self.geo_form = None
  942. self.cnc_form = None
  943. self.tools_form = None
  944. self.on_options_combo_change(0) # Will show the initial form
  945. ### Define OBJECT COLLECTION ###
  946. self.collection = ObjectCollection(self)
  947. self.ui.project_tab_layout.addWidget(self.collection.view)
  948. ###
  949. self.log.debug("Finished creating Object Collection.")
  950. ### Initialize the color box's color in Preferences -> Global -> Color
  951. # Init Plot Colors
  952. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  953. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  954. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  955. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  956. int(self.defaults['global_plot_fill'][7:9], 16))
  957. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  958. int(self.defaults['global_plot_fill'][7:9], 16))
  959. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  960. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  961. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  962. # Init Left-Right Selection colors
  963. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  964. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  965. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  966. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  967. int(self.defaults['global_sel_fill'][7:9], 16))
  968. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  969. int(self.defaults['global_sel_fill'][7:9], 16))
  970. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  971. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  972. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  973. # Init Right-Left Selection colors
  974. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  975. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  976. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  977. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  978. int(self.defaults['global_sel_fill'][7:9], 16))
  979. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  980. int(self.defaults['global_sel_fill'][7:9], 16))
  981. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  982. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  983. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  984. # Init Draw color and Selection Draw Color
  985. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  986. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  987. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  988. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  989. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  990. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  991. #### End of Data ####
  992. #### Plot Area ####
  993. start_plot_time = time.time() # debug
  994. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  995. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  996. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  997. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  998. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  999. # Keys over plot enabled
  1000. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  1001. self.ui.splitter.setStretchFactor(1, 2)
  1002. # So it can receive key presses
  1003. self.plotcanvas.vispy_canvas.native.setFocus()
  1004. self.app_cursor = self.plotcanvas.new_cursor()
  1005. self.app_cursor.enabled = False
  1006. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1007. # depending on from where those tools are called different actions can be done
  1008. self.call_source = 'app'
  1009. end_plot_time = time.time()
  1010. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1011. ### EDITOR section
  1012. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1013. self.exc_editor = FlatCAMExcEditor(self)
  1014. self.grb_editor = FlatCAMGrbEditor(self)
  1015. #### Adjust tabs width ####
  1016. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1017. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1018. self.collection.view.setMinimumWidth(290)
  1019. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  1020. #### Worker ####
  1021. self.workers = WorkerStack()
  1022. self.worker_task.connect(self.workers.add_task)
  1023. ### Signal handling ###
  1024. ## Custom signals
  1025. self.inform.connect(self.info)
  1026. self.app_quit.connect(self.quit_application)
  1027. self.message.connect(self.message_dialog)
  1028. self.progress.connect(self.set_progress_bar)
  1029. self.object_created.connect(self.on_object_created)
  1030. self.object_changed.connect(self.on_object_changed)
  1031. self.object_plotted.connect(self.on_object_plotted)
  1032. self.plots_updated.connect(self.on_plots_updated)
  1033. self.file_opened.connect(self.register_recent)
  1034. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1035. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1036. ## Standard signals
  1037. # Menu
  1038. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1039. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1040. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1041. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1042. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1043. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1044. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1045. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1046. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1047. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1048. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1049. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1050. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1051. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1052. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1053. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1054. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1055. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1056. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1057. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1058. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1059. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1060. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1061. self.ui.menufile_exit.triggered.connect(self.final_save)
  1062. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1063. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1064. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1065. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1066. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1067. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1068. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1069. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1070. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1071. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  1072. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1073. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1074. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1075. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1076. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1077. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1078. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1079. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1080. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1081. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1082. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1083. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1084. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1085. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1086. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1087. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1088. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1089. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1090. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1091. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1092. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1093. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1094. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1095. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1096. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1097. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1098. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1099. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1100. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1101. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1102. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1103. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1104. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1105. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1106. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1107. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1108. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1109. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1110. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1111. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1112. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1113. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1114. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1115. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1116. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1117. # ToolBar signals
  1118. self.connect_toolbar_signals()
  1119. # Context Menu
  1120. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1121. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1122. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1123. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1124. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  1125. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  1126. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  1127. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  1128. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  1129. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  1130. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  1131. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1132. self.ui.clearplot.triggered.connect(self.clear_plots)
  1133. self.ui.replot.triggered.connect(self.plot_all)
  1134. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1135. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1136. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1137. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1138. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1139. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1140. # Preferences Plot Area TAB
  1141. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1142. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1143. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1144. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1145. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1146. ###############################
  1147. ### GUI PREFERENCES SIGNALS ###
  1148. ###############################
  1149. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1150. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1151. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1152. )
  1153. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(self.on_toggle_units)
  1154. ###############################
  1155. ### GUI PREFERENCES SIGNALS ###
  1156. ###############################
  1157. # Setting plot colors signals
  1158. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1159. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1160. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1161. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1162. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1163. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1164. # Setting selection (left - right) colors signals
  1165. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1166. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1167. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1168. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1169. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1170. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1171. # Setting selection (right - left) colors signals
  1172. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1173. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1174. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1175. self.on_alt_sf_color_spinner)
  1176. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1177. self.on_alt_sf_color_slider)
  1178. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1179. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1180. # Setting Editor Draw colors signals
  1181. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1182. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1183. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1184. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1185. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1186. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1187. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1188. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1189. self.on_cnc_custom_parameters)
  1190. # Modify G-CODE Plot Area TAB
  1191. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1192. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1193. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1194. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1195. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1196. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1197. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1198. # Object list
  1199. self.collection.view.activated.connect(self.on_row_activated)
  1200. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1201. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1202. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1203. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1204. self.on_excellon_defaults_button)
  1205. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1206. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1207. self.on_excellon_options_button)
  1208. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1209. self.tool_tab_locked = False
  1210. # decide if to show or hide the Notebook side of the screen at startup
  1211. if self.defaults["global_project_at_startup"] is True:
  1212. self.ui.splitter.setSizes([1, 1])
  1213. else:
  1214. self.ui.splitter.setSizes([0, 1])
  1215. ####################
  1216. ### Other setups ###
  1217. ####################
  1218. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1219. self.setup_obj_classes()
  1220. self.setup_recent_items()
  1221. self.setup_component_editor()
  1222. #############
  1223. ### Shell ###
  1224. #############
  1225. ###
  1226. # Auto-complete KEYWORDS
  1227. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1228. 'aligndrill', 'clear',
  1229. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1230. 'export_gcode',
  1231. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1232. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1233. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1234. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1235. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1236. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1237. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1238. ]
  1239. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1240. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1241. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1242. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1243. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1244. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1245. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1246. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1247. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1248. ]
  1249. self.tcl_keywords = [
  1250. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1251. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1252. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1253. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1254. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1255. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1256. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1257. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1258. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1259. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1260. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1261. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1262. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1263. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1264. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1265. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1266. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1267. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1268. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1269. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1270. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1271. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1272. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1273. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1274. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1275. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1276. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1277. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1278. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1279. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1280. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1281. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1282. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1283. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1284. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1285. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1286. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1287. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1288. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1289. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1290. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1291. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1292. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1293. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1294. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1295. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1296. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1297. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1298. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1299. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1300. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1301. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1302. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1303. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1304. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1305. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1306. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1307. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1308. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1309. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1310. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1311. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1312. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1313. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1314. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1315. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1316. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1317. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1318. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1319. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1320. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1321. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1322. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1323. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1324. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1325. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1326. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1327. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1328. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1329. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1330. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1331. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1332. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1333. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1334. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1335. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1336. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1337. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1338. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1339. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1340. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1341. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1342. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1343. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1344. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1345. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1346. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1347. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1348. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1349. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1350. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1351. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1352. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1353. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1354. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1355. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1356. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1357. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1358. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1359. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1360. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1361. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1362. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1363. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1364. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1365. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1366. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1367. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1368. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1369. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1370. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1371. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1372. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1373. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1374. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1375. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1376. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1377. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1378. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1379. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1380. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1381. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1382. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1383. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1384. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1385. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1386. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1387. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1388. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1389. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1390. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1391. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1392. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1393. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1394. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1395. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1396. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1397. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1398. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1399. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1400. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1401. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1402. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1403. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1404. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1405. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1406. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1407. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1408. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1409. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1410. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1411. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1412. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1413. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1414. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1415. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1416. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1417. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1418. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1419. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1420. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1421. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1422. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1423. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1424. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1425. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1426. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1427. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1428. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1429. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1430. ]
  1431. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1432. self.shell = FCShell(self, version=self.version)
  1433. self.shell._edit.set_model_data(self.myKeywords)
  1434. self.ui.code_editor.set_model_data(self.myKeywords)
  1435. self.shell.setWindowIcon(self.ui.app_icon)
  1436. self.shell.setWindowTitle("FlatCAM Shell")
  1437. self.shell.resize(*self.defaults["global_shell_shape"])
  1438. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1439. self.shell.append_output("(Type help to get started)\n\n")
  1440. self.init_tcl()
  1441. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1442. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1443. self.ui.shell_dock.setWidget(self.shell)
  1444. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1445. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1446. QtWidgets.QDockWidget.DockWidgetFloatable |
  1447. QtWidgets.QDockWidget.DockWidgetClosable)
  1448. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1449. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1450. if self.defaults["global_shell_at_startup"]:
  1451. self.ui.shell_dock.show()
  1452. else:
  1453. self.ui.shell_dock.hide()
  1454. #########################
  1455. ### Tools and Plugins ###
  1456. #########################
  1457. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1458. self.install_tools()
  1459. ### System Font Parsing ###
  1460. # self.f_parse = ParseFont(self)
  1461. # self.parse_system_fonts()
  1462. # test if the program was started with a script as parameter
  1463. if self.cmd_line_shellfile:
  1464. try:
  1465. with open(self.cmd_line_shellfile, "r") as myfile:
  1466. cmd_line_shellfile_text = myfile.read()
  1467. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1468. except Exception as ext:
  1469. print("ERROR: ", ext)
  1470. sys.exit(2)
  1471. ###########################
  1472. #### Check for updates ####
  1473. ###########################
  1474. # Separate thread (Not worker)
  1475. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1476. if (self.beta is False or self.beta is None) and \
  1477. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1478. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1479. self.thr2 = QtCore.QThread()
  1480. self.worker_task.emit({'fcn': self.version_check,
  1481. 'params': []})
  1482. self.thr2.start()
  1483. ####################################
  1484. #### Variables for global usage ####
  1485. ####################################
  1486. # coordinates for relative position display
  1487. self.rel_point1 = (0, 0)
  1488. self.rel_point2 = (0, 0)
  1489. # variable to store coordinates
  1490. self.pos = (0, 0)
  1491. self.pos_jump = (0, 0)
  1492. # decide if we have a double click or single click
  1493. self.doubleclick = False
  1494. # variable to store if there was motion before right mouse button click (panning)
  1495. self.panning_action = False
  1496. # variable to store if a command is active (then the var is not None) and which one it is
  1497. self.command_active = None
  1498. # variable to store the status of moving selection action
  1499. # None value means that it's not an selection action
  1500. # True value = a selection from left to right
  1501. # False value = a selection from right to left
  1502. self.selection_type = None
  1503. # List to store the objects that are currently loaded in FlatCAM
  1504. # This list is updated on each object creation or object delete
  1505. self.all_objects_list = []
  1506. # List to store the objects that are selected
  1507. self.sel_objects_list = []
  1508. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1509. self.key_modifiers = None
  1510. # Variable to hold the status of the axis
  1511. self.toggle_axis = True
  1512. # Variable to store the status of the fullscreen event
  1513. self.toggle_fscreen = False
  1514. # Variable to store the status of the code editor
  1515. self.toggle_codeeditor = False
  1516. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1517. self.click_noproject = False
  1518. self.cursor = None
  1519. # Variable to store the GCODE that was edited
  1520. self.gcode_edited = ""
  1521. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1522. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1523. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1524. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1525. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1526. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1527. 'mpf']
  1528. self.svg_list = ['svg']
  1529. self.dxf_list = ['dxf']
  1530. self.prj_list = ['flatprj']
  1531. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1532. # flag for polygons not cleared
  1533. self.poly_not_cleared = False
  1534. # VisPy visuals
  1535. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1536. self.isHovering = False
  1537. self.notHovering = True
  1538. ### Save defaults to factory_defaults.FlatConfig file ###
  1539. ### It's done only once after install #############
  1540. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1541. fac_def_from_file = factory_file.read()
  1542. factory_defaults = json.loads(fac_def_from_file)
  1543. # if the file contain an empty dictionary then save the factory defaults into the file
  1544. if not factory_defaults:
  1545. self.save_factory_defaults(silent=False)
  1546. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1547. initial_lay = 'Compact'
  1548. self.on_layout(index=None, lay=initial_lay)
  1549. # Set the combobox in Preferences to the current layout
  1550. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1551. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1552. factory_file.close()
  1553. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1554. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1555. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1556. # Post-GUI initialization: Experimental attempt
  1557. # to perform unit tests on the GUI.
  1558. # if post_gui is not None:
  1559. # post_gui(self)
  1560. App.log.debug("END of constructor. Releasing control.")
  1561. # accept a project file as command line parameter
  1562. # the path/file_name must be enclosed in quotes if it contain spaces
  1563. for argument in App.args:
  1564. if '.FlatPrj' in argument:
  1565. try:
  1566. project_name = str(argument)
  1567. if project_name == "":
  1568. self.inform.emit(_("Open cancelled."))
  1569. else:
  1570. # self.open_project(project_name)
  1571. run_from_arg = True
  1572. self.worker_task.emit({'fcn': self.open_project,
  1573. 'params': [project_name, run_from_arg]})
  1574. except Exception as e:
  1575. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1576. if '.FlatConfig' in argument:
  1577. try:
  1578. file_name = str(argument)
  1579. if file_name == "":
  1580. self.inform.emit(_("Open Config file failed."))
  1581. else:
  1582. # run_from_arg = True
  1583. # self.worker_task.emit({'fcn': self.open_config_file,
  1584. # 'params': [file_name, run_from_arg]})
  1585. self.open_config_file(file_name, run_from_arg=True)
  1586. except Exception as e:
  1587. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1588. if '.FlatScript' in argument:
  1589. try:
  1590. file_name = str(argument)
  1591. if file_name == "":
  1592. self.inform.emit(_("Open Script file failed."))
  1593. else:
  1594. # run_from_arg = True
  1595. # self.worker_task.emit({'fcn': self.open_script_file,
  1596. # 'params': [file_name, run_from_arg]})
  1597. self.on_filerunscript(name=file_name)
  1598. except Exception as e:
  1599. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1600. def defaults_read_form(self):
  1601. for option in self.defaults_form_fields:
  1602. try:
  1603. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1604. except:
  1605. pass
  1606. def defaults_write_form(self, factor=None):
  1607. for option in self.defaults:
  1608. self.defaults_write_form_field(option, factor=factor)
  1609. # try:
  1610. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1611. # except KeyError:
  1612. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1613. # # TODO: Rethink this?
  1614. # pass
  1615. def defaults_write_form_field(self, field, factor=None):
  1616. try:
  1617. if factor is None:
  1618. self.defaults_form_fields[field].set_value(self.defaults[field])
  1619. else:
  1620. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1621. except KeyError:
  1622. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1623. # TODO: Rethink this?
  1624. pass
  1625. except AttributeError:
  1626. log.debug(field)
  1627. def clear_pool(self):
  1628. self.pool.close()
  1629. self.pool = Pool()
  1630. self.pool_recreated.emit(self.pool)
  1631. gc.collect()
  1632. # the order that the tools are installed is important as they can depend on each other install position
  1633. def install_tools(self):
  1634. self.dblsidedtool = DblSidedTool(self)
  1635. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1636. self.measurement_tool = Measurement(self)
  1637. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1638. self.panelize_tool = Panelize(self)
  1639. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1640. self.film_tool = Film(self)
  1641. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1642. self.paste_tool = SolderPaste(self)
  1643. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'), separator=True)
  1644. self.move_tool = ToolMove(self)
  1645. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1646. before=self.ui.menueditorigin)
  1647. self.cutout_tool = CutOut(self)
  1648. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1649. before=self.measurement_tool.menuAction)
  1650. self.ncclear_tool = NonCopperClear(self)
  1651. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1652. before=self.measurement_tool.menuAction, separator=True)
  1653. self.paint_tool = ToolPaint(self)
  1654. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1655. before=self.measurement_tool.menuAction, separator=True)
  1656. self.calculator_tool = ToolCalculator(self)
  1657. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1658. self.transform_tool = ToolTransform(self)
  1659. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1660. self.properties_tool = Properties(self)
  1661. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1662. self.image_tool = ToolImage(self)
  1663. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1664. separator=True)
  1665. self.log.debug("Tools are installed.")
  1666. def remove_tools(self):
  1667. for act in self.ui.menutool.actions():
  1668. self.ui.menutool.removeAction(act)
  1669. def init_tools(self):
  1670. log.debug("init_tools()")
  1671. # delete the data currently in the Tools Tab and the Tab itself
  1672. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1673. if widget is not None:
  1674. widget.deleteLater()
  1675. self.ui.notebook.removeTab(2)
  1676. # rebuild the Tools Tab
  1677. self.ui.tool_tab = QtWidgets.QWidget()
  1678. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1679. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1680. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1681. self.ui.tool_scroll_area = VerticalScrollArea()
  1682. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1683. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1684. # first remove all of them
  1685. self.remove_tools()
  1686. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1687. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1688. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1689. # third install all of them
  1690. self.install_tools()
  1691. self.log.debug("Tools are initialized.")
  1692. # def parse_system_fonts(self):
  1693. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1694. # 'params': []})
  1695. def connect_toolbar_signals(self):
  1696. # Toolbar
  1697. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1698. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1699. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1700. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1701. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1702. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1703. self.ui.replot_btn.triggered.connect(self.plot_all)
  1704. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1705. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1706. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1707. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1708. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1709. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1710. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1711. self.ui.delete_btn.triggered.connect(self.on_delete)
  1712. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1713. # Tools Toolbar Signals
  1714. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1715. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1716. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1717. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1718. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1719. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1720. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1721. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1722. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1723. def object2editor(self):
  1724. """
  1725. Send the current Geometry or Excellon object (if any) into the editor.
  1726. :return: None
  1727. """
  1728. self.report_usage("object2editor()")
  1729. # adjust the visibility of some of the canvas context menu
  1730. self.ui.popmenu_edit.setVisible(False)
  1731. self.ui.popmenu_save.setVisible(True)
  1732. # adjust the status of the menu entries related to the editor
  1733. self.ui.menueditedit.setDisabled(True)
  1734. self.ui.menueditok.setDisabled(False)
  1735. edited_object = self.collection.get_active()
  1736. if isinstance(edited_object, FlatCAMGeometry):
  1737. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1738. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1739. if edited_object.multigeo is True:
  1740. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  1741. if len(edited_tools) > 1:
  1742. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  1743. "is not possible.\n Edit only one geometry at a time."))
  1744. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=edited_tools[0])
  1745. else:
  1746. self.geo_editor.edit_fcgeometry(edited_object)
  1747. # we set the notebook to hidden
  1748. self.ui.splitter.setSizes([0, 1])
  1749. # set call source to the Editor we go into
  1750. self.call_source = 'geo_editor'
  1751. elif isinstance(edited_object, FlatCAMExcellon):
  1752. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1753. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1754. self.exc_editor.edit_fcexcellon(edited_object)
  1755. # set call source to the Editor we go into
  1756. self.call_source = 'exc_editor'
  1757. elif isinstance(edited_object, FlatCAMGerber):
  1758. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1759. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1760. self.grb_editor.edit_fcgerber(edited_object)
  1761. # set call source to the Editor we go into
  1762. self.call_source = 'grb_editor'
  1763. else:
  1764. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry or Excellon Object to edit."))
  1765. return
  1766. # make sure that we can't select another object while in Editor Mode:
  1767. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1768. # delete any selection shape that might be active as they are not relevant in Editor
  1769. self.delete_selection_shape()
  1770. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1771. self.ui.plot_tab_area.protectTab(0)
  1772. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  1773. self.should_we_save = True
  1774. def editor2object(self, cleanup=None):
  1775. """
  1776. Transfers the Geometry or Excellon from the editor to the current object.
  1777. :return: None
  1778. """
  1779. self.report_usage("editor2object()")
  1780. # adjust the status of the menu entries related to the editor
  1781. self.ui.menueditedit.setDisabled(False)
  1782. self.ui.menueditok.setDisabled(True)
  1783. # do not update a geometry or excellon object unless it comes out of an editor
  1784. if self.call_source != 'app':
  1785. # adjust the visibility of some of the canvas context menu
  1786. self.ui.popmenu_edit.setVisible(True)
  1787. self.ui.popmenu_save.setVisible(False)
  1788. edited_obj = self.collection.get_active()
  1789. obj_type = ""
  1790. if isinstance(edited_obj, FlatCAMGeometry):
  1791. obj_type = "Geometry"
  1792. if cleanup is None:
  1793. self.geo_editor.update_fcgeometry(edited_obj)
  1794. self.geo_editor.update_options(edited_obj)
  1795. self.geo_editor.deactivate()
  1796. # update the geo object options so it is including the bounding box values
  1797. try:
  1798. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1799. edited_obj.options['xmin'] = xmin
  1800. edited_obj.options['ymin'] = ymin
  1801. edited_obj.options['xmax'] = xmax
  1802. edited_obj.options['ymax'] = ymax
  1803. except AttributeError:
  1804. self.inform.emit(_("[WARNING] Object empty after edit."))
  1805. elif isinstance(edited_obj, FlatCAMGerber):
  1806. obj_type = "Gerber"
  1807. if cleanup is None:
  1808. self.grb_editor.update_fcgerber(edited_obj)
  1809. self.grb_editor.update_options(edited_obj)
  1810. self.grb_editor.deactivate()
  1811. # update the geo object options so it is including the bounding box values
  1812. try:
  1813. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1814. edited_obj.options['xmin'] = xmin
  1815. edited_obj.options['ymin'] = ymin
  1816. edited_obj.options['xmax'] = xmax
  1817. edited_obj.options['ymax'] = ymax
  1818. except AttributeError:
  1819. self.inform.emit(_("[WARNING] Object empty after edit."))
  1820. elif isinstance(edited_obj, FlatCAMExcellon):
  1821. obj_type = "Excellon"
  1822. if cleanup is None:
  1823. self.exc_editor.update_fcexcellon(edited_obj)
  1824. self.exc_editor.update_options(edited_obj)
  1825. self.exc_editor.deactivate()
  1826. else:
  1827. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1828. return
  1829. # if notebook is hidden we show it
  1830. if self.ui.splitter.sizes()[0] == 0:
  1831. self.ui.splitter.setSizes([1, 1])
  1832. # restore the call_source to app
  1833. self.call_source = 'app'
  1834. edited_obj.plot()
  1835. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1836. self.ui.plot_tab_area.protectTab(0)
  1837. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1838. # reset the Object UI to original settings
  1839. # edited_obj.set_ui(edited_obj.ui_type())
  1840. # edited_obj.build_ui()
  1841. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1842. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1843. def get_last_folder(self):
  1844. return self.defaults["global_last_folder"]
  1845. def get_last_save_folder(self):
  1846. loc = self.defaults["global_last_save_folder"]
  1847. if loc is None:
  1848. loc = self.defaults["global_last_folder"]
  1849. if loc is None:
  1850. loc = os.path.dirname(__file__)
  1851. return loc
  1852. def report_usage(self, resource):
  1853. """
  1854. Increments usage counter for the given resource
  1855. in self.defaults['global_stats'].
  1856. :param resource: Name of the resource.
  1857. :return: None
  1858. """
  1859. if resource in self.defaults['global_stats']:
  1860. self.defaults['global_stats'][resource] += 1
  1861. else:
  1862. self.defaults['global_stats'][resource] = 1
  1863. def init_tcl(self):
  1864. if hasattr(self,'tcl'):
  1865. # self.tcl = None
  1866. # TODO we need to clean non default variables and procedures here
  1867. # new object cannot be used here as it will not remember values created for next passes,
  1868. # because tcl was execudted in old instance of TCL
  1869. pass
  1870. else:
  1871. self.tcl = tk.Tcl()
  1872. self.setup_shell()
  1873. self.log.debug("TCL Shell has been initialized.")
  1874. # TODO: This shouldn't be here.
  1875. class TclErrorException(Exception):
  1876. """
  1877. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1878. """
  1879. pass
  1880. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1881. """
  1882. Shows a message on the FlatCAM Shell
  1883. :param msg: Message to display.
  1884. :param show: Opens the shell.
  1885. :param error: Shows the message as an error.
  1886. :return: None
  1887. """
  1888. if show:
  1889. self.ui.shell_dock.show()
  1890. try:
  1891. if error:
  1892. self.shell.append_error(msg + "\n")
  1893. elif warning:
  1894. self.shell.append_warning(msg + "\n")
  1895. elif success:
  1896. self.shell.append_success(msg + "\n")
  1897. elif selected:
  1898. self.shell.append_selected(msg + "\n")
  1899. else:
  1900. self.shell.append_output(msg + "\n")
  1901. except AttributeError:
  1902. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1903. def raise_tcl_unknown_error(self, unknownException):
  1904. """
  1905. Raise exception if is different type than TclErrorException
  1906. this is here mainly to show unknown errors inside TCL shell console.
  1907. :param unknownException:
  1908. :return:
  1909. """
  1910. if not isinstance(unknownException, self.TclErrorException):
  1911. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1912. else:
  1913. raise unknownException
  1914. def display_tcl_error(self, error, error_info=None):
  1915. """
  1916. escape bracket [ with \ otherwise there is error
  1917. "ERROR: missing close-bracket" instead of real error
  1918. :param error: it may be text or exception
  1919. :return: None
  1920. """
  1921. if isinstance(error, Exception):
  1922. exc_type, exc_value, exc_traceback = error_info
  1923. if not isinstance(error, self.TclErrorException):
  1924. show_trace = 1
  1925. else:
  1926. show_trace = int(self.defaults['global_verbose_error_level'])
  1927. if show_trace > 0:
  1928. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1929. trc_formated = []
  1930. for a in reversed(trc):
  1931. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1932. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1933. exc_type,
  1934. "\n".join(trc_formated))
  1935. else:
  1936. text = "%s" % error
  1937. else:
  1938. text = error
  1939. text = text.replace('[', '\\[').replace('"', '\\"')
  1940. self.tcl.eval('return -code error "%s"' % text)
  1941. def raise_tcl_error(self, text):
  1942. """
  1943. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1944. :param text: text of error
  1945. :return: raise exception
  1946. """
  1947. self.display_tcl_error(text)
  1948. raise self.TclErrorException(text)
  1949. def exec_command(self, text):
  1950. """
  1951. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1952. Also handles execution in separated threads
  1953. :param text:
  1954. :return: output if there was any
  1955. """
  1956. self.report_usage('exec_command')
  1957. result = self.exec_command_test(text, False)
  1958. #MS: added this method call so the geometry is updated once the TCL
  1959. #command is executed
  1960. self.plot_all()
  1961. return result
  1962. def exec_command_test(self, text, reraise=True):
  1963. """
  1964. Same as exec_command(...) with additional control over exceptions.
  1965. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1966. :param text: Input command
  1967. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1968. :return: Output from the command
  1969. """
  1970. text = str(text)
  1971. try:
  1972. self.shell.open_proccessing() # Disables input box.
  1973. result = self.tcl.eval(str(text))
  1974. if result != 'None':
  1975. self.shell.append_output(result + '\n')
  1976. except tk.TclError as e:
  1977. # This will display more precise answer if something in TCL shell fails
  1978. result = self.tcl.eval("set errorInfo")
  1979. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1980. self.shell.append_error('ERROR: ' + result + '\n')
  1981. # Show error in console and just return or in test raise exception
  1982. if reraise:
  1983. raise e
  1984. finally:
  1985. self.shell.close_proccessing()
  1986. pass
  1987. return result
  1988. # """
  1989. # Code below is unsused. Saved for later.
  1990. # """
  1991. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1992. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1993. # self.log.debug(parts)
  1994. # try:
  1995. # if parts[0] not in commands:
  1996. # self.shell.append_error("Unknown command\n")
  1997. # return
  1998. #
  1999. # #import inspect
  2000. # #inspect.getargspec(someMethod)
  2001. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2002. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2003. # self.shell.append_error(
  2004. # "Command %s takes %d arguments. %d given.\n" %
  2005. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2006. # )
  2007. # return
  2008. #
  2009. # cmdfcn = commands[parts[0]]["fcn"]
  2010. # cmdconv = commands[parts[0]]["converters"]
  2011. # if len(parts) - 1 > 0:
  2012. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2013. # else:
  2014. # retval = cmdfcn()
  2015. # retfcn = commands[parts[0]]["retfcn"]
  2016. # if retval and retfcn(retval):
  2017. # self.shell.append_output(retfcn(retval) + "\n")
  2018. #
  2019. # except Exception as e:
  2020. # #self.shell.append_error(''.join(traceback.format_exc()))
  2021. # #self.shell.append_error("?\n")
  2022. # self.shell.append_error(str(e) + "\n")
  2023. def info(self, msg):
  2024. """
  2025. Informs the user. Normally on the status bar, optionally
  2026. also on the shell.
  2027. :param msg: Text to write.
  2028. :return: None
  2029. """
  2030. # Type of message in brackets at the begining of the message.
  2031. match = re.search("\[([^\]]+)\](.*)", msg)
  2032. if match:
  2033. level = match.group(1)
  2034. msg_ = match.group(2)
  2035. self.ui.fcinfo.set_status(str(msg_), level=level)
  2036. if level.lower() == "error":
  2037. self.shell_message(msg, error=True, show=True)
  2038. elif level.lower() == "warning":
  2039. self.shell_message(msg, warning=True, show=True)
  2040. elif level.lower() == "error_notcl":
  2041. self.shell_message(msg, error=True, show=False)
  2042. elif level.lower() == "warning_notcl":
  2043. self.shell_message(msg, warning=True, show=False)
  2044. elif level.lower() == "success":
  2045. self.shell_message(msg, success=True, show=False)
  2046. elif level.lower() == "selected":
  2047. self.shell_message(msg, selected=True, show=False)
  2048. else:
  2049. self.shell_message(msg, show=False)
  2050. else:
  2051. self.ui.fcinfo.set_status(str(msg), level="info")
  2052. # make sure that if the message is to clear the infobar with a space
  2053. # is not printed over and over on the shell
  2054. if msg != '':
  2055. self.shell_message(msg)
  2056. def restore_toolbar_view(self):
  2057. tb = self.defaults["global_toolbar_view"]
  2058. if tb & 1:
  2059. self.ui.toolbarfile.setVisible(True)
  2060. else:
  2061. self.ui.toolbarfile.setVisible(False)
  2062. if tb & 2:
  2063. self.ui.toolbargeo.setVisible(True)
  2064. else:
  2065. self.ui.toolbargeo.setVisible(False)
  2066. if tb & 4:
  2067. self.ui.toolbarview.setVisible(True)
  2068. else:
  2069. self.ui.toolbarview.setVisible(False)
  2070. if tb & 8:
  2071. self.ui.toolbartools.setVisible(True)
  2072. else:
  2073. self.ui.toolbartools.setVisible(False)
  2074. if tb & 16:
  2075. self.ui.exc_edit_toolbar.setVisible(True)
  2076. else:
  2077. self.ui.exc_edit_toolbar.setVisible(False)
  2078. if tb & 32:
  2079. self.ui.geo_edit_toolbar.setVisible(True)
  2080. else:
  2081. self.ui.geo_edit_toolbar.setVisible(False)
  2082. if tb & 64:
  2083. self.ui.grb_edit_toolbar.setVisible(True)
  2084. else:
  2085. self.ui.grb_edit_toolbar.setVisible(False)
  2086. if tb & 128:
  2087. self.ui.snap_toolbar.setVisible(True)
  2088. else:
  2089. self.ui.snap_toolbar.setVisible(False)
  2090. if tb & 256:
  2091. self.ui.toolbarshell.setVisible(True)
  2092. else:
  2093. self.ui.toolbarshell.setVisible(False)
  2094. def load_defaults(self, filename):
  2095. """
  2096. Loads the aplication's default settings from current_defaults.FlatConfig into
  2097. ``self.defaults``.
  2098. :return: None
  2099. """
  2100. try:
  2101. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2102. options = f.read()
  2103. f.close()
  2104. except IOError:
  2105. self.log.error("Could not load defaults file.")
  2106. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2107. # in case the defaults file can't be loaded, show all toolbars
  2108. self.defaults["global_toolbar_view"] = 511
  2109. return
  2110. try:
  2111. defaults = json.loads(options)
  2112. except:
  2113. # in case the defaults file can't be loaded, show all toolbars
  2114. self.defaults["global_toolbar_view"] = 511
  2115. e = sys.exc_info()[0]
  2116. App.log.error(str(e))
  2117. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2118. return
  2119. self.defaults.update(defaults)
  2120. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2121. # restore the toolbar view
  2122. self.restore_toolbar_view()
  2123. def on_import_preferences(self):
  2124. """
  2125. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2126. ``self.defaults``.
  2127. :return: None
  2128. """
  2129. self.report_usage("on_import_preferences")
  2130. App.log.debug("on_import_preferences()")
  2131. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2132. try:
  2133. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2134. directory=self.data_path, filter=filter)
  2135. except TypeError:
  2136. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"), filter=filter)
  2137. filename = str(filename)
  2138. if filename == "":
  2139. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2140. else:
  2141. try:
  2142. f = open(filename)
  2143. options = f.read()
  2144. f.close()
  2145. except IOError:
  2146. self.log.error("Could not load defaults file.")
  2147. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2148. return
  2149. try:
  2150. defaults_from_file = json.loads(options)
  2151. except:
  2152. e = sys.exc_info()[0]
  2153. App.log.error(str(e))
  2154. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2155. return
  2156. self.defaults.update(defaults_from_file)
  2157. self.inform.emit(_("[success] Imported Defaults from %s") %filename)
  2158. def on_export_preferences(self):
  2159. self.report_usage("on_export_preferences")
  2160. App.log.debug("on_export_preferences()")
  2161. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2162. try:
  2163. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2164. caption=_("Export FlatCAM Preferences"),
  2165. directory=self.data_path + '/preferences_' + self.date, filter=filter
  2166. )
  2167. except TypeError:
  2168. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"), filter=filter)
  2169. filename = str(filename)
  2170. defaults_from_file = {}
  2171. if filename == "":
  2172. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2173. return
  2174. else:
  2175. try:
  2176. f = open(filename, 'w')
  2177. defaults_file_content = f.read()
  2178. f.close()
  2179. except IOError:
  2180. App.log.debug('Creating a new preferences file ...')
  2181. f = open(filename, 'w')
  2182. json.dump({}, f)
  2183. f.close()
  2184. except:
  2185. e = sys.exc_info()[0]
  2186. App.log.error("Could not load defaults file.")
  2187. App.log.error(str(e))
  2188. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2189. return
  2190. try:
  2191. defaults_from_file = json.loads(defaults_file_content)
  2192. except:
  2193. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2194. # Update options
  2195. self.defaults_read_form()
  2196. defaults_from_file.update(self.defaults)
  2197. self.propagate_defaults(silent=True)
  2198. # Save update options
  2199. try:
  2200. f = open(filename, "w")
  2201. json.dump(defaults_from_file, f)
  2202. f.close()
  2203. except:
  2204. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2205. return
  2206. self.file_saved.emit("preferences", filename)
  2207. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2208. def on_preferences_open_folder(self):
  2209. self.report_usage("on_preferences_open_folder()")
  2210. if sys.platform == 'win32':
  2211. subprocess.Popen('explorer %s' % self.data_path)
  2212. elif sys.platform == 'darwin':
  2213. os.system('open "%s"' % self.data_path)
  2214. else:
  2215. subprocess.Popen(['xdg-open', self.data_path])
  2216. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2217. def save_geometry(self, x, y, width, height, notebook_width):
  2218. self.defaults["global_def_win_x"] = x
  2219. self.defaults["global_def_win_y"] = y
  2220. self.defaults["global_def_win_w"] = width
  2221. self.defaults["global_def_win_h"] = height
  2222. self.defaults["def_notebook_width"] = notebook_width
  2223. self.save_defaults()
  2224. def message_dialog(self, title, message, kind="info"):
  2225. icon = {"info": QtWidgets.QMessageBox.Information,
  2226. "warning": QtWidgets.QMessageBox.Warning,
  2227. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2228. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2229. dlg.setText(message)
  2230. dlg.exec_()
  2231. def register_recent(self, kind, filename):
  2232. self.log.debug("register_recent()")
  2233. self.log.debug(" %s" % kind)
  2234. self.log.debug(" %s" % filename)
  2235. record = {'kind': str(kind), 'filename': str(filename)}
  2236. if record in self.recent:
  2237. return
  2238. self.recent.insert(0, record)
  2239. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2240. self.recent.pop()
  2241. try:
  2242. f = open(self.data_path + '/recent.json', 'w')
  2243. except IOError:
  2244. App.log.error("Failed to open recent items file for writing.")
  2245. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2246. return
  2247. #try:
  2248. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2249. # except:
  2250. # App.log.error("Failed to write to recent items file.")
  2251. # self.inform.emit('ERROR: Failed to write to recent items file.')
  2252. # f.close()
  2253. f.close()
  2254. # Re-buid the recent items menu
  2255. self.setup_recent_items()
  2256. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2257. """
  2258. Creates a new specalized FlatCAMObj and attaches it to the application,
  2259. this is, updates the GUI accordingly, any other records and plots it.
  2260. This method is thread-safe.
  2261. Notes:
  2262. * If the name is in use, the self.collection will modify it
  2263. when appending it to the collection. There is no need to handle
  2264. name conflicts here.
  2265. :param kind: The kind of object to create. One of 'gerber',
  2266. 'excellon', 'cncjob' and 'geometry'.
  2267. :type kind: str
  2268. :param name: Name for the object.
  2269. :type name: str
  2270. :param initialize: Function to run after creation of the object
  2271. but before it is attached to the application. The function is
  2272. called with 2 parameters: the new object and the App instance.
  2273. :type initialize: function
  2274. :return: None
  2275. :rtype: None
  2276. """
  2277. App.log.debug("new_object()")
  2278. obj_plot = plot
  2279. obj_autoselected = autoselected
  2280. t0 = time.time() # Debug
  2281. ## Create object
  2282. classdict = {
  2283. "gerber": FlatCAMGerber,
  2284. "excellon": FlatCAMExcellon,
  2285. "cncjob": FlatCAMCNCjob,
  2286. "geometry": FlatCAMGeometry
  2287. }
  2288. App.log.debug("Calling object constructor...")
  2289. obj = classdict[kind](name)
  2290. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2291. # Set options from "Project options" form
  2292. self.options_read_form()
  2293. # IMPORTANT
  2294. # The key names in defaults and options dictionary's are not random:
  2295. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2296. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2297. # the options from project options form into the self.options. After that, below, depending on the type of
  2298. # object that is created, it will strip the name of the object and the underline (if the original key was
  2299. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2300. # "toolchange"
  2301. for option in self.options:
  2302. if option.find(kind + "_") == 0:
  2303. oname = option[len(kind) + 1:]
  2304. obj.options[oname] = self.options[option]
  2305. obj.isHovering = False
  2306. obj.notHovering = True
  2307. # Initialize as per user request
  2308. # User must take care to implement initialize
  2309. # in a thread-safe way as is is likely that we
  2310. # have been invoked in a separate thread.
  2311. t1 = time.time()
  2312. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2313. try:
  2314. return_value = initialize(obj, self)
  2315. except Exception as e:
  2316. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2317. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2318. msg += traceback.format_exc()
  2319. self.inform.emit(msg)
  2320. # if str(e) == "Empty Geometry":
  2321. # self.inform.emit("[ERROR_NOTCL] )
  2322. # else:
  2323. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2324. return "fail"
  2325. t2 = time.time()
  2326. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2327. if return_value == 'fail':
  2328. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2329. return "fail"
  2330. # Check units and convert if necessary
  2331. # This condition CAN be true because initialize() can change obj.units
  2332. if self.options["units"].upper() != obj.units.upper():
  2333. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2334. obj.convert_units(self.options["units"])
  2335. t3 = time.time()
  2336. self.log.debug("%f seconds converting units." % (t3 - t2))
  2337. # Create the bounding box for the object and then add the results to the obj.options
  2338. try:
  2339. xmin, ymin, xmax, ymax = obj.bounds()
  2340. obj.options['xmin'] = xmin
  2341. obj.options['ymin'] = ymin
  2342. obj.options['xmax'] = xmax
  2343. obj.options['ymax'] = ymax
  2344. except:
  2345. log.warning("The object has no bounds properties.")
  2346. # don't plot objects with no bounds, there is nothing to plot
  2347. self.plot = False
  2348. pass
  2349. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2350. # Move the object to the main thread and let the app know that it is available.
  2351. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  2352. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2353. return obj
  2354. def new_excellon_object(self):
  2355. self.report_usage("new_excellon_object()")
  2356. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  2357. def new_geometry_object(self):
  2358. self.report_usage("new_geometry_object()")
  2359. def initialize(obj, self):
  2360. obj.multitool = False
  2361. self.new_object('geometry', 'new_g', initialize, plot=False)
  2362. def on_object_created(self, obj, plot, autoselect):
  2363. """
  2364. Event callback for object creation.
  2365. :param obj: The newly created FlatCAM object.
  2366. :return: None
  2367. """
  2368. t0 = time.time() # DEBUG
  2369. self.log.debug("on_object_created()")
  2370. # The Collection might change the name if there is a collision
  2371. self.collection.append(obj)
  2372. # after adding the object to the collection always update the list of objects that are in the collection
  2373. self.all_objects_list = self.collection.get_list()
  2374. # self.inform.emit('[selected] %s created & selected: %s' %
  2375. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2376. if obj.kind == 'gerber':
  2377. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2378. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2379. elif obj.kind == 'excellon':
  2380. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2381. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2382. elif obj.kind == 'cncjob':
  2383. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2384. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2385. elif obj.kind == 'geometry':
  2386. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2387. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2388. # update the SHELL auto-completer model with the name of the new object
  2389. self.myKeywords.append(obj.options['name'])
  2390. self.shell._edit.set_model_data(self.myKeywords)
  2391. self.ui.code_editor.set_model_data(self.myKeywords)
  2392. if autoselect:
  2393. # select the just opened object but deselect the previous ones
  2394. self.collection.set_all_inactive()
  2395. self.collection.set_active(obj.options["name"])
  2396. # here it is done the object plotting
  2397. def worker_task(obj):
  2398. with self.proc_container.new("Plotting"):
  2399. if isinstance(obj, FlatCAMCNCjob):
  2400. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2401. else:
  2402. obj.plot()
  2403. t1 = time.time() # DEBUG
  2404. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2405. self.object_plotted.emit(obj)
  2406. # Send to worker
  2407. # self.worker.add_task(worker_task, [self])
  2408. if plot is True:
  2409. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2410. def on_object_changed(self, obj):
  2411. # update the bounding box data from obj.options
  2412. xmin, ymin, xmax, ymax = obj.bounds()
  2413. obj.options['xmin'] = xmin
  2414. obj.options['ymin'] = ymin
  2415. obj.options['xmax'] = xmax
  2416. obj.options['ymax'] = ymax
  2417. log.debug("Object changed, updating the bounding box data on self.options")
  2418. # delete the old selection shape
  2419. self.delete_selection_shape()
  2420. self.should_we_save = True
  2421. def on_object_plotted(self, obj):
  2422. self.on_zoom_fit(None)
  2423. def options_read_form(self):
  2424. for option in self.options_form_fields:
  2425. self.options[option] = self.options_form_fields[option].get_value()
  2426. def options_write_form(self):
  2427. for option in self.options:
  2428. self.options_write_form_field(option)
  2429. def options_write_form_field(self, field):
  2430. try:
  2431. self.options_form_fields[field].set_value(self.options[field])
  2432. except KeyError:
  2433. # Changed from error to debug. This allows to have data stored
  2434. # which is not user-editable.
  2435. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2436. pass
  2437. def on_about(self):
  2438. """
  2439. Displays the "about" dialog.
  2440. :return: None
  2441. """
  2442. self.report_usage("on_about")
  2443. version = self.version
  2444. version_date = self.version_date
  2445. beta = self.beta
  2446. class AboutDialog(QtWidgets.QDialog):
  2447. def __init__(self, parent=None):
  2448. QtWidgets.QDialog.__init__(self, parent)
  2449. # Icon and title
  2450. self.setWindowIcon(parent.app_icon)
  2451. self.setWindowTitle("FlatCAM")
  2452. layout1 = QtWidgets.QVBoxLayout()
  2453. self.setLayout(layout1)
  2454. layout2 = QtWidgets.QHBoxLayout()
  2455. layout1.addLayout(layout2)
  2456. logo = QtWidgets.QLabel()
  2457. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2458. layout2.addWidget(logo, stretch=0)
  2459. title = QtWidgets.QLabel(
  2460. _(
  2461. "<font size=8><B>FlatCAM</B></font><BR>"
  2462. "Version {version} {beta} ({date}) - {arch} <BR>"
  2463. "<BR>"
  2464. "2D Computer-Aided Printed Circuit Board<BR>"
  2465. "Manufacturing.<BR>"
  2466. "<BR>"
  2467. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2468. "<BR>"
  2469. "<B> Main Contributors:</B><BR>"
  2470. "Denis Hayrullin<BR>"
  2471. "Kamil Sopko<BR>"
  2472. "Marius Stanciu<BR>"
  2473. "Matthieu Berthomé<BR>"
  2474. "and many others found "
  2475. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2476. "<BR>"
  2477. "Development is done "
  2478. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2479. "DOWNLOAD area "
  2480. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2481. ""
  2482. ).format(version=version,
  2483. beta=('BETA' if beta else ''),
  2484. date=version_date,
  2485. arch=platform.architecture()[0])
  2486. )
  2487. title.setOpenExternalLinks(True)
  2488. layout2.addWidget(title, stretch=1)
  2489. layout3 = QtWidgets.QHBoxLayout()
  2490. layout1.addLayout(layout3)
  2491. layout3.addStretch()
  2492. okbtn = QtWidgets.QPushButton("Close")
  2493. layout3.addWidget(okbtn)
  2494. okbtn.clicked.connect(self.accept)
  2495. AboutDialog(self.ui).exec_()
  2496. def on_file_savedefaults(self):
  2497. """
  2498. Callback for menu item File->Save Defaults. Saves application default options
  2499. ``self.defaults`` to current_defaults.FlatConfig.
  2500. :return: None
  2501. """
  2502. self.save_defaults()
  2503. # def on_app_exit(self):
  2504. # self.report_usage("on_app_exit()")
  2505. #
  2506. # if self.collection.get_list():
  2507. # msgbox = QtWidgets.QMessageBox()
  2508. # # msgbox.setText("<B>Save changes ...</B>")
  2509. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2510. # "\n"
  2511. # "Do you want to Save the project?")
  2512. # msgbox.setWindowTitle("Save changes")
  2513. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2514. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2515. # QtWidgets.QMessageBox.Cancel)
  2516. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2517. #
  2518. # response = msgbox.exec_()
  2519. #
  2520. # if response == QtWidgets.QMessageBox.Yes:
  2521. # self.on_file_saveprojectas(thread=False)
  2522. # elif response == QtWidgets.QMessageBox.Cancel:
  2523. # return
  2524. # self.save_defaults()
  2525. # else:
  2526. # self.save_defaults()
  2527. # log.debug("Application defaults saved ... Exit event.")
  2528. # QtWidgets.qApp.quit()
  2529. def save_defaults(self, silent=False):
  2530. """
  2531. Saves application default options
  2532. ``self.defaults`` to current_defaults.FlatConfig.
  2533. :return: None
  2534. """
  2535. self.report_usage("save_defaults")
  2536. # Read options from file
  2537. try:
  2538. f = open(self.data_path + "/current_defaults.FlatConfig")
  2539. defaults_file_content = f.read()
  2540. f.close()
  2541. except:
  2542. e = sys.exc_info()[0]
  2543. App.log.error("Could not load defaults file.")
  2544. App.log.error(str(e))
  2545. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2546. return
  2547. try:
  2548. defaults = json.loads(defaults_file_content)
  2549. except:
  2550. e = sys.exc_info()[0]
  2551. App.log.error("Failed to parse defaults file.")
  2552. App.log.error(str(e))
  2553. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2554. return
  2555. # Update options
  2556. self.defaults_read_form()
  2557. defaults.update(self.defaults)
  2558. self.propagate_defaults(silent=True)
  2559. # Save update options
  2560. try:
  2561. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2562. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2563. f.close()
  2564. except:
  2565. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2566. return
  2567. # Save the toolbar view
  2568. tb_status = 0
  2569. if self.ui.toolbarfile.isVisible():
  2570. tb_status += 1
  2571. if self.ui.toolbargeo.isVisible():
  2572. tb_status += 2
  2573. if self.ui.toolbarview.isVisible():
  2574. tb_status += 4
  2575. if self.ui.toolbartools.isVisible():
  2576. tb_status += 8
  2577. if self.ui.exc_edit_toolbar.isVisible():
  2578. tb_status += 16
  2579. if self.ui.geo_edit_toolbar.isVisible():
  2580. tb_status += 32
  2581. if self.ui.grb_edit_toolbar.isVisible():
  2582. tb_status += 64
  2583. if self.ui.snap_toolbar.isVisible():
  2584. tb_status += 128
  2585. if self.ui.toolbarshell.isVisible():
  2586. tb_status += 256
  2587. self.defaults["global_toolbar_view"] = tb_status
  2588. if not silent:
  2589. self.inform.emit(_("[success] Defaults saved."))
  2590. def save_factory_defaults(self, silent=False):
  2591. """
  2592. Saves application factory default options
  2593. ``self.defaults`` to factory_defaults.FlatConfig.
  2594. It's a one time job done just after the first install.
  2595. :return: None
  2596. """
  2597. self.report_usage("save_factory_defaults")
  2598. # Read options from file
  2599. try:
  2600. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2601. factory_defaults_file_content = f_f_def.read()
  2602. f_f_def.close()
  2603. except:
  2604. e = sys.exc_info()[0]
  2605. App.log.error("Could not load factory defaults file.")
  2606. App.log.error(str(e))
  2607. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2608. return
  2609. try:
  2610. factory_defaults = json.loads(factory_defaults_file_content)
  2611. except:
  2612. e = sys.exc_info()[0]
  2613. App.log.error("Failed to parse factory defaults file.")
  2614. App.log.error(str(e))
  2615. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2616. return
  2617. # Update options
  2618. self.defaults_read_form()
  2619. factory_defaults.update(self.defaults)
  2620. self.propagate_defaults(silent=True)
  2621. # Save update options
  2622. try:
  2623. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2624. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2625. f_f_def_s.close()
  2626. except:
  2627. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2628. return
  2629. if silent is False:
  2630. self.inform.emit(_("Factory defaults saved."))
  2631. def final_save(self):
  2632. if self.save_in_progress:
  2633. self.inform.emit(_("Application is saving the project. Please wait ..."))
  2634. return
  2635. if self.should_we_save and self.collection.get_list():
  2636. msgbox = QtWidgets.QMessageBox()
  2637. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2638. "\n"
  2639. "Do you want to Save the project?"))
  2640. msgbox.setWindowTitle(_("Save changes"))
  2641. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2642. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2643. QtWidgets.QMessageBox.Cancel)
  2644. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2645. response = msgbox.exec_()
  2646. if response == QtWidgets.QMessageBox.Yes:
  2647. self.on_file_saveprojectas(thread=True, quit=True)
  2648. elif response == QtWidgets.QMessageBox.No:
  2649. QtWidgets.qApp.quit()
  2650. elif response == QtWidgets.QMessageBox.Cancel:
  2651. return
  2652. else:
  2653. QtWidgets.qApp.quit()
  2654. def quit_application(self):
  2655. self.save_defaults()
  2656. log.debug("App.final_save() --> App Defaults saved.")
  2657. # save toolbar state to file
  2658. settings = QSettings("Open Source", "FlatCAM")
  2659. settings.setValue('saved_gui_state', self.ui.saveState())
  2660. settings.setValue('maximized_gui', self.ui.isMaximized())
  2661. # This will write the setting to the platform specific storage.
  2662. del settings
  2663. log.debug("App.final_save() --> App UI state saved.")
  2664. QtWidgets.qApp.quit()
  2665. def on_toggle_shell(self):
  2666. """
  2667. toggle shell if is visible close it if closed open it
  2668. :return:
  2669. """
  2670. self.report_usage("on_toggle_shell()")
  2671. if self.ui.shell_dock.isVisible():
  2672. self.ui.shell_dock.hide()
  2673. else:
  2674. self.ui.shell_dock.show()
  2675. def on_edit_join(self, name=None):
  2676. """
  2677. Callback for Edit->Join. Joins the selected geometry objects into
  2678. a new one.
  2679. :return: None
  2680. """
  2681. self.report_usage("on_edit_join()")
  2682. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2683. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2684. tooldias = []
  2685. geo_type_list = []
  2686. objs = self.collection.get_selected()
  2687. for obj in objs:
  2688. geo_type_list.append(obj.multigeo)
  2689. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2690. if len(set(geo_type_list)) != 1:
  2691. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2692. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2693. "convert from one to another and retry joining \n"
  2694. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2695. "the result may not be what was expected. \n"
  2696. "Check the generated GCODE."))
  2697. return
  2698. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2699. if True in geo_type_list:
  2700. def initialize(obj, app):
  2701. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2702. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2703. for v in obj.tools.values():
  2704. v['data']['name'] = obj_name_multi
  2705. self.new_object("geometry", obj_name_multi, initialize)
  2706. else:
  2707. def initialize(obj, app):
  2708. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2709. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2710. for v in obj.tools.values():
  2711. v['data']['name'] = obj_name_single
  2712. self.new_object("geometry", obj_name_single, initialize)
  2713. self.should_we_save = True
  2714. def on_edit_join_exc(self):
  2715. """
  2716. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2717. a new one.
  2718. :return: None
  2719. """
  2720. self.report_usage("on_edit_join_exc()")
  2721. objs = self.collection.get_selected()
  2722. for obj in objs:
  2723. if not isinstance(obj, FlatCAMExcellon):
  2724. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  2725. return
  2726. def initialize(obj, app):
  2727. FlatCAMExcellon.merge(objs, obj)
  2728. self.new_object("excellon", 'Combo_Excellon', initialize)
  2729. self.should_we_save = True
  2730. def on_edit_join_grb(self):
  2731. """
  2732. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2733. a new one.
  2734. :return: None
  2735. """
  2736. self.report_usage("on_edit_join_grb()")
  2737. objs = self.collection.get_selected()
  2738. for obj in objs:
  2739. if not isinstance(obj, FlatCAMGerber):
  2740. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  2741. return
  2742. def initialize(obj, app):
  2743. FlatCAMGerber.merge(objs, obj)
  2744. self.new_object("gerber", 'Combo_Gerber', initialize)
  2745. self.should_we_save = True
  2746. def on_convert_singlegeo_to_multigeo(self):
  2747. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2748. obj = self.collection.get_active()
  2749. if obj is None:
  2750. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2751. return
  2752. if not isinstance(obj, FlatCAMGeometry):
  2753. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2754. return
  2755. obj.multigeo = True
  2756. for tooluid, dict_value in obj.tools.items():
  2757. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2758. if not isinstance(obj.solid_geometry, list):
  2759. obj.solid_geometry = [obj.solid_geometry]
  2760. obj.solid_geometry[:] = []
  2761. obj.plot()
  2762. self.should_we_save = True
  2763. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2764. def on_convert_multigeo_to_singlegeo(self):
  2765. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2766. obj = self.collection.get_active()
  2767. if obj is None:
  2768. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2769. return
  2770. if not isinstance(obj, FlatCAMGeometry):
  2771. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2772. return
  2773. obj.multigeo = False
  2774. total_solid_geometry = []
  2775. for tooluid, dict_value in obj.tools.items():
  2776. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2777. # clear the original geometry
  2778. dict_value['solid_geometry'][:] = []
  2779. obj.solid_geometry = deepcopy(total_solid_geometry)
  2780. obj.plot()
  2781. self.should_we_save = True
  2782. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2783. def on_options_dict_change(self, field):
  2784. self.options_write_form_field(field)
  2785. if field == "units":
  2786. self.set_screen_units(self.options['units'])
  2787. def on_defaults_dict_change(self, field):
  2788. self.defaults_write_form_field(field)
  2789. if field == "units":
  2790. self.set_screen_units(self.defaults['units'])
  2791. def set_screen_units(self, units):
  2792. self.ui.units_label.setText("[" + self.defaults["units"].lower() + "]")
  2793. def on_toggle_units(self):
  2794. """
  2795. Callback for the Units radio-button change in the Options tab.
  2796. Changes the application's default units or the current project's units.
  2797. If changing the project's units, the change propagates to all of
  2798. the objects in the project.
  2799. :return: None
  2800. """
  2801. self.report_usage("on_toggle_units")
  2802. if self.toggle_units_ignore:
  2803. return
  2804. # If option is the same, then ignore
  2805. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2806. self.defaults["units"].upper():
  2807. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2808. return
  2809. # Options to scale
  2810. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2811. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2812. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2813. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  2814. "excellon_z_pdepth",
  2815. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  2816. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  2817. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  2818. "geometry_feedrate_probe",
  2819. 'cncjob_tooldia',
  2820. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  2821. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  2822. "tools_2sided_drilldia", "tools_film_boundary",
  2823. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2824. "tools_panelize_constrainx", "tools_panelize_constrainy",
  2825. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  2826. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  2827. "tools_transform_offset_y",
  2828. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  2829. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  2830. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  2831. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  2832. 'global_gridx', 'global_gridy', 'global_snap_max']
  2833. def scale_options(sfactor):
  2834. for dim in dimensions:
  2835. if dim == 'excellon_toolchangexy':
  2836. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2837. coords_xy[0] *= sfactor
  2838. coords_xy[1] *= sfactor
  2839. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2840. elif dim == 'geometry_toolchangexy':
  2841. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2842. coords_xy[0] *= sfactor
  2843. coords_xy[1] *= sfactor
  2844. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2845. elif dim == 'tools_ncctools':
  2846. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2847. ncctols[0] *= sfactor
  2848. ncctols[1] *= sfactor
  2849. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  2850. elif dim == 'tools_solderpaste_tools':
  2851. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2852. sp_tools[0] *= sfactor
  2853. sp_tools[1] *= sfactor
  2854. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  2855. elif dim == 'tools_solderpaste_xy_toolchange':
  2856. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2857. sp_coords[0] *= sfactor
  2858. sp_coords[1] *= sfactor
  2859. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  2860. else:
  2861. try:
  2862. self.options[dim] = float(self.options[dim]) * sfactor
  2863. except Exception as e:
  2864. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  2865. def scale_defaults(sfactor):
  2866. for dim in dimensions:
  2867. if dim == 'excellon_toolchangexy':
  2868. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2869. coords_xy[0] *= sfactor
  2870. coords_xy[1] *= sfactor
  2871. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2872. elif dim == 'geometry_toolchangexy':
  2873. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2874. coords_xy[0] *= sfactor
  2875. coords_xy[1] *= sfactor
  2876. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2877. elif dim == 'tools_ncctools':
  2878. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2879. ncctols[0] *= sfactor
  2880. ncctols[1] *= sfactor
  2881. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  2882. elif dim == 'tools_solderpaste_tools':
  2883. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2884. sp_tools[0] *= sfactor
  2885. sp_tools[1] *= sfactor
  2886. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  2887. elif dim == 'tools_solderpaste_xy_toolchange':
  2888. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2889. sp_coords[0] *= sfactor
  2890. sp_coords[1] *= sfactor
  2891. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  2892. else:
  2893. try:
  2894. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  2895. except Exception as e:
  2896. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  2897. # The scaling factor depending on choice of units.
  2898. factor = 1/25.4
  2899. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2900. factor = 25.4
  2901. # Changing project units. Warn user.
  2902. msgbox = QtWidgets.QMessageBox()
  2903. msgbox.setWindowTitle("Toggle Units")
  2904. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  2905. msgbox.setText("<B>Change project units ...</B>")
  2906. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2907. "properties of all objects to be scaled accordingly.\nContinue?")
  2908. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2909. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2910. response = msgbox.exec_()
  2911. if response == QtWidgets.QMessageBox.Ok:
  2912. self.options_read_form()
  2913. scale_options(factor)
  2914. self.options_write_form()
  2915. self.defaults_read_form()
  2916. scale_defaults(factor)
  2917. self.defaults_write_form()
  2918. self.should_we_save = True
  2919. # change this only if the workspace is active
  2920. if self.defaults['global_workspace'] is True:
  2921. self.plotcanvas.draw_workspace()
  2922. # adjust the grid values on the main toolbar
  2923. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2924. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2925. for obj in self.collection.get_list():
  2926. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  2927. obj.convert_units(units)
  2928. # make that the properties stored in the object are also updated
  2929. self.object_changed.emit(obj)
  2930. obj.build_ui()
  2931. current = self.collection.get_active()
  2932. if current is not None:
  2933. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2934. if not isinstance(current, FlatCAMGeometry):
  2935. current.to_form()
  2936. self.plot_all()
  2937. self.inform.emit(_("[success] Converted units to %s") % self.defaults["units"])
  2938. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2939. self.set_screen_units(self.defaults["units"])
  2940. else:
  2941. # Undo toggling
  2942. self.toggle_units_ignore = True
  2943. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2944. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  2945. else:
  2946. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  2947. self.toggle_units_ignore = False
  2948. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  2949. self.options_read_form()
  2950. self.defaults_read_form()
  2951. def on_toggle_units_click(self):
  2952. if self.options["units"] == 'MM':
  2953. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  2954. else:
  2955. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  2956. self.on_toggle_units()
  2957. def on_fullscreen(self):
  2958. self.report_usage("on_fullscreen()")
  2959. if self.toggle_fscreen is False:
  2960. if sys.platform == 'win32':
  2961. self.ui.showFullScreen()
  2962. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2963. tb.setVisible(False)
  2964. self.ui.splitter_left.setVisible(False)
  2965. self.toggle_fscreen = True
  2966. else:
  2967. if sys.platform == 'win32':
  2968. self.ui.showNormal()
  2969. self.restore_toolbar_view()
  2970. self.ui.splitter_left.setVisible(True)
  2971. self.toggle_fscreen = False
  2972. def on_toggle_plotarea(self):
  2973. self.report_usage("on_toggle_plotarea()")
  2974. try:
  2975. name = self.ui.plot_tab_area.widget(0).objectName()
  2976. except AttributeError:
  2977. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2978. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2979. self.ui.plot_tab_area.protectTab(0)
  2980. return
  2981. if name != 'plotarea':
  2982. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2983. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2984. self.ui.plot_tab_area.protectTab(0)
  2985. else:
  2986. self.ui.plot_tab_area.closeTab(0)
  2987. def on_toggle_notebook(self):
  2988. if self.ui.splitter.sizes()[0] == 0:
  2989. self.ui.splitter.setSizes([1, 1])
  2990. else:
  2991. self.ui.splitter.setSizes([0, 1])
  2992. def on_toggle_axis(self):
  2993. self.report_usage("on_toggle_axis()")
  2994. if self.toggle_axis is False:
  2995. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2996. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2997. self.plotcanvas.redraw()
  2998. self.toggle_axis = True
  2999. else:
  3000. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3001. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3002. self.plotcanvas.redraw()
  3003. self.toggle_axis = False
  3004. def on_toggle_grid(self):
  3005. self.report_usage("on_toggle_grid()")
  3006. self.ui.grid_snap_btn.trigger()
  3007. def on_options_combo_change(self, sel):
  3008. """
  3009. Called when the combo box to choose between application defaults and
  3010. project option changes value. The corresponding variables are
  3011. copied to the UI.
  3012. :param sel: The option index that was chosen.
  3013. :return: None
  3014. """
  3015. # combo_sel = self.ui.notebook.combo_options.get_active()
  3016. App.log.debug("Options --> %s" % sel)
  3017. # form = [self.defaults_form, self.options_form][sel]
  3018. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3019. if sel == 0:
  3020. self.gen_form = self.ui.general_defaults_form
  3021. self.ger_form = self.ui.gerber_defaults_form
  3022. self.exc_form = self.ui.excellon_defaults_form
  3023. self.geo_form = self.ui.geometry_defaults_form
  3024. self.cnc_form = self.ui.cncjob_defaults_form
  3025. self.tools_form = self.ui.tools_defaults_form
  3026. elif sel == 1:
  3027. self.gen_form = self.ui.general_options_form
  3028. self.ger_form = self.ui.gerber_options_form
  3029. self.exc_form = self.ui.excellon_options_form
  3030. self.geo_form = self.ui.geometry_options_form
  3031. self.cnc_form = self.ui.cncjob_options_form
  3032. self.tools_form = self.ui.tools_options_form
  3033. else:
  3034. return
  3035. try:
  3036. self.ui.general_scroll_area.takeWidget()
  3037. except:
  3038. self.log.debug("Nothing to remove")
  3039. self.ui.general_scroll_area.setWidget(self.gen_form)
  3040. self.gen_form.show()
  3041. try:
  3042. self.ui.gerber_scroll_area.takeWidget()
  3043. except:
  3044. self.log.debug("Nothing to remove")
  3045. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3046. self.ger_form.show()
  3047. try:
  3048. self.ui.excellon_scroll_area.takeWidget()
  3049. except:
  3050. self.log.debug("Nothing to remove")
  3051. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3052. self.exc_form.show()
  3053. try:
  3054. self.ui.geometry_scroll_area.takeWidget()
  3055. except:
  3056. self.log.debug("Nothing to remove")
  3057. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3058. self.geo_form.show()
  3059. try:
  3060. self.ui.cncjob_scroll_area.takeWidget()
  3061. except:
  3062. self.log.debug("Nothing to remove")
  3063. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3064. self.cnc_form.show()
  3065. try:
  3066. self.ui.tools_scroll_area.takeWidget()
  3067. except:
  3068. self.log.debug("Nothing to remove")
  3069. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3070. self.tools_form.show()
  3071. self.log.debug("Finished GUI form initialization.")
  3072. # self.options2form()
  3073. def on_excellon_defaults_button(self):
  3074. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3075. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3076. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3077. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3078. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3079. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3080. log.debug("Excellon app defaults loaded ...")
  3081. def on_excellon_options_button(self):
  3082. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3083. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3084. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3085. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3086. self.options_form_fields["excellon_zeros"].set_value('L')
  3087. self.options_form_fields["excellon_units"].set_value('INCH')
  3088. log.debug("Excellon options defaults loaded ...")
  3089. # Setting plot colors handlers
  3090. def on_pf_color_entry(self):
  3091. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3092. self.defaults['global_plot_fill'][7:9]
  3093. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3094. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3095. def on_pf_color_button(self):
  3096. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3097. c_dialog = QtWidgets.QColorDialog()
  3098. plot_fill_color = c_dialog.getColor(initial=current_color)
  3099. if plot_fill_color.isValid() is False:
  3100. return
  3101. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3102. "background-color:%s" % str(plot_fill_color.name()))
  3103. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3104. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3105. self.defaults['global_plot_fill'] = new_val
  3106. def on_pf_color_spinner(self):
  3107. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3108. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3109. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  3110. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3111. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  3112. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3113. def on_pf_color_slider(self):
  3114. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3115. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3116. def on_pl_color_entry(self):
  3117. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3118. self.defaults['global_plot_line'][7:9]
  3119. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3120. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3121. def on_pl_color_button(self):
  3122. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3123. # print(current_color)
  3124. c_dialog = QtWidgets.QColorDialog()
  3125. plot_line_color = c_dialog.getColor(initial=current_color)
  3126. if plot_line_color.isValid() is False:
  3127. return
  3128. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3129. "background-color:%s" % str(plot_line_color.name()))
  3130. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3131. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3132. self.defaults['global_plot_line'] = new_val_line
  3133. # Setting selection colors (left - right) handlers
  3134. def on_sf_color_entry(self):
  3135. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3136. self.defaults['global_sel_fill'][7:9]
  3137. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3138. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3139. def on_sf_color_button(self):
  3140. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3141. c_dialog = QtWidgets.QColorDialog()
  3142. plot_fill_color = c_dialog.getColor(initial=current_color)
  3143. if plot_fill_color.isValid() is False:
  3144. return
  3145. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3146. "background-color:%s" % str(plot_fill_color.name()))
  3147. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3148. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3149. self.defaults['global_sel_fill'] = new_val
  3150. def on_sf_color_spinner(self):
  3151. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3152. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3153. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  3154. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3155. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  3156. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3157. def on_sf_color_slider(self):
  3158. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3159. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3160. def on_sl_color_entry(self):
  3161. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3162. self.defaults['global_sel_line'][7:9]
  3163. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3164. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3165. def on_sl_color_button(self):
  3166. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3167. c_dialog = QtWidgets.QColorDialog()
  3168. plot_line_color = c_dialog.getColor(initial=current_color)
  3169. if plot_line_color.isValid() is False:
  3170. return
  3171. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3172. "background-color:%s" % str(plot_line_color.name()))
  3173. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3174. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3175. self.defaults['global_sel_line'] = new_val_line
  3176. # Setting selection colors (right - left) handlers
  3177. def on_alt_sf_color_entry(self):
  3178. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3179. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3180. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3181. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3182. def on_alt_sf_color_button(self):
  3183. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3184. c_dialog = QtWidgets.QColorDialog()
  3185. plot_fill_color = c_dialog.getColor(initial=current_color)
  3186. if plot_fill_color.isValid() is False:
  3187. return
  3188. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3189. "background-color:%s" % str(plot_fill_color.name()))
  3190. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3191. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3192. self.defaults['global_alt_sel_fill'] = new_val
  3193. def on_alt_sf_color_spinner(self):
  3194. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3195. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3196. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  3197. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3198. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  3199. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3200. def on_alt_sf_color_slider(self):
  3201. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3202. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3203. def on_alt_sl_color_entry(self):
  3204. self.defaults['global_alt_sel_line'] = self.ui.general_defaults_form.general_gui_group \
  3205. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  3206. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3207. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3208. def on_alt_sl_color_button(self):
  3209. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3210. c_dialog = QtWidgets.QColorDialog()
  3211. plot_line_color = c_dialog.getColor(initial=current_color)
  3212. if plot_line_color.isValid() is False:
  3213. return
  3214. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3215. "background-color:%s" % str(plot_line_color.name()))
  3216. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3217. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3218. self.defaults['global_alt_sel_line'] = new_val_line
  3219. # Setting Editor colors
  3220. def on_draw_color_entry(self):
  3221. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3222. .draw_color_entry.get_value()
  3223. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3224. "background-color:%s" % str(self.defaults['global_draw_color']))
  3225. def on_draw_color_button(self):
  3226. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3227. c_dialog = QtWidgets.QColorDialog()
  3228. draw_color = c_dialog.getColor(initial=current_color)
  3229. if draw_color.isValid() is False:
  3230. return
  3231. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3232. "background-color:%s" % str(draw_color.name()))
  3233. new_val = str(draw_color.name())
  3234. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3235. self.defaults['global_draw_color'] = new_val
  3236. def on_sel_draw_color_entry(self):
  3237. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3238. .sel_draw_color_entry.get_value()
  3239. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3240. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3241. def on_sel_draw_color_button(self):
  3242. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3243. c_dialog = QtWidgets.QColorDialog()
  3244. sel_draw_color = c_dialog.getColor(initial=current_color)
  3245. if sel_draw_color.isValid() is False:
  3246. return
  3247. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3248. "background-color:%s" % str(sel_draw_color.name()))
  3249. new_val_sel = str(sel_draw_color.name())
  3250. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3251. self.defaults['global_sel_draw_color'] = new_val_sel
  3252. def on_deselect_all(self):
  3253. self.collection.set_all_inactive()
  3254. self.delete_selection_shape()
  3255. def on_workspace_modified(self):
  3256. self.save_defaults(silent=True)
  3257. self.plotcanvas.draw_workspace()
  3258. def on_workspace(self):
  3259. self.report_usage("on_workspace()")
  3260. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3261. self.plotcanvas.restore_workspace()
  3262. else:
  3263. self.plotcanvas.delete_workspace()
  3264. self.save_defaults(silent=True)
  3265. def on_workspace_menu(self):
  3266. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3267. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3268. else:
  3269. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3270. self.on_workspace()
  3271. def on_layout(self, index, lay=None):
  3272. self.report_usage("on_layout()")
  3273. if lay:
  3274. current_layout = lay
  3275. else:
  3276. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3277. settings = QSettings("Open Source", "FlatCAM")
  3278. settings.setValue('layout', current_layout)
  3279. # This will write the setting to the platform specific storage.
  3280. del settings
  3281. # first remove the toolbars:
  3282. try:
  3283. self.ui.removeToolBar(self.ui.toolbarfile)
  3284. self.ui.removeToolBar(self.ui.toolbargeo)
  3285. self.ui.removeToolBar(self.ui.toolbarview)
  3286. self.ui.removeToolBar(self.ui.toolbarshell)
  3287. self.ui.removeToolBar(self.ui.toolbartools)
  3288. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3289. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3290. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3291. self.ui.removeToolBar(self.ui.snap_toolbar)
  3292. self.ui.removeToolBar(self.ui.toolbarshell)
  3293. except:
  3294. pass
  3295. if current_layout == 'Standard':
  3296. ### TOOLBAR INSTALLATION ###
  3297. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3298. self.ui.toolbarfile.setObjectName('File_TB')
  3299. self.ui.addToolBar(self.ui.toolbarfile)
  3300. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3301. self.ui.toolbargeo.setObjectName('Edit_TB')
  3302. self.ui.addToolBar(self.ui.toolbargeo)
  3303. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3304. self.ui.toolbarview.setObjectName('View_TB')
  3305. self.ui.addToolBar(self.ui.toolbarview)
  3306. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3307. self.ui.toolbarshell.setObjectName('Shell_TB')
  3308. self.ui.addToolBar(self.ui.toolbarshell)
  3309. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3310. self.ui.toolbartools.setObjectName('Tools_TB')
  3311. self.ui.addToolBar(self.ui.toolbartools)
  3312. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3313. self.ui.exc_edit_toolbar.setVisible(False)
  3314. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3315. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3316. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3317. self.ui.geo_edit_toolbar.setVisible(False)
  3318. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3319. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3320. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3321. self.ui.grb_edit_toolbar.setVisible(False)
  3322. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3323. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3324. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3325. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3326. # self.ui.snap_toolbar.setMaximumHeight(30)
  3327. self.ui.addToolBar(self.ui.snap_toolbar)
  3328. self.ui.corner_snap_btn.setVisible(False)
  3329. self.ui.snap_magnet.setVisible(False)
  3330. elif current_layout == 'Compact':
  3331. ### TOOLBAR INSTALLATION ###
  3332. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3333. self.ui.toolbarfile.setObjectName('File_TB')
  3334. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3335. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3336. self.ui.toolbargeo.setObjectName('Edit_TB')
  3337. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3338. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3339. self.ui.toolbarview.setObjectName('View_TB')
  3340. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3341. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3342. self.ui.toolbarshell.setObjectName('Shell_TB')
  3343. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3344. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3345. self.ui.toolbartools.setObjectName('Tools_TB')
  3346. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3347. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3348. # self.ui.geo_edit_toolbar.setVisible(False)
  3349. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3350. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3351. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3352. # self.ui.grb_edit_toolbar.setVisible(False)
  3353. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3354. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  3355. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3356. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3357. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3358. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3359. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3360. self.ui.snap_toolbar.setMaximumHeight(30)
  3361. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3362. self.ui.corner_snap_btn.setVisible(True)
  3363. self.ui.snap_magnet.setVisible(True)
  3364. # add all the actions to the toolbars
  3365. self.ui.populate_toolbars()
  3366. # reconnect all the signals to the toolbar actions
  3367. self.connect_toolbar_signals()
  3368. self.ui.grid_snap_btn.setChecked(True)
  3369. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3370. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3371. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3372. self.ui.grid_gap_link_cb.setChecked(True)
  3373. def on_cnc_custom_parameters(self, signal_text):
  3374. if signal_text == 'Parameters':
  3375. return
  3376. else:
  3377. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3378. def on_save_button(self):
  3379. self.save_defaults(silent=False)
  3380. # load the defaults so they are updated into the app
  3381. self.load_defaults(filename='current_defaults')
  3382. # Re-fresh project options
  3383. self.on_options_app2project()
  3384. def handlePrint(self):
  3385. self.report_usage("handlePrint()")
  3386. dialog = QtPrintSupport.QPrintDialog()
  3387. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3388. self.ui.code_editor.document().print_(dialog.printer())
  3389. def handlePreview(self):
  3390. self.report_usage("handlePreview()")
  3391. dialog = QtPrintSupport.QPrintPreviewDialog()
  3392. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3393. dialog.exec_()
  3394. def handleTextChanged(self):
  3395. # enable = not self.ui.code_editor.document().isEmpty()
  3396. # self.ui.buttonPrint.setEnabled(enable)
  3397. # self.ui.buttonPreview.setEnabled(enable)
  3398. pass
  3399. def handleOpen(self, filt=None):
  3400. self.report_usage("handleOpen()")
  3401. if filt:
  3402. _filter_ = filt
  3403. else:
  3404. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3405. "All Files (*.*)"
  3406. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  3407. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  3408. if path:
  3409. file = QtCore.QFile(path)
  3410. if file.open(QtCore.QIODevice.ReadOnly):
  3411. stream = QtCore.QTextStream(file)
  3412. self.gcode_edited = stream.readAll()
  3413. self.ui.code_editor.setPlainText(self.gcode_edited)
  3414. file.close()
  3415. def handleSaveGCode(self,name=None, filt=None):
  3416. self.report_usage("handleSaveGCode()")
  3417. if filt:
  3418. _filter_ = filt
  3419. else:
  3420. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3421. "All Files (*.*)"
  3422. if name:
  3423. obj_name = name
  3424. else:
  3425. try:
  3426. obj_name = self.collection.get_active().options['name']
  3427. except AttributeError:
  3428. obj_name = 'file'
  3429. if filt is None:
  3430. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3431. try:
  3432. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3433. caption=_("Export G-Code ..."),
  3434. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3435. filter=_filter_
  3436. )[0])
  3437. except TypeError:
  3438. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3439. if filename == "":
  3440. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  3441. return
  3442. else:
  3443. try:
  3444. my_gcode = self.ui.code_editor.toPlainText()
  3445. with open(filename, 'w') as f:
  3446. for line in my_gcode:
  3447. f.write(line)
  3448. except FileNotFoundError:
  3449. self.inform.emit(_("[WARNING] No such file or directory"))
  3450. return
  3451. # Just for adding it to the recent files list.
  3452. self.file_opened.emit("cncjob", filename)
  3453. self.file_saved.emit("cncjob", filename)
  3454. self.inform.emit(_("Saved to: %s") % filename)
  3455. def handleFindGCode(self):
  3456. self.report_usage("handleFindGCode()")
  3457. flags = QtGui.QTextDocument.FindCaseSensitively
  3458. text_to_be_found = self.ui.entryFind.get_value()
  3459. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3460. if r is False:
  3461. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3462. def handleReplaceGCode(self):
  3463. self.report_usage("handleReplaceGCode()")
  3464. old = self.ui.entryFind.get_value()
  3465. new = self.ui.entryReplace.get_value()
  3466. if self.ui.sel_all_cb.isChecked():
  3467. while True:
  3468. cursor = self.ui.code_editor.textCursor()
  3469. cursor.beginEditBlock()
  3470. flags = QtGui.QTextDocument.FindCaseSensitively
  3471. # self.ui.editor is the QPlainTextEdit
  3472. r = self.ui.code_editor.find(str(old), flags)
  3473. if r:
  3474. qc = self.ui.code_editor.textCursor()
  3475. if qc.hasSelection():
  3476. qc.insertText(new)
  3477. else:
  3478. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3479. break
  3480. # Mark end of undo block
  3481. cursor.endEditBlock()
  3482. else:
  3483. cursor = self.ui.code_editor.textCursor()
  3484. cursor.beginEditBlock()
  3485. qc = self.ui.code_editor.textCursor()
  3486. if qc.hasSelection():
  3487. qc.insertText(new)
  3488. # Mark end of undo block
  3489. cursor.endEditBlock()
  3490. def on_tool_add_keypress(self):
  3491. ## Current application units in Upper Case
  3492. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3493. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3494. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3495. if notebook_widget_name == 'selected_tab':
  3496. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3497. # Tool add works for Geometry only if Advanced is True in Preferences
  3498. if self.defaults["global_app_level"] == 'a':
  3499. tool_add_popup = FCInputDialog(title="New Tool ...",
  3500. text='Enter a Tool Diameter:',
  3501. min=0.0000, max=99.9999, decimals=4)
  3502. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3503. val, ok = tool_add_popup.get_value()
  3504. if ok:
  3505. if float(val) == 0:
  3506. self.inform.emit(
  3507. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3508. return
  3509. self.collection.get_active().on_tool_add(dia=float(val))
  3510. else:
  3511. self.inform.emit(
  3512. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3513. else:
  3514. msgbox = QtWidgets.QMessageBox()
  3515. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3516. "Go to Preferences -> General - Show Advanced Options."))
  3517. msgbox.setWindowTitle("Tool adding ...")
  3518. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3519. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3520. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3521. msgbox.exec_()
  3522. # work only if the notebook tab on focus is the Tools_Tab
  3523. if notebook_widget_name == 'tool_tab':
  3524. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3525. tool_add_popup = FCInputDialog(title="New Tool ...",
  3526. text='Enter a Tool Diameter:',
  3527. min=0.0000, max=99.9999, decimals=4)
  3528. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3529. val, ok = tool_add_popup.get_value()
  3530. # and only if the tool is NCC Tool
  3531. if tool_widget == self.ncclear_tool.toolName:
  3532. if ok:
  3533. if float(val) == 0:
  3534. self.inform.emit(
  3535. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3536. return
  3537. self.ncclear_tool.on_tool_add(dia=float(val))
  3538. else:
  3539. self.inform.emit(
  3540. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3541. # and only if the tool is Paint Area Tool
  3542. elif tool_widget == self.paint_tool.toolName:
  3543. if ok:
  3544. if float(val) == 0:
  3545. self.inform.emit(
  3546. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3547. return
  3548. self.paint_tool.on_tool_add(dia=float(val))
  3549. else:
  3550. self.inform.emit(
  3551. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3552. # and only if the tool is Solder Paste Dispensing Tool
  3553. elif tool_widget == self.paste_tool.toolName:
  3554. if ok:
  3555. if float(val) == 0:
  3556. self.inform.emit(
  3557. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3558. return
  3559. self.paste_tool.on_tool_add(dia=float(val))
  3560. else:
  3561. self.inform.emit(
  3562. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3563. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3564. # See description bellow.
  3565. def on_delete_keypress(self):
  3566. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3567. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3568. if notebook_widget_name == 'selected_tab':
  3569. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3570. self.collection.get_active().on_tool_delete()
  3571. # work only if the notebook tab on focus is the Tools_Tab
  3572. elif notebook_widget_name == 'tool_tab':
  3573. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3574. # and only if the tool is NCC Tool
  3575. if tool_widget == self.ncclear_tool.toolName:
  3576. self.ncclear_tool.on_tool_delete()
  3577. # and only if the tool is Paint Tool
  3578. elif tool_widget == self.paint_tool.toolName:
  3579. self.paint_tool.on_tool_delete()
  3580. # and only if the tool is Solder Paste Dispensing Tool
  3581. elif tool_widget == self.paste_tool.toolName:
  3582. self.paste_tool.on_tool_delete()
  3583. else:
  3584. self.on_delete()
  3585. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3586. # some screens you have to be careful where you hover with your mouse.
  3587. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3588. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3589. # Complicated, I know :)
  3590. def on_delete(self):
  3591. """
  3592. Delete the currently selected FlatCAMObjs.
  3593. :return: None
  3594. """
  3595. self.report_usage("on_delete()")
  3596. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3597. # a geometry object before we update it.
  3598. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3599. if self.collection.get_active():
  3600. self.log.debug("on_delete()")
  3601. self.report_usage("on_delete")
  3602. while (self.collection.get_active()):
  3603. self.delete_first_selected()
  3604. self.inform.emit(_("Object(s) deleted ..."))
  3605. # make sure that the selection shape is deleted, too
  3606. self.delete_selection_shape()
  3607. else:
  3608. self.inform.emit(_("Failed. No object(s) selected..."))
  3609. else:
  3610. self.inform.emit(_("Save the work in Editor and try again ..."))
  3611. def on_set_origin(self):
  3612. """
  3613. Set the origin to the left mouse click position
  3614. :return: None
  3615. """
  3616. #display the message for the user
  3617. #and ask him to click on the desired position
  3618. self.report_usage("on_set_origin()")
  3619. self.inform.emit(_('Click to set the origin ...'))
  3620. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3621. def on_jump_to(self):
  3622. """
  3623. Jump to a location by setting the mouse cursor location
  3624. :return:
  3625. """
  3626. self.report_usage("on_jump_to()")
  3627. dia_box = Dialog_box(title=_("Jump to ..."),
  3628. label=_("Enter the coordinates in format X,Y:"),
  3629. icon=QtGui.QIcon('share/jump_to16.png'))
  3630. if dia_box.ok is True:
  3631. try:
  3632. location = eval(dia_box.location)
  3633. if not isinstance(location, tuple):
  3634. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3635. return
  3636. except:
  3637. return
  3638. else:
  3639. return
  3640. self.plotcanvas.fit_center(loc=location)
  3641. cursor = QtGui.QCursor()
  3642. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3643. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3644. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3645. self.inform.emit(_("Done."))
  3646. def on_copy_object(self):
  3647. self.report_usage("on_copy_object()")
  3648. def initialize(obj_init, app):
  3649. obj_init.solid_geometry = obj.solid_geometry
  3650. try:
  3651. obj_init.follow_geometry = obj.follow_geometry
  3652. except:
  3653. pass
  3654. try:
  3655. obj_init.apertures = obj.apertures
  3656. except:
  3657. pass
  3658. try:
  3659. if obj.tools:
  3660. obj_init.tools = obj.tools
  3661. except Exception as e:
  3662. log.debug("on_copy_object() --> %s" % str(e))
  3663. def initialize_excellon(obj_init, app):
  3664. obj_init.tools = obj.tools
  3665. # drills are offset, so they need to be deep copied
  3666. obj_init.drills = deepcopy(obj.drills)
  3667. # slots are offset, so they need to be deep copied
  3668. obj_init.slots = deepcopy(obj.slots)
  3669. obj_init.create_geometry()
  3670. for obj in self.collection.get_selected():
  3671. obj_name = obj.options["name"]
  3672. try:
  3673. if isinstance(obj, FlatCAMExcellon):
  3674. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3675. elif isinstance(obj,FlatCAMGerber):
  3676. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3677. elif isinstance(obj,FlatCAMGeometry):
  3678. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3679. except Exception as e:
  3680. return "Operation failed: %s" % str(e)
  3681. def on_copy_object2(self, custom_name):
  3682. def initialize_geometry(obj_init, app):
  3683. obj_init.solid_geometry = obj.solid_geometry
  3684. try:
  3685. obj_init.follow_geometry = obj.follow_geometry
  3686. except:
  3687. pass
  3688. try:
  3689. obj_init.apertures = obj.apertures
  3690. except:
  3691. pass
  3692. try:
  3693. if obj.tools:
  3694. obj_init.tools = obj.tools
  3695. except Exception as e:
  3696. log.debug("on_copy_object2() --> %s" % str(e))
  3697. def initialize_gerber(obj_init, app):
  3698. obj_init.solid_geometry = obj.solid_geometry
  3699. obj_init.apertures = deepcopy(obj.apertures)
  3700. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3701. def initialize_excellon(obj_init, app):
  3702. obj_init.tools = obj.tools
  3703. # drills are offset, so they need to be deep copied
  3704. obj_init.drills = deepcopy(obj.drills)
  3705. # slots are offset, so they need to be deep copied
  3706. obj_init.slots = deepcopy(obj.slots)
  3707. obj_init.create_geometry()
  3708. for obj in self.collection.get_selected():
  3709. obj_name = obj.options["name"]
  3710. try:
  3711. if isinstance(obj, FlatCAMExcellon):
  3712. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3713. elif isinstance(obj,FlatCAMGerber):
  3714. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3715. elif isinstance(obj,FlatCAMGeometry):
  3716. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3717. except Exception as e:
  3718. return "Operation failed: %s" % str(e)
  3719. def on_rename_object(self, text):
  3720. self.report_usage("on_rename_object()")
  3721. named_obj = self.collection.get_active()
  3722. for obj in named_obj:
  3723. if obj is list:
  3724. self.on_rename_object(text)
  3725. else:
  3726. try:
  3727. obj.options['name'] = text
  3728. except:
  3729. log.warning("Could not rename the object in the list")
  3730. def on_copy_object_as_geometry(self):
  3731. self.report_usage("on_copy_object_as_geometry()")
  3732. def initialize(obj_init, app):
  3733. obj_init.solid_geometry = obj.solid_geometry
  3734. try:
  3735. obj_init.follow_geometry = obj.follow_geometry
  3736. except:
  3737. pass
  3738. try:
  3739. obj_init.apertures = obj.apertures
  3740. except:
  3741. pass
  3742. if obj.tools:
  3743. obj_init.tools = obj.tools
  3744. def initialize_excellon(obj, app):
  3745. objs = self.collection.get_selected()
  3746. FlatCAMGeometry.merge(objs, obj)
  3747. for obj in self.collection.get_selected():
  3748. obj_name = obj.options["name"]
  3749. try:
  3750. if isinstance(obj, FlatCAMExcellon):
  3751. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3752. else:
  3753. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3754. except Exception as e:
  3755. return "Operation failed: %s" % str(e)
  3756. def on_set_zero_click(self, event):
  3757. #this function will be available only for mouse left click
  3758. pos =[]
  3759. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3760. if event.button == 1:
  3761. if self.grid_status() == True:
  3762. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3763. else:
  3764. pos = pos_canvas
  3765. x = 0 - pos[0]
  3766. y = 0 - pos[1]
  3767. for obj in self.collection.get_list():
  3768. obj.offset((x,y))
  3769. self.object_changed.emit(obj)
  3770. obj.plot()
  3771. # Update the object bounding box options
  3772. a, b, c, d = obj.bounds()
  3773. obj.options['xmin'] = a
  3774. obj.options['ymin'] = b
  3775. obj.options['xmax'] = c
  3776. obj.options['ymax'] = d
  3777. # self.plot_all(zoom=False)
  3778. self.inform.emit(_('[success] Origin set ...'))
  3779. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3780. self.should_we_save = True
  3781. def on_selectall(self):
  3782. self.report_usage("on_selectall()")
  3783. # delete the possible selection box around a possible selected object
  3784. self.delete_selection_shape()
  3785. for name in self.collection.get_names():
  3786. self.collection.set_active(name)
  3787. curr_sel_obj = self.collection.get_by_name(name)
  3788. # create the selection box around the selected object
  3789. self.draw_selection_shape(curr_sel_obj)
  3790. def on_preferences(self):
  3791. # add the tab if it was closed
  3792. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  3793. # delete the absolute and relative position and messages in the infobar
  3794. self.ui.position_label.setText("")
  3795. self.ui.rel_position_label.setText("")
  3796. # Switch plot_area to preferences page
  3797. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3798. self.ui.show()
  3799. def on_flipy(self):
  3800. self.report_usage("on_flipy()")
  3801. obj_list = self.collection.get_selected()
  3802. xminlist = []
  3803. yminlist = []
  3804. xmaxlist = []
  3805. ymaxlist = []
  3806. if not obj_list:
  3807. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  3808. else:
  3809. try:
  3810. # first get a bounding box to fit all
  3811. for obj in obj_list:
  3812. xmin, ymin, xmax, ymax = obj.bounds()
  3813. xminlist.append(xmin)
  3814. yminlist.append(ymin)
  3815. xmaxlist.append(xmax)
  3816. ymaxlist.append(ymax)
  3817. # get the minimum x,y and maximum x,y for all objects selected
  3818. xminimal = min(xminlist)
  3819. yminimal = min(yminlist)
  3820. xmaximal = max(xmaxlist)
  3821. ymaximal = max(ymaxlist)
  3822. px = 0.5 * (xminimal + xmaximal)
  3823. py = 0.5 * (yminimal + ymaximal)
  3824. # execute mirroring
  3825. for obj in obj_list:
  3826. obj.mirror('X', [px, py])
  3827. obj.plot()
  3828. self.object_changed.emit(obj)
  3829. self.inform.emit(_("[success] Flip on Y axis done."))
  3830. except Exception as e:
  3831. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3832. return
  3833. def on_flipx(self):
  3834. self.report_usage("on_flipx()")
  3835. obj_list = self.collection.get_selected()
  3836. xminlist = []
  3837. yminlist = []
  3838. xmaxlist = []
  3839. ymaxlist = []
  3840. if not obj_list:
  3841. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  3842. else:
  3843. try:
  3844. # first get a bounding box to fit all
  3845. for obj in obj_list:
  3846. xmin, ymin, xmax, ymax = obj.bounds()
  3847. xminlist.append(xmin)
  3848. yminlist.append(ymin)
  3849. xmaxlist.append(xmax)
  3850. ymaxlist.append(ymax)
  3851. # get the minimum x,y and maximum x,y for all objects selected
  3852. xminimal = min(xminlist)
  3853. yminimal = min(yminlist)
  3854. xmaximal = max(xmaxlist)
  3855. ymaximal = max(ymaxlist)
  3856. px = 0.5 * (xminimal + xmaximal)
  3857. py = 0.5 * (yminimal + ymaximal)
  3858. # execute mirroring
  3859. for obj in obj_list:
  3860. obj.mirror('Y', [px, py])
  3861. obj.plot()
  3862. self.object_changed.emit(obj)
  3863. self.inform.emit(_("[success] Flip on X axis done."))
  3864. except Exception as e:
  3865. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3866. return
  3867. def on_rotate(self, silent=False, preset=None):
  3868. self.report_usage("on_rotate()")
  3869. obj_list = self.collection.get_selected()
  3870. xminlist = []
  3871. yminlist = []
  3872. xmaxlist = []
  3873. ymaxlist = []
  3874. if not obj_list:
  3875. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  3876. else:
  3877. if silent is False:
  3878. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3879. min=-360, max=360, decimals=4,
  3880. init_val=float(self.defaults['tools_transform_rotate']))
  3881. num, ok = rotatebox.get_value()
  3882. else:
  3883. num = preset
  3884. ok = True
  3885. if ok:
  3886. try:
  3887. # first get a bounding box to fit all
  3888. for obj in obj_list:
  3889. xmin, ymin, xmax, ymax = obj.bounds()
  3890. xminlist.append(xmin)
  3891. yminlist.append(ymin)
  3892. xmaxlist.append(xmax)
  3893. ymaxlist.append(ymax)
  3894. # get the minimum x,y and maximum x,y for all objects selected
  3895. xminimal = min(xminlist)
  3896. yminimal = min(yminlist)
  3897. xmaximal = max(xmaxlist)
  3898. ymaximal = max(ymaxlist)
  3899. px = 0.5 * (xminimal + xmaximal)
  3900. py = 0.5 * (yminimal + ymaximal)
  3901. for sel_obj in obj_list:
  3902. sel_obj.rotate(-float(num), point=(px, py))
  3903. sel_obj.plot()
  3904. self.object_changed.emit(sel_obj)
  3905. self.inform.emit(_("[success] Rotation done."))
  3906. except Exception as e:
  3907. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3908. return
  3909. def on_skewx(self):
  3910. self.report_usage("on_skewx()")
  3911. obj_list = self.collection.get_selected()
  3912. xminlist = []
  3913. yminlist = []
  3914. if not obj_list:
  3915. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  3916. else:
  3917. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3918. min=-360, max=360, decimals=4,
  3919. init_val=float(self.defaults['tools_transform_skew_x']))
  3920. num, ok = skewxbox.get_value()
  3921. if ok:
  3922. # first get a bounding box to fit all
  3923. for obj in obj_list:
  3924. xmin, ymin, xmax, ymax = obj.bounds()
  3925. xminlist.append(xmin)
  3926. yminlist.append(ymin)
  3927. # get the minimum x,y and maximum x,y for all objects selected
  3928. xminimal = min(xminlist)
  3929. yminimal = min(yminlist)
  3930. for obj in obj_list:
  3931. obj.skew(num, 0, point=(xminimal, yminimal))
  3932. obj.plot()
  3933. self.object_changed.emit(obj)
  3934. self.inform.emit(_("[success] Skew on X axis done."))
  3935. def on_skewy(self):
  3936. self.report_usage("on_skewy()")
  3937. obj_list = self.collection.get_selected()
  3938. xminlist = []
  3939. yminlist = []
  3940. if not obj_list:
  3941. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  3942. else:
  3943. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3944. min=-360, max=360, decimals=4,
  3945. init_val=float(self.defaults['tools_transform_skew_y']))
  3946. num, ok = skewybox.get_value()
  3947. if ok:
  3948. # first get a bounding box to fit all
  3949. for obj in obj_list:
  3950. xmin, ymin, xmax, ymax = obj.bounds()
  3951. xminlist.append(xmin)
  3952. yminlist.append(ymin)
  3953. # get the minimum x,y and maximum x,y for all objects selected
  3954. xminimal = min(xminlist)
  3955. yminimal = min(yminlist)
  3956. for obj in obj_list:
  3957. obj.skew(0, num, point=(xminimal, yminimal))
  3958. obj.plot()
  3959. self.object_changed.emit(obj)
  3960. self.inform.emit(_("[success] Skew on Y axis done."))
  3961. def delete_first_selected(self):
  3962. # Keep this for later
  3963. try:
  3964. name = self.collection.get_active().options["name"]
  3965. except AttributeError:
  3966. self.log.debug("Nothing selected for deletion")
  3967. return
  3968. # Remove plot
  3969. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3970. # self.plotcanvas.auto_adjust_axes()
  3971. # Clear form
  3972. self.setup_component_editor()
  3973. # Remove from dictionary
  3974. self.collection.delete_active()
  3975. self.inform.emit("Object deleted: %s" % name)
  3976. def on_plots_updated(self):
  3977. """
  3978. Callback used to report when the plots have changed.
  3979. Adjust axes and zooms to fit.
  3980. :return: None
  3981. """
  3982. # self.plotcanvas.auto_adjust_axes()
  3983. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3984. self.on_zoom_fit(None)
  3985. # TODO: Rework toolbar 'clear', 'replot' functions
  3986. def on_toolbar_replot(self):
  3987. """
  3988. Callback for toolbar button. Re-plots all objects.
  3989. :return: None
  3990. """
  3991. self.report_usage("on_toolbar_replot")
  3992. self.log.debug("on_toolbar_replot()")
  3993. try:
  3994. self.collection.get_active().read_form()
  3995. except AttributeError:
  3996. self.log.debug("on_toolbar_replot(): AttributeError")
  3997. pass
  3998. self.plot_all()
  3999. def on_row_activated(self, index):
  4000. if index.isValid():
  4001. if index.internalPointer().parent_item != self.collection.root_item:
  4002. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4003. def grid_status(self):
  4004. if self.ui.grid_snap_btn.isChecked():
  4005. return 1
  4006. else:
  4007. return 0
  4008. def populate_cmenu_grids(self):
  4009. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4010. self.ui.cmenu_gridmenu.clear()
  4011. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4012. for grid in sorted_list:
  4013. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4014. action.triggered.connect(self.set_grid)
  4015. self.ui.cmenu_gridmenu.addSeparator()
  4016. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  4017. grid_add.triggered.connect(self.on_grid_add)
  4018. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  4019. grid_delete.triggered.connect(self.on_grid_delete)
  4020. def set_grid(self):
  4021. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4022. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4023. def on_grid_add(self):
  4024. ## Current application units in lower Case
  4025. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4026. grid_add_popup = FCInputDialog(title="New Grid ...",
  4027. text='Enter a Grid VAlue:',
  4028. min=0.0000, max=99.9999, decimals=4)
  4029. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4030. val, ok = grid_add_popup.get_value()
  4031. if ok:
  4032. if float(val) == 0:
  4033. self.inform.emit(
  4034. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4035. return
  4036. else:
  4037. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4038. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4039. self.inform.emit(
  4040. _("[success] New Grid added ..."))
  4041. else:
  4042. self.inform.emit(
  4043. _("[WARNING_NOTCL] Grid already exists ..."))
  4044. else:
  4045. self.inform.emit(
  4046. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4047. def on_grid_delete(self):
  4048. ## Current application units in lower Case
  4049. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4050. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4051. text='Enter a Grid Value:',
  4052. min=0.0000, max=99.9999, decimals=4)
  4053. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4054. val, ok = grid_del_popup.get_value()
  4055. if ok:
  4056. if float(val) == 0:
  4057. self.inform.emit(
  4058. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4059. return
  4060. else:
  4061. try:
  4062. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4063. except ValueError:
  4064. self.inform.emit(
  4065. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4066. return
  4067. self.inform.emit(
  4068. _("[success] Grid Value deleted ..."))
  4069. else:
  4070. self.inform.emit(
  4071. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4072. def on_shortcut_list(self):
  4073. self.report_usage("on_shortcut_list()")
  4074. # add the tab if it was closed
  4075. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  4076. # delete the absolute and relative position and messages in the infobar
  4077. self.ui.position_label.setText("")
  4078. self.ui.rel_position_label.setText("")
  4079. # Switch plot_area to preferences page
  4080. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4081. self.ui.show()
  4082. def on_select_tab(self, name):
  4083. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4084. if self.ui.splitter.sizes()[0] == 0:
  4085. self.ui.splitter.setSizes([1, 1])
  4086. else:
  4087. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4088. self.ui.splitter.setSizes([0, 1])
  4089. if name == 'project':
  4090. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4091. elif name == 'selected':
  4092. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4093. elif name == 'tool':
  4094. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4095. def on_copy_name(self):
  4096. self.report_usage("on_copy_name()")
  4097. obj = self.collection.get_active()
  4098. try:
  4099. name = obj.options["name"]
  4100. except AttributeError:
  4101. log.debug("on_copy_name() --> No object selected to copy it's name")
  4102. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4103. return
  4104. self.clipboard.setText(name)
  4105. self.inform.emit(_("Name copied on clipboard ..."))
  4106. def on_mouse_click_over_plot(self, event):
  4107. """
  4108. Default actions are:
  4109. :param event: Contains information about the event, like which button
  4110. was clicked, the pixel coordinates and the axes coordinates.
  4111. :return: None
  4112. """
  4113. self.pos = []
  4114. # So it can receive key presses
  4115. self.plotcanvas.vispy_canvas.native.setFocus()
  4116. # Set the mouse button for panning
  4117. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  4118. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4119. if self.grid_status() == True:
  4120. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4121. self.app_cursor.enabled = True
  4122. else:
  4123. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4124. self.app_cursor.enabled = False
  4125. try:
  4126. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4127. if event.button == 1:
  4128. # Reset here the relative coordinates so there is a new reference on the click position
  4129. if self.rel_point1 is None:
  4130. self.rel_point1 = self.pos
  4131. else:
  4132. self.rel_point2 = copy(self.rel_point1)
  4133. self.rel_point1 = self.pos
  4134. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4135. if modifiers == QtCore.Qt.ShiftModifier:
  4136. # do not auto open the Project Tab
  4137. self.click_noproject = True
  4138. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  4139. return
  4140. self.on_mouse_move_over_plot(event, origin_click=True)
  4141. except Exception as e:
  4142. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4143. def on_double_click_over_plot(self, event):
  4144. self.doubleclick = True
  4145. def on_mouse_move_over_plot(self, event, origin_click=None):
  4146. """
  4147. Callback for the mouse motion event over the plot. This event is generated
  4148. by the Matplotlib backend and has been registered in ``self.__init__()``.
  4149. For details, see: http://matplotlib.org/users/event_handling.html
  4150. :param event: Contains information about the event.
  4151. :param origin_click
  4152. :return: None
  4153. """
  4154. # So it can receive key presses
  4155. self.plotcanvas.vispy_canvas.native.setFocus()
  4156. self.pos_jump = event.pos
  4157. if origin_click is True:
  4158. pass
  4159. else:
  4160. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4161. if event.button == 2:
  4162. self.panning_action = True
  4163. return
  4164. else:
  4165. self.panning_action = False
  4166. if self.rel_point1 is not None:
  4167. try: # May fail in case mouse not within axes
  4168. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4169. if self.grid_status():
  4170. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4171. self.app_cursor.enabled = True
  4172. # Update cursor
  4173. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  4174. else:
  4175. pos = (pos_canvas[0], pos_canvas[1])
  4176. self.app_cursor.enabled = False
  4177. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4178. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  4179. dx = pos[0] - self.rel_point1[0]
  4180. dy = pos[1] - self.rel_point1[1]
  4181. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4182. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4183. self.mouse = [pos[0], pos[1]]
  4184. # if the mouse is moved and the LMB is clicked then the action is a selection
  4185. if event.is_dragging == 1 and event.button == 1:
  4186. self.delete_selection_shape()
  4187. if dx < 0:
  4188. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4189. face_color=self.defaults['global_alt_sel_fill'])
  4190. self.selection_type = False
  4191. else:
  4192. self.draw_moving_selection_shape(self.pos, pos)
  4193. self.selection_type = True
  4194. # hover effect - enabled in Preferences -> General -> GUI Settings
  4195. if self.defaults['global_hover']:
  4196. for obj in self.collection.get_list():
  4197. try:
  4198. # select the object(s) only if it is enabled (plotted)
  4199. if obj.options['plot']:
  4200. if obj not in self.collection.get_selected():
  4201. poly_obj = Polygon(
  4202. [(obj.options['xmin'], obj.options['ymin']),
  4203. (obj.options['xmax'], obj.options['ymin']),
  4204. (obj.options['xmax'], obj.options['ymax']),
  4205. (obj.options['xmin'], obj.options['ymax'])]
  4206. )
  4207. if Point(pos).within(poly_obj):
  4208. if obj.isHovering is False:
  4209. obj.isHovering = True
  4210. obj.notHovering = True
  4211. # create the selection box around the selected object
  4212. self.draw_hover_shape(obj, color='#d1e0e0')
  4213. else:
  4214. if obj.notHovering is True:
  4215. obj.notHovering = False
  4216. obj.isHovering = False
  4217. self.delete_hover_shape()
  4218. except:
  4219. # the Exception here will happen if we try to select on screen and we have an
  4220. # newly (and empty) just created Geometry or Excellon object that do not have the
  4221. # xmin, xmax, ymin, ymax options.
  4222. # In this case poly_obj creation (see above) will fail
  4223. pass
  4224. except:
  4225. self.ui.position_label.setText("")
  4226. self.ui.rel_position_label.setText("")
  4227. self.mouse = None
  4228. def on_mouse_click_release_over_plot(self, event):
  4229. """
  4230. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4231. and has been registered in ''self.__init__()''.
  4232. :param event: contains information about the event.
  4233. :return:
  4234. """
  4235. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4236. if self.grid_status():
  4237. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4238. else:
  4239. pos = (pos_canvas[0], pos_canvas[1])
  4240. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4241. # canvas menu
  4242. try:
  4243. if event.button == 2: # right click
  4244. if self.panning_action is True:
  4245. self.panning_action = False
  4246. else:
  4247. self.cursor = QtGui.QCursor()
  4248. self.populate_cmenu_grids()
  4249. self.ui.popMenu.popup(self.cursor.pos())
  4250. except Exception as e:
  4251. log.warning("Error: %s" % str(e))
  4252. return
  4253. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4254. # selection and then select a type of selection ("enclosing" or "touching")
  4255. try:
  4256. if event.button == 1: # left click
  4257. if self.doubleclick is True:
  4258. self.doubleclick = False
  4259. if self.collection.get_selected():
  4260. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4261. if self.ui.splitter.sizes()[0] == 0:
  4262. self.ui.splitter.setSizes([1, 1])
  4263. # delete the selection shape(S) as it may be in the way
  4264. self.delete_selection_shape()
  4265. self.delete_hover_shape()
  4266. else:
  4267. if self.selection_type is not None:
  4268. self.selection_area_handler(self.pos, pos, self.selection_type)
  4269. self.selection_type = None
  4270. else:
  4271. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4272. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  4273. # and if it's not selected then it will be selected
  4274. if modifiers == QtCore.Qt.ControlModifier:
  4275. # If there is no active command (self.command_active is None) then we check if we clicked on
  4276. # a object by checking the bounding limits against mouse click position
  4277. if self.command_active is None:
  4278. self.select_objects(key='CTRL')
  4279. self.delete_hover_shape()
  4280. else:
  4281. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  4282. # checking the bounding limits against mouse click position
  4283. if self.command_active is None:
  4284. self.select_objects()
  4285. self.delete_hover_shape()
  4286. except Exception as e:
  4287. log.warning("Error: %s" % str(e))
  4288. return
  4289. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4290. """
  4291. :param start_pos: mouse position when the selection LMB click was done
  4292. :param end_pos: mouse position when the left mouse button is released
  4293. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4294. :return:
  4295. """
  4296. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4297. self.delete_selection_shape()
  4298. for obj in self.collection.get_list():
  4299. try:
  4300. # select the object(s) only if it is enabled (plotted)
  4301. if obj.options['plot']:
  4302. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4303. (obj.options['xmax'], obj.options['ymin']),
  4304. (obj.options['xmax'], obj.options['ymax']),
  4305. (obj.options['xmin'], obj.options['ymax'])])
  4306. if sel_type is True:
  4307. if poly_obj.within(poly_selection):
  4308. # create the selection box around the selected object
  4309. self.draw_selection_shape(obj)
  4310. self.collection.set_active(obj.options['name'])
  4311. else:
  4312. if poly_selection.intersects(poly_obj):
  4313. # create the selection box around the selected object
  4314. self.draw_selection_shape(obj)
  4315. self.collection.set_active(obj.options['name'])
  4316. except:
  4317. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4318. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4319. # In this case poly_obj creation (see above) will fail
  4320. pass
  4321. def select_objects(self, key=None):
  4322. # list where we store the overlapped objects under our mouse left click position
  4323. objects_under_the_click_list = []
  4324. # Populate the list with the overlapped objects on the click position
  4325. curr_x, curr_y = self.pos
  4326. for obj in self.all_objects_list:
  4327. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4328. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4329. if obj.options['name'] not in objects_under_the_click_list:
  4330. if obj.options['plot']:
  4331. # add objects to the objects_under_the_click list only if the object is plotted
  4332. # (active and not disabled)
  4333. objects_under_the_click_list.append(obj.options['name'])
  4334. try:
  4335. # If there is no element in the overlapped objects list then make everyone inactive
  4336. # because we selected "nothing"
  4337. if not objects_under_the_click_list:
  4338. self.collection.set_all_inactive()
  4339. # delete the possible selection box around a possible selected object
  4340. self.delete_selection_shape()
  4341. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4342. # only when working on App
  4343. if self.call_source == 'app':
  4344. if self.click_noproject is False:
  4345. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4346. else:
  4347. # restore auto open the Project Tab
  4348. self.click_noproject = False
  4349. # delete any text in the status bar, implicitly the last object name that was selected
  4350. self.inform.emit("")
  4351. else:
  4352. self.call_source = 'app'
  4353. else:
  4354. # case when there is only an object under the click and we toggle it
  4355. if len(objects_under_the_click_list) == 1:
  4356. if self.collection.get_active() is None :
  4357. self.collection.set_active(objects_under_the_click_list[0])
  4358. # create the selection box around the selected object
  4359. curr_sel_obj = self.collection.get_active()
  4360. self.draw_selection_shape(curr_sel_obj)
  4361. # self.inform.emit('[selected] %s: %s selected' %
  4362. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4363. if curr_sel_obj.kind == 'gerber':
  4364. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4365. color='green', name=str(curr_sel_obj.options['name'])))
  4366. elif curr_sel_obj.kind == 'excellon':
  4367. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4368. color='brown', name=str(curr_sel_obj.options['name'])))
  4369. elif curr_sel_obj.kind == 'cncjob':
  4370. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4371. color='blue', name=str(curr_sel_obj.options['name'])))
  4372. elif curr_sel_obj.kind == 'geometry':
  4373. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4374. color='red', name=str(curr_sel_obj.options['name'])))
  4375. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4376. self.collection.set_all_inactive()
  4377. self.delete_selection_shape()
  4378. self.collection.set_active(objects_under_the_click_list[0])
  4379. # create the selection box around the selected object
  4380. curr_sel_obj = self.collection.get_active()
  4381. self.draw_selection_shape(curr_sel_obj)
  4382. # self.inform.emit('[selected] %s: %s selected' %
  4383. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4384. if curr_sel_obj.kind == 'gerber':
  4385. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4386. color='green', name=str(curr_sel_obj.options['name'])))
  4387. elif curr_sel_obj.kind == 'excellon':
  4388. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4389. color='brown', name=str(curr_sel_obj.options['name'])))
  4390. elif curr_sel_obj.kind == 'cncjob':
  4391. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4392. color='blue', name=str(curr_sel_obj.options['name'])))
  4393. elif curr_sel_obj.kind == 'geometry':
  4394. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4395. color='red', name=str(curr_sel_obj.options['name'])))
  4396. else:
  4397. self.collection.set_all_inactive()
  4398. self.delete_selection_shape()
  4399. if self.call_source == 'app':
  4400. # delete any text in the status bar, implicitly the last object name that was selected
  4401. self.inform.emit("")
  4402. else:
  4403. self.call_source = 'app'
  4404. else:
  4405. # If there is no selected object
  4406. # make active the first element of the overlapped objects list
  4407. if self.collection.get_active() is None:
  4408. self.collection.set_active(objects_under_the_click_list[0])
  4409. name_sel_obj = self.collection.get_active().options['name']
  4410. # In case that there is a selected object but it is not in the overlapped object list
  4411. # make that object inactive and activate the first element in the overlapped object list
  4412. if name_sel_obj not in objects_under_the_click_list:
  4413. self.collection.set_inactive(name_sel_obj)
  4414. name_sel_obj = objects_under_the_click_list[0]
  4415. self.collection.set_active(name_sel_obj)
  4416. else:
  4417. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4418. self.collection.set_all_inactive()
  4419. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4420. len(objects_under_the_click_list)])
  4421. curr_sel_obj = self.collection.get_active()
  4422. # delete the possible selection box around a possible selected object
  4423. self.delete_selection_shape()
  4424. # create the selection box around the selected object
  4425. self.draw_selection_shape(curr_sel_obj)
  4426. # self.inform.emit('[selected] %s: %s selected' %
  4427. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4428. if curr_sel_obj.kind == 'gerber':
  4429. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4430. color='green', name=str(curr_sel_obj.options['name'])))
  4431. elif curr_sel_obj.kind == 'excellon':
  4432. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4433. color='brown', name=str(curr_sel_obj.options['name'])))
  4434. elif curr_sel_obj.kind == 'cncjob':
  4435. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4436. color='blue', name=str(curr_sel_obj.options['name'])))
  4437. elif curr_sel_obj.kind == 'geometry':
  4438. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4439. color='red', name=str(curr_sel_obj.options['name'])))
  4440. # for obj in self.collection.get_list():
  4441. # obj.plot()
  4442. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4443. # TODO: on selected objects change the object colors and do not draw the selection box
  4444. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4445. except Exception as e:
  4446. log.error("[ERROR] Something went bad. %s" % str(e))
  4447. return
  4448. def delete_hover_shape(self):
  4449. self.hover_shapes.clear()
  4450. self.hover_shapes.redraw()
  4451. def draw_hover_shape(self, sel_obj, color=None):
  4452. """
  4453. :param sel_obj: the object for which the hover shape must be drawn
  4454. :return:
  4455. """
  4456. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4457. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4458. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4459. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4460. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4461. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4462. hover_rect = hover_rect.buffer(-0.1)
  4463. hover_rect = hover_rect.buffer(0.2)
  4464. else:
  4465. hover_rect = hover_rect.buffer(-0.00393)
  4466. hover_rect = hover_rect.buffer(0.00787)
  4467. if color:
  4468. face = Color(color)
  4469. face.alpha = 0.2
  4470. outline = Color(color, alpha=0.8)
  4471. else:
  4472. face = Color(self.defaults['global_sel_fill'])
  4473. face.alpha = 0.2
  4474. outline = self.defaults['global_sel_line']
  4475. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4476. def delete_selection_shape(self):
  4477. self.move_tool.sel_shapes.clear()
  4478. self.move_tool.sel_shapes.redraw()
  4479. def draw_selection_shape(self, sel_obj, color=None):
  4480. """
  4481. :param sel_obj: the object for which the selection shape must be drawn
  4482. :return:
  4483. """
  4484. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4485. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4486. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4487. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4488. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4489. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4490. sel_rect = sel_rect.buffer(-0.1)
  4491. sel_rect = sel_rect.buffer(0.2)
  4492. else:
  4493. sel_rect = sel_rect.buffer(-0.00393)
  4494. sel_rect = sel_rect.buffer(0.00787)
  4495. if color:
  4496. face = Color(color, alpha=0.2)
  4497. outline = Color(color, alpha=0.8)
  4498. else:
  4499. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4500. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4501. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4502. face_color=face, update=True, layer=0, tolerance=None))
  4503. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4504. """
  4505. :param old_coords: old coordinates
  4506. :param coords: new coordinates
  4507. :return:
  4508. """
  4509. if 'color' in kwargs:
  4510. color = kwargs['color']
  4511. else:
  4512. color = self.defaults['global_sel_line']
  4513. if 'face_color' in kwargs:
  4514. face_color = kwargs['face_color']
  4515. else:
  4516. face_color = self.defaults['global_sel_fill']
  4517. x0, y0 = old_coords
  4518. x1, y1 = coords
  4519. pt1 = (x0, y0)
  4520. pt2 = (x1, y0)
  4521. pt3 = (x1, y1)
  4522. pt4 = (x0, y1)
  4523. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4524. color_t = Color(face_color)
  4525. color_t.alpha = 0.3
  4526. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4527. layer=0, tolerance=None)
  4528. def on_file_new_click(self):
  4529. if self.collection.get_list() and self.should_we_save:
  4530. msgbox = QtWidgets.QMessageBox()
  4531. # msgbox.setText("<B>Save changes ...</B>")
  4532. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4533. "Creating a New project will delete them.\n"
  4534. "Do you want to Save the project?"))
  4535. msgbox.setWindowTitle(_("Save changes"))
  4536. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4537. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  4538. QtWidgets.QMessageBox.No)
  4539. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4540. response = msgbox.exec_()
  4541. if response == QtWidgets.QMessageBox.Yes:
  4542. self.on_file_saveprojectas()
  4543. elif response == QtWidgets.QMessageBox.Cancel:
  4544. return
  4545. self.on_file_new()
  4546. else:
  4547. self.on_file_new()
  4548. self.inform.emit(_("[success] New Project created..."))
  4549. def on_file_new(self):
  4550. """
  4551. Callback for menu item File->New. Returns the application to its
  4552. startup state. This method is thread-safe.
  4553. :return: None
  4554. """
  4555. self.report_usage("on_file_new")
  4556. # Remove everything from memory
  4557. App.log.debug("on_file_new()")
  4558. if self.call_source != 'app':
  4559. self.editor2object(cleanup=True)
  4560. ### EDITOR section
  4561. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  4562. self.exc_editor = FlatCAMExcEditor(self)
  4563. self.grb_editor = FlatCAMGrbEditor(self)
  4564. # Clear pool
  4565. self.clear_pool()
  4566. #delete shapes left drawn from mark shape_collections, if any
  4567. for obj in self.collection.get_list():
  4568. try:
  4569. obj.mark_shapes.enabled = False
  4570. obj.mark_shapes.clear(update=True)
  4571. except:
  4572. pass
  4573. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4574. self.init_tcl()
  4575. self.delete_selection_shape()
  4576. self.collection.delete_all()
  4577. self.setup_component_editor()
  4578. # Clear project filename
  4579. self.project_filename = None
  4580. # Load the application defaults
  4581. self.load_defaults(filename='current_defaults')
  4582. # Re-fresh project options
  4583. self.on_options_app2project()
  4584. # Init Tools
  4585. self.init_tools()
  4586. # Close any Tabs opened in the Plot Tab Area section
  4587. for index in range(self.ui.plot_tab_area.count()):
  4588. self.ui.plot_tab_area.closeTab(index)
  4589. # for whatever reason previous command does not close the last tab so I do it manually
  4590. self.ui.plot_tab_area.closeTab(0)
  4591. # # And then add again the Plot Area
  4592. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4593. self.ui.plot_tab_area.protectTab(0)
  4594. # take the focus of the Notebook on Project Tab.
  4595. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4596. def obj_properties(self):
  4597. self.report_usage("obj_properties()")
  4598. self.properties_tool.run(toggle=False)
  4599. def on_project_context_save(self):
  4600. obj = self.collection.get_active()
  4601. if type(obj) == FlatCAMGeometry:
  4602. self.on_file_exportdxf()
  4603. elif type(obj) == FlatCAMExcellon:
  4604. self.on_file_saveexcellon()
  4605. elif type(obj) == FlatCAMCNCjob:
  4606. obj.on_exportgcode_button_click()
  4607. elif type(obj) == FlatCAMGerber:
  4608. self.on_file_savegerber()
  4609. def obj_move(self):
  4610. self.report_usage("obj_move()")
  4611. self.move_tool.run()
  4612. def on_fileopengerber(self):
  4613. """
  4614. File menu callback for opening a Gerber.
  4615. :return: None
  4616. """
  4617. self.report_usage("on_fileopengerber")
  4618. App.log.debug("on_fileopengerber()")
  4619. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4620. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4621. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  4622. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4623. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4624. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4625. "Allegro Files (*.art);;" \
  4626. "Mentor Files (*.pho *.gdo);;" \
  4627. "All Files (*.*)"
  4628. try:
  4629. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4630. directory=self.get_last_folder(), filter=_filter_)
  4631. except TypeError:
  4632. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4633. filenames = [str(filename) for filename in filenames]
  4634. if len(filenames) == 0:
  4635. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4636. else:
  4637. for filename in filenames:
  4638. if filename != '':
  4639. self.worker_task.emit({'fcn': self.open_gerber,
  4640. 'params': [filename]})
  4641. def on_fileopenexcellon(self):
  4642. """
  4643. File menu callback for opening an Excellon file.
  4644. :return: None
  4645. """
  4646. self.report_usage("on_fileopenexcellon")
  4647. App.log.debug("on_fileopenexcellon()")
  4648. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4649. "All Files (*.*)"
  4650. try:
  4651. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4652. directory=self.get_last_folder(), filter=_filter_)
  4653. except TypeError:
  4654. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4655. filenames = [str(filename) for filename in filenames]
  4656. if len(filenames) == 0:
  4657. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  4658. else:
  4659. for filename in filenames:
  4660. if filename != '':
  4661. self.worker_task.emit({'fcn': self.open_excellon,
  4662. 'params': [filename]})
  4663. def on_fileopengcode(self):
  4664. """
  4665. File menu call back for opening gcode.
  4666. :return: None
  4667. """
  4668. self.report_usage("on_fileopengcode")
  4669. App.log.debug("on_fileopengcode()")
  4670. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4671. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4672. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4673. "All Files (*.*)"
  4674. try:
  4675. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  4676. directory=self.get_last_folder(), filter=_filter_)
  4677. except TypeError:
  4678. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  4679. filenames = [str(filename) for filename in filenames]
  4680. if len(filenames) == 0:
  4681. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  4682. else:
  4683. for filename in filenames:
  4684. if filename != '':
  4685. self.worker_task.emit({'fcn': self.open_gcode,
  4686. 'params': [filename]})
  4687. def on_file_openproject(self):
  4688. """
  4689. File menu callback for opening a project.
  4690. :return: None
  4691. """
  4692. self.report_usage("on_file_openproject")
  4693. App.log.debug("on_file_openproject()")
  4694. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4695. try:
  4696. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  4697. directory=self.get_last_folder(), filter=_filter_)
  4698. except TypeError:
  4699. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  4700. # The Qt methods above will return a QString which can cause problems later.
  4701. # So far json.dump() will fail to serialize it.
  4702. # TODO: Improve the serialization methods and remove this fix.
  4703. filename = str(filename)
  4704. if filename == "":
  4705. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  4706. else:
  4707. # self.worker_task.emit({'fcn': self.open_project,
  4708. # 'params': [filename]})
  4709. # The above was failing because open_project() is not
  4710. # thread safe. The new_project()
  4711. self.open_project(filename)
  4712. def on_file_openconfig(self):
  4713. """
  4714. File menu callback for opening a config file.
  4715. :return: None
  4716. """
  4717. self.report_usage("on_file_openconfig")
  4718. App.log.debug("on_file_openconfig()")
  4719. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  4720. try:
  4721. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4722. directory=self.data_path, filter=_filter_)
  4723. except TypeError:
  4724. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4725. filter = _filter_)
  4726. if filename == "":
  4727. self.inform.emit(_("[WARNING_NOTCL Open Config cancelled."))
  4728. else:
  4729. self.open_config_file(filename)
  4730. def on_file_exportsvg(self):
  4731. """
  4732. Callback for menu item File->Export SVG.
  4733. :return: None
  4734. """
  4735. self.report_usage("on_file_exportsvg")
  4736. App.log.debug("on_file_exportsvg()")
  4737. obj = self.collection.get_active()
  4738. if obj is None:
  4739. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4740. msg = _("Please Select a Geometry object to export")
  4741. msgbox = QtWidgets.QMessageBox()
  4742. msgbox.setInformativeText(msg)
  4743. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4744. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4745. msgbox.exec_()
  4746. return
  4747. # Check for more compatible types and add as required
  4748. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4749. and not isinstance(obj, FlatCAMExcellon)):
  4750. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  4751. msgbox = QtWidgets.QMessageBox()
  4752. msgbox.setInformativeText(msg)
  4753. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4754. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4755. msgbox.exec_()
  4756. return
  4757. name = self.collection.get_active().options["name"]
  4758. filter = "SVG File (*.svg);;All Files (*.*)"
  4759. try:
  4760. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4761. caption=_("Export SVG"),
  4762. directory=self.get_last_save_folder() + '/' + str(name),
  4763. filter=filter)
  4764. except TypeError:
  4765. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  4766. filename = str(filename)
  4767. if filename == "":
  4768. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  4769. return
  4770. else:
  4771. self.export_svg(name, filename)
  4772. self.file_saved.emit("SVG", filename)
  4773. def on_file_exportpng(self):
  4774. self.report_usage("on_file_exportpng")
  4775. App.log.debug("on_file_exportpng()")
  4776. image = _screenshot()
  4777. data = np.asarray(image)
  4778. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4779. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  4780. return
  4781. filter_ = "PNG File (*.png);;All Files (*.*)"
  4782. try:
  4783. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4784. caption=_("Export PNG Image"),
  4785. directory=self.get_last_save_folder() + '/png_' + self.date,
  4786. filter=filter_)
  4787. except TypeError:
  4788. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  4789. filename = str(filename)
  4790. if filename == "":
  4791. self.inform.emit(_("Export PNG cancelled."))
  4792. return
  4793. else:
  4794. write_png(filename, data)
  4795. self.file_saved.emit("png", filename)
  4796. def on_file_savegerber(self):
  4797. """
  4798. Callback for menu item File->Export Gerber.
  4799. :return: None
  4800. """
  4801. self.report_usage("on_file_savegerber")
  4802. App.log.debug("on_file_savegerber()")
  4803. obj = self.collection.get_active()
  4804. if obj is None:
  4805. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  4806. return
  4807. # Check for more compatible types and add as required
  4808. if not isinstance(obj, FlatCAMGerber):
  4809. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  4810. return
  4811. name = self.collection.get_active().options["name"]
  4812. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  4813. try:
  4814. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4815. caption="Save Gerber source file",
  4816. directory=self.get_last_save_folder() + '/' + name,
  4817. filter=filter)
  4818. except TypeError:
  4819. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  4820. filename = str(filename)
  4821. if filename == "":
  4822. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  4823. return
  4824. else:
  4825. self.save_source_file(name, filename)
  4826. self.file_saved.emit("Gerber", filename)
  4827. def on_file_saveexcellon(self):
  4828. """
  4829. Callback for menu item File->Export Gerber.
  4830. :return: None
  4831. """
  4832. self.report_usage("on_file_saveexcellon")
  4833. App.log.debug("on_file_saveexcellon()")
  4834. obj = self.collection.get_active()
  4835. if obj is None:
  4836. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  4837. return
  4838. # Check for more compatible types and add as required
  4839. if not isinstance(obj, FlatCAMExcellon):
  4840. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4841. return
  4842. name = self.collection.get_active().options["name"]
  4843. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4844. try:
  4845. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4846. caption=_("Save Excellon source file"),
  4847. directory=self.get_last_save_folder() + '/' + name,
  4848. filter=filter)
  4849. except TypeError:
  4850. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  4851. filename = str(filename)
  4852. if filename == "":
  4853. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  4854. return
  4855. else:
  4856. self.save_source_file(name, filename)
  4857. self.file_saved.emit("Excellon", filename)
  4858. def on_file_exportexcellon(self):
  4859. """
  4860. Callback for menu item File->Export SVG.
  4861. :return: None
  4862. """
  4863. self.report_usage("on_file_exportexcellon")
  4864. App.log.debug("on_file_exportexcellon()")
  4865. obj = self.collection.get_active()
  4866. if obj is None:
  4867. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  4868. return
  4869. # Check for more compatible types and add as required
  4870. if not isinstance(obj, FlatCAMExcellon):
  4871. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4872. return
  4873. name = self.collection.get_active().options["name"]
  4874. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4875. try:
  4876. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4877. caption=_("Export Excellon"),
  4878. directory=self.get_last_save_folder() + '/' + name,
  4879. filter=filter)
  4880. except TypeError:
  4881. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  4882. filename = str(filename)
  4883. if filename == "":
  4884. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  4885. return
  4886. else:
  4887. self.export_excellon(name, filename)
  4888. self.file_saved.emit("Excellon", filename)
  4889. def on_file_exportdxf(self):
  4890. """
  4891. Callback for menu item File->Export DXF.
  4892. :return: None
  4893. """
  4894. self.report_usage("on_file_exportdxf")
  4895. App.log.debug("on_file_exportdxf()")
  4896. obj = self.collection.get_active()
  4897. if obj is None:
  4898. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4899. msg = _("Please Select a Geometry object to export")
  4900. msgbox = QtWidgets.QMessageBox()
  4901. msgbox.setInformativeText(msg)
  4902. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4903. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4904. msgbox.exec_()
  4905. return
  4906. # Check for more compatible types and add as required
  4907. if not isinstance(obj, FlatCAMGeometry):
  4908. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  4909. msgbox = QtWidgets.QMessageBox()
  4910. msgbox.setInformativeText(msg)
  4911. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4912. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4913. msgbox.exec_()
  4914. return
  4915. name = self.collection.get_active().options["name"]
  4916. filter = "DXF File (*.DXF);;All Files (*.*)"
  4917. try:
  4918. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4919. caption=_("Export DXF"),
  4920. directory=self.get_last_save_folder() + '/' + name,
  4921. filter=filter)
  4922. except TypeError:
  4923. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"), filter=filter)
  4924. filename = str(filename)
  4925. if filename == "":
  4926. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  4927. return
  4928. else:
  4929. self.export_dxf(name, filename)
  4930. self.file_saved.emit("DXF", filename)
  4931. def on_file_importsvg(self, type_of_obj):
  4932. """
  4933. Callback for menu item File->Import SVG.
  4934. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4935. :type type_of_obj: str
  4936. :return: None
  4937. """
  4938. self.report_usage("on_file_importsvg")
  4939. App.log.debug("on_file_importsvg()")
  4940. filter = "SVG File (*.svg);;All Files (*.*)"
  4941. try:
  4942. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  4943. directory=self.get_last_folder(), filter=filter)
  4944. except TypeError:
  4945. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"), filter=filter)
  4946. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4947. type_of_obj = "geometry"
  4948. filenames = [str(filename) for filename in filenames]
  4949. if len(filenames) == 0:
  4950. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  4951. else:
  4952. for filename in filenames:
  4953. if filename != '':
  4954. self.worker_task.emit({'fcn': self.import_svg,
  4955. 'params': [filename, type_of_obj]})
  4956. def on_file_importdxf(self, type_of_obj):
  4957. """
  4958. Callback for menu item File->Import DXF.
  4959. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4960. :type type_of_obj: str
  4961. :return: None
  4962. """
  4963. self.report_usage("on_file_importdxf")
  4964. App.log.debug("on_file_importdxf()")
  4965. filter = "DXF File (*.DXF);;All Files (*.*)"
  4966. try:
  4967. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  4968. directory=self.get_last_folder(), filter=filter)
  4969. except TypeError:
  4970. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"), filter=filter)
  4971. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4972. type_of_obj = "geometry"
  4973. filenames = [str(filename) for filename in filenames]
  4974. if len(filenames) == 0:
  4975. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  4976. else:
  4977. for filename in filenames:
  4978. if filename != '':
  4979. self.worker_task.emit({'fcn': self.import_dxf,
  4980. 'params': [filename, type_of_obj]})
  4981. ###################################################################################################################
  4982. ### The following section has the functions that are displayed are call the Editoe tab CNCJob Tab #################
  4983. ###################################################################################################################
  4984. def init_code_editor(self, name):
  4985. # Signals section
  4986. # Disconnect the old signals
  4987. self.ui.buttonOpen.clicked.disconnect()
  4988. self.ui.buttonSave.clicked.disconnect()
  4989. # add the tab if it was closed
  4990. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  4991. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  4992. # delete the absolute and relative position and messages in the infobar
  4993. self.ui.position_label.setText("")
  4994. self.ui.rel_position_label.setText("")
  4995. # first clear previous text in text editor (if any)
  4996. self.ui.code_editor.clear()
  4997. self.ui.code_editor.setReadOnly(False)
  4998. self.toggle_codeeditor = True
  4999. self.ui.code_editor.completer_enable = False
  5000. # Switch plot_area to CNCJob tab
  5001. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5002. def on_view_source(self):
  5003. try:
  5004. obj = self.collection.get_active()
  5005. except:
  5006. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5007. return 'fail'
  5008. # then append the text from GCode to the text editor
  5009. try:
  5010. file = StringIO(obj.source_file)
  5011. except AttributeError:
  5012. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5013. return 'fail'
  5014. if obj.kind == 'gerber':
  5015. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5016. elif obj.kind == 'excellon':
  5017. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5018. self.init_code_editor(name=_("Source Editor"))
  5019. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5020. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5021. try:
  5022. for line in file:
  5023. proc_line = str(line).strip('\n')
  5024. self.ui.code_editor.append(proc_line)
  5025. except Exception as e:
  5026. log.debug('App.on_view_source() -->%s' % str(e))
  5027. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5028. return
  5029. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5030. self.handleTextChanged()
  5031. self.ui.show()
  5032. def on_toggle_code_editor(self):
  5033. self.report_usage("on_toggle_code_editor()")
  5034. if self.toggle_codeeditor is False:
  5035. self.init_code_editor(name=_("Code Editor"))
  5036. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  5037. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  5038. else:
  5039. for idx in range(self.ui.plot_tab_area.count()):
  5040. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  5041. self.ui.plot_tab_area.closeTab(idx)
  5042. break
  5043. self.toggle_codeeditor = False
  5044. def on_filenewscript(self):
  5045. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5046. self.init_code_editor(name=_("Script Editor"))
  5047. self.ui.code_editor.completer_enable = True
  5048. self.ui.code_editor.append(_(
  5049. "#\n"
  5050. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  5051. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  5052. "#\n\n"
  5053. "# FlatCAM commands list:\n"
  5054. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  5055. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  5056. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  5057. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  5058. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  5059. "# WriteGCode\n"
  5060. "#\n\n"
  5061. ))
  5062. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5063. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5064. self.handleTextChanged()
  5065. self.ui.code_editor.show()
  5066. def on_fileopenscript(self):
  5067. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5068. try:
  5069. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  5070. directory=self.get_last_folder(), filter=_filter_)
  5071. except TypeError:
  5072. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  5073. # The Qt methods above will return a QString which can cause problems later.
  5074. # So far json.dump() will fail to serialize it.
  5075. # TODO: Improve the serialization methods and remove this fix.
  5076. filename = str(filename)
  5077. if filename == "":
  5078. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  5079. else:
  5080. self.on_filenewscript()
  5081. try:
  5082. with open(filename, "r") as opened_script:
  5083. try:
  5084. for line in opened_script:
  5085. proc_line = str(line).strip('\n')
  5086. self.ui.code_editor.append(proc_line)
  5087. except Exception as e:
  5088. log.debug('App.on_fileopenscript() -->%s' % str(e))
  5089. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  5090. return
  5091. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5092. self.handleTextChanged()
  5093. self.ui.show()
  5094. except Exception as e:
  5095. log.debug("App.on_fileopenscript() -> %s" % str(e))
  5096. def on_filerunscript(self, name=None):
  5097. """
  5098. File menu callback for loading and running a TCL script.
  5099. :return: None
  5100. """
  5101. self.report_usage("on_filerunscript")
  5102. App.log.debug("on_file_runscript()")
  5103. if name:
  5104. filename = name
  5105. else:
  5106. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5107. try:
  5108. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  5109. directory=self.get_last_folder(), filter=_filter_)
  5110. except TypeError:
  5111. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  5112. # The Qt methods above will return a QString which can cause problems later.
  5113. # So far json.dump() will fail to serialize it.
  5114. # TODO: Improve the serialization methods and remove this fix.
  5115. filename = str(filename)
  5116. if filename == "":
  5117. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  5118. else:
  5119. try:
  5120. with open(filename, "r") as tcl_script:
  5121. cmd_line_shellfile_content = tcl_script.read()
  5122. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  5123. except Exception as e:
  5124. log.debug("App.on_filerunscript() -> %s" % str(e))
  5125. sys.exit(2)
  5126. def on_file_saveproject(self):
  5127. """
  5128. Callback for menu item File->Save Project. Saves the project to
  5129. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  5130. if set to None. The project is saved by calling ``self.save_project()``.
  5131. :return: None
  5132. """
  5133. self.report_usage("on_file_saveproject")
  5134. if self.project_filename is None:
  5135. self.on_file_saveprojectas()
  5136. else:
  5137. self.worker_task.emit({'fcn': self.save_project,
  5138. 'params': [self.project_filename]})
  5139. self.file_opened.emit("project", self.project_filename)
  5140. self.file_saved.emit("project", self.project_filename)
  5141. self.should_we_save = False
  5142. def on_file_saveprojectas(self, make_copy=False, thread=True, quit=False):
  5143. """
  5144. Callback for menu item File->Save Project As... Opens a file
  5145. chooser and saves the project to the given file via
  5146. ``self.save_project()``.
  5147. :return: None
  5148. """
  5149. self.report_usage("on_file_saveprojectas")
  5150. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  5151. try:
  5152. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5153. caption=_("Save Project As ..."),
  5154. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  5155. filter=filter_)
  5156. except TypeError:
  5157. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  5158. filename = str(filename)
  5159. if filename == '':
  5160. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  5161. return
  5162. try:
  5163. f = open(filename, 'r')
  5164. f.close()
  5165. exists = True
  5166. except IOError:
  5167. exists = False
  5168. if thread is True:
  5169. self.worker_task.emit({'fcn': self.save_project,
  5170. 'params': [filename, quit]})
  5171. else:
  5172. self.save_project(filename, quit)
  5173. # self.save_project(filename)
  5174. self.file_opened.emit("project", filename)
  5175. self.file_saved.emit("project", filename)
  5176. if not make_copy:
  5177. self.project_filename = filename
  5178. self.should_we_save = False
  5179. def export_svg(self, obj_name, filename, scale_factor=0.00):
  5180. """
  5181. Exports a Geometry Object to an SVG file.
  5182. :param filename: Path to the SVG file to save to.
  5183. :return:
  5184. """
  5185. self.report_usage("export_svg()")
  5186. if filename is None:
  5187. filename = self.defaults["global_last_save_folder"]
  5188. self.log.debug("export_svg()")
  5189. try:
  5190. obj = self.collection.get_by_name(str(obj_name))
  5191. except:
  5192. # TODO: The return behavior has not been established... should raise exception?
  5193. return "Could not retrieve object: %s" % obj_name
  5194. with self.proc_container.new(_("Exporting SVG")) as proc:
  5195. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5196. # Determine bounding area for svg export
  5197. bounds = obj.bounds()
  5198. size = obj.size()
  5199. # Convert everything to strings for use in the xml doc
  5200. svgwidth = str(size[0])
  5201. svgheight = str(size[1])
  5202. minx = str(bounds[0])
  5203. miny = str(bounds[1] - size[1])
  5204. uom = obj.units.lower()
  5205. # Add a SVG Header and footer to the svg output from shapely
  5206. # The transform flips the Y Axis so that everything renders
  5207. # properly within svg apps such as inkscape
  5208. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5209. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5210. svg_header += 'width="' + svgwidth + uom + '" '
  5211. svg_header += 'height="' + svgheight + uom + '" '
  5212. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  5213. svg_header += '<g transform="scale(1,-1)">'
  5214. svg_footer = '</g> </svg>'
  5215. svg_elem = svg_header + exported_svg + svg_footer
  5216. # Parse the xml through a xml parser just to add line feeds
  5217. # and to make it look more pretty for the output
  5218. svgcode = parse_xml_string(svg_elem)
  5219. with open(filename, 'w') as fp:
  5220. fp.write(svgcode.toprettyxml())
  5221. self.file_saved.emit("SVG", filename)
  5222. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5223. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  5224. """
  5225. Exports a Geometry Object to an SVG file in negative.
  5226. :param filename: Path to the SVG file to save to.
  5227. :param: use_thread: If True use threads
  5228. :type: Bool
  5229. :return:
  5230. """
  5231. self.report_usage("export_negative()")
  5232. if filename is None:
  5233. filename = self.defaults["global_last_save_folder"]
  5234. self.log.debug("export_svg() negative")
  5235. try:
  5236. obj = self.collection.get_by_name(str(obj_name))
  5237. except:
  5238. # TODO: The return behavior has not been established... should raise exception?
  5239. return "Could not retrieve object: %s" % obj_name
  5240. try:
  5241. box = self.collection.get_by_name(str(box_name))
  5242. except:
  5243. # TODO: The return behavior has not been established... should raise exception?
  5244. return "Could not retrieve object: %s" % box_name
  5245. if box is None:
  5246. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5247. box = obj
  5248. def make_negative_film():
  5249. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5250. self.progress.emit(40)
  5251. # Determine bounding area for svg export
  5252. bounds = box.bounds()
  5253. size = box.size()
  5254. uom = obj.units.lower()
  5255. # Convert everything to strings for use in the xml doc
  5256. svgwidth = str(size[0] + (2 * boundary))
  5257. svgheight = str(size[1] + (2 * boundary))
  5258. minx = str(bounds[0] - boundary)
  5259. miny = str(bounds[1] + boundary + size[1])
  5260. miny_rect = str(bounds[1] - boundary)
  5261. # Add a SVG Header and footer to the svg output from shapely
  5262. # The transform flips the Y Axis so that everything renders
  5263. # properly within svg apps such as inkscape
  5264. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5265. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5266. svg_header += 'width="' + svgwidth + uom + '" '
  5267. svg_header += 'height="' + svgheight + uom + '" '
  5268. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5269. svg_header += '>'
  5270. svg_header += '<g transform="scale(1,-1)">'
  5271. svg_footer = '</g> </svg>'
  5272. self.progress.emit(60)
  5273. # Change the attributes of the exported SVG
  5274. # We don't need stroke-width - wrong, we do when we have lines with certain width
  5275. # We set opacity to maximum
  5276. # We set the color to WHITE
  5277. root = ET.fromstring(exported_svg)
  5278. for child in root:
  5279. child.set('fill', '#FFFFFF')
  5280. child.set('opacity', '1.0')
  5281. child.set('stroke', '#FFFFFF')
  5282. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  5283. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  5284. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  5285. first_svg_elem_tag = 'rect'
  5286. first_svg_elem_attribs = {
  5287. 'x': minx,
  5288. 'y': miny_rect,
  5289. 'width': svgwidth,
  5290. 'height': svgheight,
  5291. 'id': 'neg_rect',
  5292. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  5293. }
  5294. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  5295. exported_svg = ET.tostring(root)
  5296. svg_elem = svg_header + str(exported_svg) + svg_footer
  5297. self.progress.emit(80)
  5298. # Parse the xml through a xml parser just to add line feeds
  5299. # and to make it look more pretty for the output
  5300. doc = parse_xml_string(svg_elem)
  5301. with open(filename, 'w') as fp:
  5302. fp.write(doc.toprettyxml())
  5303. self.progress.emit(100)
  5304. self.file_saved.emit("SVG", filename)
  5305. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5306. if use_thread is True:
  5307. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5308. def job_thread_film(app_obj):
  5309. try:
  5310. make_negative_film()
  5311. except Exception as e:
  5312. proc.done()
  5313. return
  5314. proc.done()
  5315. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5316. else:
  5317. make_negative_film()
  5318. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  5319. """
  5320. Exports a Geometry Object to an SVG file in negative.
  5321. :param filename: Path to the SVG file to save to.
  5322. :param: use_thread: If True use threads
  5323. :type: Bool
  5324. :return:
  5325. """
  5326. self.report_usage("export_svg_black()")
  5327. if filename is None:
  5328. filename = self.defaults["global_last_save_folder"]
  5329. self.log.debug("export_svg() black")
  5330. try:
  5331. obj = self.collection.get_by_name(str(obj_name))
  5332. except:
  5333. # TODO: The return behavior has not been established... should raise exception?
  5334. return "Could not retrieve object: %s" % obj_name
  5335. try:
  5336. box = self.collection.get_by_name(str(box_name))
  5337. except:
  5338. # TODO: The return behavior has not been established... should raise exception?
  5339. return "Could not retrieve object: %s" % box_name
  5340. if box is None:
  5341. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5342. box = obj
  5343. def make_black_film():
  5344. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5345. self.progress.emit(40)
  5346. # Change the attributes of the exported SVG
  5347. # We don't need stroke-width
  5348. # We set opacity to maximum
  5349. # We set the colour to WHITE
  5350. root = ET.fromstring(exported_svg)
  5351. for child in root:
  5352. child.set('fill', '#000000')
  5353. child.set('opacity', '1.0')
  5354. child.set('stroke', '#000000')
  5355. exported_svg = ET.tostring(root)
  5356. # Determine bounding area for svg export
  5357. bounds = box.bounds()
  5358. size = box.size()
  5359. # This contain the measure units
  5360. uom = obj.units.lower()
  5361. # Define a boundary around SVG of about 1.0mm (~39mils)
  5362. if uom in "mm":
  5363. boundary = 1.0
  5364. else:
  5365. boundary = 0.0393701
  5366. self.progress.emit(80)
  5367. # Convert everything to strings for use in the xml doc
  5368. svgwidth = str(size[0] + (2 * boundary))
  5369. svgheight = str(size[1] + (2 * boundary))
  5370. minx = str(bounds[0] - boundary)
  5371. miny = str(bounds[1] + boundary + size[1])
  5372. self.log.debug(minx)
  5373. self.log.debug(miny)
  5374. # Add a SVG Header and footer to the svg output from shapely
  5375. # The transform flips the Y Axis so that everything renders
  5376. # properly within svg apps such as inkscape
  5377. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5378. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5379. svg_header += 'width="' + svgwidth + uom + '" '
  5380. svg_header += 'height="' + svgheight + uom + '" '
  5381. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5382. svg_header += '>'
  5383. svg_header += '<g transform="scale(1,-1)">'
  5384. svg_footer = '</g> </svg>'
  5385. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5386. self.progress.emit(90)
  5387. # Parse the xml through a xml parser just to add line feeds
  5388. # and to make it look more pretty for the output
  5389. doc = parse_xml_string(svg_elem)
  5390. with open(filename, 'w') as fp:
  5391. fp.write(doc.toprettyxml())
  5392. self.progress.emit(100)
  5393. self.file_saved.emit("SVG", filename)
  5394. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5395. if use_thread is True:
  5396. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5397. def job_thread_film(app_obj):
  5398. try:
  5399. make_black_film()
  5400. except Exception as e:
  5401. proc.done()
  5402. return
  5403. proc.done()
  5404. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5405. else:
  5406. make_black_film()
  5407. def save_source_file(self, obj_name, filename, use_thread=True):
  5408. """
  5409. Exports a Gerber Object to an Gerber file.
  5410. :param filename: Path to the Gerber file to save to.
  5411. :return:
  5412. """
  5413. self.report_usage("save source file()")
  5414. if filename is None:
  5415. filename = self.defaults["global_last_save_folder"]
  5416. self.log.debug("save source file()")
  5417. obj = self.collection.get_by_name(obj_name)
  5418. file_string = StringIO(obj.source_file)
  5419. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5420. with open(filename, 'w') as file:
  5421. file.writelines('G04*\n')
  5422. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5423. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5424. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5425. file.writelines('G04 Created on : %s*\n' % time_string)
  5426. for line in file_string:
  5427. file.writelines(line)
  5428. def export_excellon(self, obj_name, filename, use_thread=True):
  5429. """
  5430. Exports a Excellon Object to an Excellon file.
  5431. :param filename: Path to the Excellon file to save to.
  5432. :return:
  5433. """
  5434. self.report_usage("export_excellon()")
  5435. if filename is None:
  5436. filename = self.defaults["global_last_save_folder"]
  5437. self.log.debug("export_excellon()")
  5438. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5439. self.defaults["excellon_exp_decimals"]
  5440. )
  5441. units = ''
  5442. try:
  5443. obj = self.collection.get_by_name(str(obj_name))
  5444. except:
  5445. # TODO: The return behavior has not been established... should raise exception?
  5446. return "Could not retrieve object: %s" % obj_name
  5447. # updated units
  5448. eunits = self.defaults["excellon_exp_units"]
  5449. ewhole = self.defaults["excellon_exp_integer"]
  5450. efract = self.defaults["excellon_exp_decimals"]
  5451. ezeros = self.defaults["excellon_exp_zeros"]
  5452. eformat = self.defaults[ "excellon_exp_format"]
  5453. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5454. if fc_units == 'MM':
  5455. factor = 1 if eunits == 'METRIC' else 0.03937
  5456. else:
  5457. factor = 25.4 if eunits == 'METRIC' else 1
  5458. def make_excellon():
  5459. try:
  5460. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5461. header = 'M48\n'
  5462. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5463. (str(self.version), str(self.version_date))
  5464. header += ';Filename: %s' % str(obj_name) + '\n'
  5465. header += ';Created on : %s' % time_str + '\n'
  5466. if eformat == 'dec':
  5467. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5468. header += eunits + '\n'
  5469. for tool in obj.tools:
  5470. if eunits == 'METRIC':
  5471. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5472. tool=str(tool),
  5473. dec=2)
  5474. else:
  5475. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5476. tool=str(tool),
  5477. dec=4)
  5478. else:
  5479. if ezeros == 'LZ':
  5480. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5481. form='ndec', e_zeros='LZ', factor=factor)
  5482. header += '%s,%s\n' % (eunits, 'LZ')
  5483. header += format_exc
  5484. for tool in obj.tools:
  5485. if eunits == 'METRIC':
  5486. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5487. tool=str(tool),
  5488. dec=2)
  5489. else:
  5490. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5491. tool=str(tool),
  5492. dec=4)
  5493. else:
  5494. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5495. form='ndec', e_zeros='TZ', factor=factor)
  5496. header += '%s,%s\n' % (eunits, 'TZ')
  5497. header += format_exc
  5498. for tool in obj.tools:
  5499. if eunits == 'METRIC':
  5500. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5501. tool=str(tool),
  5502. dec=2)
  5503. else:
  5504. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5505. tool=str(tool),
  5506. dec=4)
  5507. header += '%\n'
  5508. footer = 'M30\n'
  5509. exported_excellon = header
  5510. exported_excellon += excellon_code
  5511. exported_excellon += footer
  5512. with open(filename, 'w') as fp:
  5513. fp.write(exported_excellon)
  5514. self.file_saved.emit("Excellon", filename)
  5515. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5516. except Exception as e:
  5517. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5518. return 'fail'
  5519. if use_thread is True:
  5520. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5521. def job_thread_exc(app_obj):
  5522. ret = make_excellon()
  5523. if ret == 'fail':
  5524. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5525. return
  5526. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5527. else:
  5528. ret = make_excellon()
  5529. if ret == 'fail':
  5530. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5531. return
  5532. def export_dxf(self, obj_name, filename, use_thread=True):
  5533. """
  5534. Exports a Geometry Object to an DXF file.
  5535. :param filename: Path to the DXF file to save to.
  5536. :return:
  5537. """
  5538. self.report_usage("export_dxf()")
  5539. if filename is None:
  5540. filename = self.defaults["global_last_save_folder"]
  5541. self.log.debug("export_dxf()")
  5542. format_exc = ''
  5543. units = ''
  5544. try:
  5545. obj = self.collection.get_by_name(str(obj_name))
  5546. except:
  5547. # TODO: The return behavior has not been established... should raise exception?
  5548. return "Could not retrieve object: %s" % obj_name
  5549. # updated units
  5550. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5551. if units == 'IN' or units == 'INCH':
  5552. units = 'INCH'
  5553. elif units == 'MM' or units == 'METIRC':
  5554. units ='METRIC'
  5555. def make_dxf():
  5556. try:
  5557. dxf_code = obj.export_dxf()
  5558. dxf_code.saveas(filename)
  5559. self.file_saved.emit("DXF", filename)
  5560. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  5561. except:
  5562. return 'fail'
  5563. if use_thread is True:
  5564. with self.proc_container.new(_("Exporting DXF")) as proc:
  5565. def job_thread_exc(app_obj):
  5566. ret = make_dxf()
  5567. if ret == 'fail':
  5568. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5569. return
  5570. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5571. else:
  5572. ret = make_dxf()
  5573. if ret == 'fail':
  5574. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5575. return
  5576. def import_svg(self, filename, geo_type='geometry', outname=None):
  5577. """
  5578. Adds a new Geometry Object to the projects and populates
  5579. it with shapes extracted from the SVG file.
  5580. :param filename: Path to the SVG file.
  5581. :param outname:
  5582. :return:
  5583. """
  5584. self.report_usage("import_svg()")
  5585. obj_type = ""
  5586. if geo_type is None or geo_type == "geometry":
  5587. obj_type = "geometry"
  5588. elif geo_type == "gerber":
  5589. obj_type = geo_type
  5590. else:
  5591. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5592. "Only Geometry and Gerber are supported"))
  5593. return
  5594. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5595. def obj_init(geo_obj, app_obj):
  5596. geo_obj.import_svg(filename, obj_type, units=units)
  5597. geo_obj.multigeo = False
  5598. with self.proc_container.new(_("Importing SVG")) as proc:
  5599. # Object name
  5600. name = outname or filename.split('/')[-1].split('\\')[-1]
  5601. self.new_object(obj_type, name, obj_init, autoselected=False)
  5602. self.progress.emit(20)
  5603. # Register recent file
  5604. self.file_opened.emit("svg", filename)
  5605. # GUI feedback
  5606. self.inform.emit(_("[success] Opened: %s") % filename)
  5607. self.progress.emit(100)
  5608. def import_dxf(self, filename, geo_type='geometry', outname=None):
  5609. """
  5610. Adds a new Geometry Object to the projects and populates
  5611. it with shapes extracted from the DXF file.
  5612. :param filename: Path to the DXF file.
  5613. :param outname:
  5614. :type putname: str
  5615. :return:
  5616. """
  5617. self.report_usage("import_dxf()")
  5618. obj_type = ""
  5619. if geo_type is None or geo_type == "geometry":
  5620. obj_type = "geometry"
  5621. elif geo_type == "gerber":
  5622. obj_type = geo_type
  5623. else:
  5624. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5625. "Only Geometry and Gerber are supported"))
  5626. return
  5627. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5628. def obj_init(geo_obj, app_obj):
  5629. geo_obj.import_dxf(filename, obj_type, units=units)
  5630. geo_obj.multigeo = False
  5631. with self.proc_container.new(_("Importing DXF")) as proc:
  5632. # Object name
  5633. name = outname or filename.split('/')[-1].split('\\')[-1]
  5634. self.new_object(obj_type, name, obj_init, autoselected=False)
  5635. self.progress.emit(20)
  5636. # Register recent file
  5637. self.file_opened.emit("dxf", filename)
  5638. # GUI feedback
  5639. self.inform.emit(_("[success] Opened: %s") % filename)
  5640. self.progress.emit(100)
  5641. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  5642. """
  5643. Adds a new Geometry Object to the projects and populates
  5644. it with shapes extracted from the SVG file.
  5645. :param filename: Path to the SVG file.
  5646. :param outname:
  5647. :return:
  5648. """
  5649. self.report_usage("import_image()")
  5650. obj_type = ""
  5651. if type is None or type == "geometry":
  5652. obj_type = "geometry"
  5653. elif type == "gerber":
  5654. obj_type = type
  5655. else:
  5656. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5657. "Only Geometry and Gerber are supported"))
  5658. return
  5659. def obj_init(geo_obj, app_obj):
  5660. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  5661. geo_obj.multigeo = False
  5662. with self.proc_container.new(_("Importing Image")) as proc:
  5663. # Object name
  5664. name = outname or filename.split('/')[-1].split('\\')[-1]
  5665. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  5666. self.new_object(obj_type, name, obj_init)
  5667. self.progress.emit(20)
  5668. # Register recent file
  5669. self.file_opened.emit("image", filename)
  5670. # GUI feedback
  5671. self.inform.emit(_("[success] Opened: %s") % filename)
  5672. self.progress.emit(100)
  5673. def open_gerber(self, filename, outname=None):
  5674. """
  5675. Opens a Gerber file, parses it and creates a new object for
  5676. it in the program. Thread-safe.
  5677. :param outname: Name of the resulting object. None causes the
  5678. name to be that of the file.
  5679. :param filename: Gerber file filename
  5680. :type filename: str
  5681. :param follow: If true, the parser will not create polygons, just lines
  5682. following the gerber path.
  5683. :type follow: bool
  5684. :return: None
  5685. """
  5686. # How the object should be initialized
  5687. def obj_init(gerber_obj, app_obj):
  5688. assert isinstance(gerber_obj, FlatCAMGerber), \
  5689. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  5690. # Opening the file happens here
  5691. self.progress.emit(30)
  5692. try:
  5693. gerber_obj.parse_file(filename)
  5694. except IOError:
  5695. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  5696. app_obj.progress.emit(0)
  5697. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  5698. return "fail"
  5699. except ParseError as err:
  5700. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename, error=str(err)))
  5701. app_obj.progress.emit(0)
  5702. self.log.error(str(err))
  5703. return "fail"
  5704. except:
  5705. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  5706. msg += traceback.format_exc()
  5707. app_obj.inform.emit(msg)
  5708. return "fail"
  5709. if gerber_obj.is_empty():
  5710. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  5711. # self.collection.set_active(gerber_obj.options["name"])
  5712. # self.collection.delete_active()
  5713. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  5714. return "fail"
  5715. # Further parsing
  5716. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  5717. App.log.debug("open_gerber()")
  5718. with self.proc_container.new(_("Opening Gerber")) as proc:
  5719. self.progress.emit(10)
  5720. # Object name
  5721. name = outname or filename.split('/')[-1].split('\\')[-1]
  5722. ### Object creation ###
  5723. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  5724. if ret == 'fail':
  5725. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  5726. return
  5727. # Register recent file
  5728. self.file_opened.emit("gerber", filename)
  5729. self.progress.emit(100)
  5730. # GUI feedback
  5731. self.inform.emit(_("[success] Opened: %s") % filename)
  5732. def open_excellon(self, filename, outname=None):
  5733. """
  5734. Opens an Excellon file, parses it and creates a new object for
  5735. it in the program. Thread-safe.
  5736. :param outname: Name of the resulting object. None causes the
  5737. name to be that of the file.
  5738. :param filename: Excellon file filename
  5739. :type filename: str
  5740. :return: None
  5741. """
  5742. App.log.debug("open_excellon()")
  5743. #self.progress.emit(10)
  5744. # How the object should be initialized
  5745. def obj_init(excellon_obj, app_obj):
  5746. # self.progress.emit(20)
  5747. try:
  5748. ret = excellon_obj.parse_file(filename)
  5749. if ret == "fail":
  5750. log.debug("Excellon parsing failed.")
  5751. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  5752. return "fail"
  5753. except IOError:
  5754. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  5755. log.debug("Could not open Excellon object.")
  5756. self.progress.emit(0) # TODO: self and app_bjj mixed
  5757. return "fail"
  5758. except:
  5759. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  5760. msg += traceback.format_exc()
  5761. app_obj.inform.emit(msg)
  5762. return "fail"
  5763. ret = excellon_obj.create_geometry()
  5764. if ret == 'fail':
  5765. log.debug("Could not create geometry for Excellon object.")
  5766. return "fail"
  5767. # if excellon_obj.is_empty():
  5768. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5769. # return "fail"
  5770. for tool in excellon_obj.tools:
  5771. if excellon_obj.tools[tool]['solid_geometry']:
  5772. return
  5773. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  5774. return "fail"
  5775. with self.proc_container.new(_("Opening Excellon.")):
  5776. # Object name
  5777. name = outname or filename.split('/')[-1].split('\\')[-1]
  5778. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  5779. if ret == 'fail':
  5780. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  5781. return
  5782. # Register recent file
  5783. self.file_opened.emit("excellon", filename)
  5784. # GUI feedback
  5785. self.inform.emit(_("[success] Opened: %s") % filename)
  5786. # self.progress.emit(100)
  5787. def open_gcode(self, filename, outname=None):
  5788. """
  5789. Opens a G-gcode file, parses it and creates a new object for
  5790. it in the program. Thread-safe.
  5791. :param outname: Name of the resulting object. None causes the
  5792. name to be that of the file.
  5793. :param filename: G-code file filename
  5794. :type filename: str
  5795. :return: None
  5796. """
  5797. App.log.debug("open_gcode()")
  5798. # How the object should be initialized
  5799. def obj_init(job_obj, app_obj_):
  5800. """
  5801. :type app_obj_: App
  5802. """
  5803. assert isinstance(app_obj_, App), \
  5804. "Initializer expected App, got %s" % type(app_obj_)
  5805. self.progress.emit(10)
  5806. try:
  5807. f = open(filename)
  5808. gcode = f.read()
  5809. f.close()
  5810. except IOError:
  5811. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  5812. self.progress.emit(0)
  5813. return "fail"
  5814. job_obj.gcode = gcode
  5815. self.progress.emit(20)
  5816. ret = job_obj.gcode_parse()
  5817. if ret == "fail":
  5818. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  5819. return "fail"
  5820. self.progress.emit(60)
  5821. job_obj.create_geometry()
  5822. with self.proc_container.new(_("Opening G-Code.")):
  5823. # Object name
  5824. name = outname or filename.split('/')[-1].split('\\')[-1]
  5825. # New object creation and file processing
  5826. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5827. if ret == 'fail':
  5828. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5829. "Attempting to create a FlatCAM CNCJob Object from "
  5830. "G-Code file failed during processing"))
  5831. return "fail"
  5832. # Register recent file
  5833. self.file_opened.emit("cncjob", filename)
  5834. # GUI feedback
  5835. self.inform.emit(_("[success] Opened: %s") % filename)
  5836. self.progress.emit(100)
  5837. def open_config_file(self, filename, run_from_arg=None):
  5838. """
  5839. Loads a config file from the specified file.
  5840. :param filename: Name of the file from which to load.
  5841. :type filename: str
  5842. :return: None
  5843. """
  5844. App.log.debug("Opening config file: " + filename)
  5845. # add the tab if it was closed
  5846. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  5847. # first clear previous text in text editor (if any)
  5848. self.ui.code_editor.clear()
  5849. # Switch plot_area to CNCJob tab
  5850. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5851. try:
  5852. if filename:
  5853. f = QtCore.QFile(filename)
  5854. if f.open(QtCore.QIODevice.ReadOnly):
  5855. stream = QtCore.QTextStream(f)
  5856. gcode_edited = stream.readAll()
  5857. self.ui.code_editor.setPlainText(gcode_edited)
  5858. f.close()
  5859. except IOError:
  5860. App.log.error("Failed to open config file: %s" % filename)
  5861. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  5862. return
  5863. def open_project(self, filename, run_from_arg=None):
  5864. """
  5865. Loads a project from the specified file.
  5866. 1) Loads and parses file
  5867. 2) Registers the file as recently opened.
  5868. 3) Calls on_file_new()
  5869. 4) Updates options
  5870. 5) Calls new_object() with the object's from_dict() as init method.
  5871. 6) Calls plot_all()
  5872. :param filename: Name of the file from which to load.
  5873. :type filename: str
  5874. :return: None
  5875. """
  5876. App.log.debug("Opening project: " + filename)
  5877. # Open and parse an uncompressed Project file
  5878. try:
  5879. f = open(filename, 'r')
  5880. except IOError:
  5881. App.log.error("Failed to open project file: %s" % filename)
  5882. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5883. return
  5884. try:
  5885. d = json.load(f, object_hook=dict2obj)
  5886. except:
  5887. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s" % filename)
  5888. f.close()
  5889. # Open and parse a compressed Project file
  5890. try:
  5891. with lzma.open(filename) as f:
  5892. file_content = f.read().decode('utf-8')
  5893. d = json.loads(file_content, object_hook=dict2obj)
  5894. except IOError:
  5895. App.log.error("Failed to open project file: %s" % filename)
  5896. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5897. return
  5898. self.file_opened.emit("project", filename)
  5899. # Clear the current project
  5900. ## NOT THREAD SAFE ##
  5901. if run_from_arg is True:
  5902. pass
  5903. else:
  5904. self.on_file_new()
  5905. #Project options
  5906. self.options.update(d['options'])
  5907. self.project_filename = filename
  5908. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5909. self.set_screen_units(self.options["units"])
  5910. # Re create objects
  5911. App.log.debug("Re-creating objects...")
  5912. for obj in d['objs']:
  5913. def obj_init(obj_inst, app_inst):
  5914. obj_inst.from_dict(obj)
  5915. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5916. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5917. self.plot_all()
  5918. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  5919. self.should_we_save = False
  5920. App.log.debug("Project loaded")
  5921. def propagate_defaults(self, silent=False):
  5922. """
  5923. This method is used to set default values in classes. It's
  5924. an alternative to project options but allows the use
  5925. of values invisible to the user.
  5926. :return: None
  5927. """
  5928. if silent is False:
  5929. self.log.debug("propagate_defaults()")
  5930. # Which objects to update the given parameters.
  5931. routes = {
  5932. "global_zdownrate": CNCjob,
  5933. "excellon_zeros": Excellon,
  5934. "excellon_format_upper_in": Excellon,
  5935. "excellon_format_lower_in": Excellon,
  5936. "excellon_format_upper_mm": Excellon,
  5937. "excellon_format_lower_mm": Excellon,
  5938. "excellon_units": Excellon,
  5939. "gerber_use_buffer_for_union": Gerber,
  5940. "geometry_multidepth": Geometry
  5941. }
  5942. for param in routes:
  5943. if param in routes[param].defaults:
  5944. try:
  5945. routes[param].defaults[param] = self.defaults[param]
  5946. if silent is False:
  5947. self.log.debug(" " + param + " OK")
  5948. except KeyError:
  5949. if silent is False:
  5950. self.log.debug(" ERROR: " + param + " not in defaults.")
  5951. else:
  5952. # Try extracting the name:
  5953. # classname_param here is param in the object
  5954. if param.find(routes[param].__name__.lower() + "_") == 0:
  5955. p = param[len(routes[param].__name__) + 1:]
  5956. if p in routes[param].defaults:
  5957. routes[param].defaults[p] = self.defaults[param]
  5958. if silent is False:
  5959. self.log.debug(" " + param + " OK!")
  5960. def restore_main_win_geom(self):
  5961. try:
  5962. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5963. self.defaults["global_def_win_y"],
  5964. self.defaults["global_def_win_w"],
  5965. self.defaults["global_def_win_h"])
  5966. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5967. settings = QSettings("Open Source", "FlatCAM")
  5968. if settings.contains("maximized_gui"):
  5969. maximized_ui = settings.value('maximized_gui', type=bool)
  5970. if maximized_ui is True:
  5971. self.ui.showMaximized()
  5972. except KeyError:
  5973. pass
  5974. def plot_all(self, zoom=True):
  5975. """
  5976. Re-generates all plots from all objects.
  5977. :return: None
  5978. """
  5979. self.log.debug("Plot_all()")
  5980. for obj in self.collection.get_list():
  5981. def worker_task(obj):
  5982. with self.proc_container.new("Plotting"):
  5983. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5984. if zoom:
  5985. self.object_plotted.emit(obj)
  5986. # Send to worker
  5987. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5988. # self.progress.emit(10)
  5989. #
  5990. # def worker_task(app_obj):
  5991. # print "worker task"
  5992. # percentage = 0.1
  5993. # try:
  5994. # delta = 0.9 / len(self.collection.get_list())
  5995. # except ZeroDivisionError:
  5996. # self.progress.emit(0)
  5997. # return
  5998. # for obj in self.collection.get_list():
  5999. # with self.proc_container.new("Plotting"):
  6000. # obj.plot()
  6001. # app_obj.object_plotted.emit(obj)
  6002. #
  6003. # percentage += delta
  6004. # self.progress.emit(int(percentage*100))
  6005. #
  6006. # self.progress.emit(0)
  6007. # self.plots_updated.emit()
  6008. #
  6009. # # Send to worker
  6010. # #self.worker.add_task(worker_task, [self])
  6011. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6012. def register_folder(self, filename):
  6013. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6014. def register_save_folder(self, filename):
  6015. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6016. def set_progress_bar(self, percentage, text=""):
  6017. self.ui.progress_bar.setValue(int(percentage))
  6018. def setup_shell(self):
  6019. """
  6020. Creates shell functions. Runs once at startup.
  6021. :return: None
  6022. """
  6023. self.log.debug("setup_shell()")
  6024. def shelp(p=None):
  6025. if not p:
  6026. return _("Available commands:\n") + \
  6027. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  6028. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  6029. if p not in commands:
  6030. return "Unknown command: %s" % p
  6031. return commands[p]["help"]
  6032. # --- Migrated to new architecture ---
  6033. # def options(name):
  6034. # ops = self.collection.get_by_name(str(name)).options
  6035. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  6036. def h(*args):
  6037. """
  6038. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  6039. and standalone parameters into list.
  6040. """
  6041. kwa = {}
  6042. a = []
  6043. n = len(args)
  6044. name = None
  6045. for i in range(n):
  6046. match = re.search(r'^-([a-zA-Z].*)', args[i])
  6047. if match:
  6048. assert name is None
  6049. name = match.group(1)
  6050. continue
  6051. if name is None:
  6052. a.append(args[i])
  6053. else:
  6054. kwa[name] = args[i]
  6055. name = None
  6056. return a, kwa
  6057. @contextmanager
  6058. def wait_signal(signal, timeout=10000):
  6059. """
  6060. Block loop until signal emitted, timeout (ms) elapses
  6061. or unhandled exception happens in a thread.
  6062. :param signal: Signal to wait for.
  6063. """
  6064. loop = QtCore.QEventLoop()
  6065. # Normal termination
  6066. signal.connect(loop.quit)
  6067. # Termination by exception in thread
  6068. self.thread_exception.connect(loop.quit)
  6069. status = {'timed_out': False}
  6070. def report_quit():
  6071. status['timed_out'] = True
  6072. loop.quit()
  6073. yield
  6074. # Temporarily change how exceptions are managed.
  6075. oeh = sys.excepthook
  6076. ex = []
  6077. def except_hook(type_, value, traceback_):
  6078. ex.append(value)
  6079. oeh(type_, value, traceback_)
  6080. sys.excepthook = except_hook
  6081. # Terminate on timeout
  6082. if timeout is not None:
  6083. QtCore.QTimer.singleShot(timeout, report_quit)
  6084. #### Block ####
  6085. loop.exec_()
  6086. # Restore exception management
  6087. sys.excepthook = oeh
  6088. if ex:
  6089. self.raiseTclError(str(ex[0]))
  6090. if status['timed_out']:
  6091. raise Exception('Timed out!')
  6092. def make_docs():
  6093. output = ''
  6094. import collections
  6095. od = collections.OrderedDict(sorted(commands.items()))
  6096. for cmd_, val in od.items():
  6097. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  6098. t = val['help']
  6099. usage_i = t.find('>')
  6100. if usage_i < 0:
  6101. expl = t
  6102. output += expl + '\n\n'
  6103. continue
  6104. expl = t[:usage_i - 1]
  6105. output += expl + '\n\n'
  6106. end_usage_i = t[usage_i:].find('\n')
  6107. if end_usage_i < 0:
  6108. end_usage_i = len(t[usage_i:])
  6109. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  6110. else:
  6111. extras = t[usage_i+end_usage_i+1:]
  6112. parts = [s.strip() for s in extras.split('\n')]
  6113. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  6114. for p in parts:
  6115. output += ' ' + p + '\n\n'
  6116. return output
  6117. '''
  6118. Howto implement TCL shell commands:
  6119. All parameters passed to command should be possible to set as None and test it afterwards.
  6120. This is because we need to see error caused in tcl,
  6121. if None value as default parameter is not allowed TCL will return empty error.
  6122. Use:
  6123. def mycommand(name=None,...):
  6124. Test it like this:
  6125. if name is None:
  6126. self.raise_tcl_error('Argument name is missing.')
  6127. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  6128. otherwise we will miss it and processing will silently continue.
  6129. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  6130. which is catched in exec_command and displayed in TCL shell console with red background.
  6131. Error in console is displayed with TCL trace.
  6132. This behavior works only within main thread,
  6133. errors with promissed tasks can be catched and detected only with log.
  6134. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  6135. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  6136. '''
  6137. commands = {
  6138. 'help': {
  6139. 'fcn': shelp,
  6140. 'help': _("Shows list of commands.")
  6141. },
  6142. }
  6143. # Import/overwrite tcl commands as objects of TclCommand descendants
  6144. # This modifies the variable 'commands'.
  6145. tclCommands.register_all_commands(self, commands)
  6146. # Add commands to the tcl interpreter
  6147. for cmd in commands:
  6148. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  6149. # Make the tcl puts function return instead of print to stdout
  6150. self.tcl.eval('''
  6151. rename puts original_puts
  6152. proc puts {args} {
  6153. if {[llength $args] == 1} {
  6154. return "[lindex $args 0]"
  6155. } else {
  6156. eval original_puts $args
  6157. }
  6158. }
  6159. ''')
  6160. def setup_recent_items(self):
  6161. # TODO: Move this to constructor
  6162. icons = {
  6163. "gerber": "share/flatcam_icon16.png",
  6164. "excellon": "share/drill16.png",
  6165. "cncjob": "share/cnc16.png",
  6166. "project": "share/project16.png",
  6167. "svg": "share/geometry16.png",
  6168. "dxf": "share/dxf16.png",
  6169. "image": "share/image16.png"
  6170. }
  6171. openers = {
  6172. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  6173. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  6174. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  6175. 'project': self.open_project,
  6176. 'svg': self.import_svg,
  6177. 'dxf': self.import_dxf,
  6178. 'image': self.import_image
  6179. }
  6180. # Open file
  6181. try:
  6182. f = open(self.data_path + '/recent.json')
  6183. except IOError:
  6184. App.log.error("Failed to load recent item list.")
  6185. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  6186. return
  6187. try:
  6188. self.recent = json.load(f)
  6189. except json.scanner.JSONDecodeError:
  6190. App.log.error("Failed to parse recent item list.")
  6191. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  6192. f.close()
  6193. return
  6194. f.close()
  6195. # Closure needed to create callbacks in a loop.
  6196. # Otherwise late binding occurs.
  6197. def make_callback(func, fname):
  6198. def opener():
  6199. func(fname)
  6200. return opener
  6201. def reset_recent():
  6202. # Reset menu
  6203. self.ui.recent.clear()
  6204. self.recent = []
  6205. try:
  6206. f = open(self.data_path + '/recent.json', 'w')
  6207. except IOError:
  6208. App.log.error("Failed to open recent items file for writing.")
  6209. return
  6210. json.dump(self.recent, f)
  6211. # Reset menu
  6212. self.ui.recent.clear()
  6213. # Create menu items
  6214. for recent in self.recent:
  6215. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6216. try:
  6217. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6218. # Attach callback
  6219. o = make_callback(openers[recent["kind"]], recent['filename'])
  6220. action.triggered.connect(o)
  6221. self.ui.recent.addAction(action)
  6222. except KeyError:
  6223. App.log.error("Unsupported file type: %s" % recent["kind"])
  6224. # Last action in Recent Files menu is one that Clear the content
  6225. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  6226. clear_action.triggered.connect(reset_recent)
  6227. self.ui.recent.addSeparator()
  6228. self.ui.recent.addAction(clear_action)
  6229. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6230. # self.ui.menufilerecent.set_submenu(recent_menu)
  6231. # recent_menu.show_all()
  6232. # self.ui.recent.show()
  6233. self.log.debug("Recent items list has been populated.")
  6234. def setup_component_editor(self):
  6235. # label = QtWidgets.QLabel("Choose an item from Project")
  6236. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6237. sel_title = QtWidgets.QTextEdit(
  6238. _('<b>Shortcut Key List</b>'))
  6239. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6240. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6241. # font = self.sel_title.font()
  6242. # font.setPointSize(12)
  6243. # self.sel_title.setFont(font)
  6244. selected_text = _('''
  6245. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  6246. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6247. The normal flow when working in FlatCAM is the following:</span></p>
  6248. <ol>
  6249. <li><span style="font-size:10px">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 />
  6250. <br />
  6251. 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 />
  6252. &nbsp;</li>
  6253. <li><span style="font-size:10px">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 />
  6254. <br />
  6255. 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 />
  6256. <br />
  6257. You can change the parameters in this screen and the flow direction is like this:<br />
  6258. <br />
  6259. <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>
  6260. </ol>
  6261. <p><span style="font-size:10px">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>
  6262. ''')
  6263. sel_title.setText(selected_text)
  6264. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6265. self.ui.selected_scroll_area.setWidget(sel_title)
  6266. # tool_title = QtWidgets.QTextEdit(
  6267. # '<b>Shortcut Key List</b>')
  6268. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6269. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6270. # # font = self.sel_title.font()
  6271. # # font.setPointSize(12)
  6272. # # self.sel_title.setFont(font)
  6273. #
  6274. # tool_text = '''
  6275. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  6276. #
  6277. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6278. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  6279. #
  6280. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  6281. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  6282. #
  6283. # <ol>
  6284. # </ol>
  6285. #
  6286. # <p><span style="font-size:10px">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: &#39;`&#39; (key left to 1).</span></p>
  6287. #
  6288. # '''
  6289. #
  6290. # tool_title.setText(tool_text)
  6291. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6292. #
  6293. # self.ui.tool_scroll_area.setWidget(tool_title)
  6294. def setup_obj_classes(self):
  6295. """
  6296. Sets up application specifics on the FlatCAMObj class.
  6297. :return: None
  6298. """
  6299. FlatCAMObj.app = self
  6300. ObjectCollection.app = self
  6301. FCProcess.app = self
  6302. FCProcessContainer.app = self
  6303. def version_check(self):
  6304. """
  6305. Checks for the latest version of the program. Alerts the
  6306. user if theirs is outdated. This method is meant to be run
  6307. in a separate thread.
  6308. :return: None
  6309. """
  6310. self.log.debug("version_check()")
  6311. if self.ui.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  6312. full_url = App.version_url + \
  6313. "?s=" + str(self.defaults['global_serial']) + \
  6314. "&v=" + str(self.version) + \
  6315. "&os=" + str(self.os) + \
  6316. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  6317. else:
  6318. # no_stats dict; just so it won't break things on website
  6319. no_ststs_dict = {}
  6320. no_ststs_dict["global_ststs"] = {}
  6321. full_url = App.version_url + \
  6322. "?s=" + str(self.defaults['global_serial']) + \
  6323. "&v=" + str(self.version) + \
  6324. "&os=" + str(self.os) + \
  6325. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6326. App.log.debug("Checking for updates @ %s" % full_url)
  6327. ### Get the data
  6328. try:
  6329. f = urllib.request.urlopen(full_url)
  6330. except:
  6331. # App.log.warning("Failed checking for latest version. Could not connect.")
  6332. self.log.warning("Failed checking for latest version. Could not connect.")
  6333. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  6334. return
  6335. try:
  6336. data = json.load(f)
  6337. except Exception as e:
  6338. App.log.error("Could not parse information about latest version.")
  6339. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  6340. App.log.debug("json.load(): %s" % str(e))
  6341. f.close()
  6342. return
  6343. f.close()
  6344. ### Latest version?
  6345. if self.version >= data["version"]:
  6346. App.log.debug("FlatCAM is up to date!")
  6347. self.inform.emit(_("[success] FlatCAM is up to date!"))
  6348. return
  6349. App.log.debug("Newer version available.")
  6350. self.message.emit(
  6351. _("Newer Version Available"),
  6352. _("There is a newer version of FlatCAM available for download:\n\n") +
  6353. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  6354. _("info")
  6355. )
  6356. def on_zoom_fit(self, event):
  6357. """
  6358. Callback for zoom-out request. This can be either from the corresponding
  6359. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6360. with axes limits from the geometry bounds of all objects.
  6361. :param event: Ignored.
  6362. :return: None
  6363. """
  6364. self.plotcanvas.fit_view()
  6365. def disable_all_plots(self):
  6366. self.report_usage("disable_all_plots()")
  6367. self.disable_plots(self.collection.get_list())
  6368. self.inform.emit(_("[success] All plots disabled."))
  6369. def disable_other_plots(self):
  6370. self.report_usage("disable_other_plots()")
  6371. self.disable_plots(self.collection.get_non_selected())
  6372. self.inform.emit(_("[success] All non selected plots disabled."))
  6373. def enable_all_plots(self):
  6374. self.report_usage("enable_all_plots()")
  6375. self.enable_plots(self.collection.get_list())
  6376. self.inform.emit(_("[success] All plots enabled."))
  6377. # TODO: FIX THIS
  6378. '''
  6379. By default this is not threaded
  6380. If threaded the app give warnings like this:
  6381. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6382. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6383. '''
  6384. def enable_plots(self, objects, threaded=False):
  6385. if threaded is True:
  6386. def worker_task(app_obj):
  6387. percentage = 0.1
  6388. try:
  6389. delta = 0.9 / len(objects)
  6390. except ZeroDivisionError:
  6391. self.progress.emit(0)
  6392. return
  6393. for obj in objects:
  6394. obj.options['plot'] = True
  6395. percentage += delta
  6396. self.progress.emit(int(percentage*100))
  6397. self.progress.emit(0)
  6398. self.plots_updated.emit()
  6399. self.collection.update_view()
  6400. # Send to worker
  6401. # self.worker.add_task(worker_task, [self])
  6402. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6403. else:
  6404. for obj in objects:
  6405. obj.options['plot'] = True
  6406. self.progress.emit(0)
  6407. self.plots_updated.emit()
  6408. self.collection.update_view()
  6409. # TODO: FIX THIS
  6410. '''
  6411. By default this is not threaded
  6412. If threaded the app give warnings like this:
  6413. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6414. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6415. '''
  6416. def disable_plots(self, objects, threaded=False):
  6417. # TODO: This method is very similar to replot_all. Try to merge.
  6418. """
  6419. Disables plots
  6420. :param objects: list
  6421. Objects to be disabled
  6422. :return:
  6423. """
  6424. if threaded is True:
  6425. self.progress.emit(10)
  6426. def worker_task(app_obj):
  6427. percentage = 0.1
  6428. try:
  6429. delta = 0.9 / len(objects)
  6430. except ZeroDivisionError:
  6431. self.progress.emit(0)
  6432. return
  6433. for obj in objects:
  6434. obj.options['plot'] = False
  6435. percentage += delta
  6436. self.progress.emit(int(percentage*100))
  6437. self.progress.emit(0)
  6438. self.plots_updated.emit()
  6439. self.collection.update_view()
  6440. # Send to worker
  6441. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6442. else:
  6443. for obj in objects:
  6444. obj.options['plot'] = False
  6445. self.plots_updated.emit()
  6446. self.collection.update_view()
  6447. def clear_plots(self):
  6448. objects = self.collection.get_list()
  6449. for obj in objects:
  6450. obj.clear(obj == objects[-1])
  6451. # Clear pool to free memory
  6452. self.clear_pool()
  6453. def generate_cnc_job(self, objects):
  6454. self.report_usage("generate_cnc_job()")
  6455. # for obj in objects:
  6456. # obj.generatecncjob()
  6457. for obj in objects:
  6458. obj.on_generatecnc_button_click()
  6459. def save_project(self, filename, quit=False):
  6460. """
  6461. Saves the current project to the specified file.
  6462. :param filename: Name of the file in which to save.
  6463. :type filename: str
  6464. :return: None
  6465. """
  6466. self.log.debug("save_project()")
  6467. self.save_in_progress = True
  6468. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6469. ## Capture the latest changes
  6470. # Current object
  6471. try:
  6472. self.collection.get_active().read_form()
  6473. except:
  6474. self.log.debug("There was no active object")
  6475. pass
  6476. # Project options
  6477. self.options_read_form()
  6478. # Serialize the whole project
  6479. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6480. "options": self.options,
  6481. "version": self.version}
  6482. if self.defaults["global_save_compressed"] is True:
  6483. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6484. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6485. # # Write
  6486. f.write(g)
  6487. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6488. else:
  6489. # Open file
  6490. try:
  6491. f = open(filename, 'w')
  6492. except IOError:
  6493. App.log.error("Failed to open file for saving: %s", filename)
  6494. return
  6495. # Write
  6496. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6497. f.close()
  6498. # verification of the saved project
  6499. # Open and parse
  6500. try:
  6501. saved_f = open(filename, 'r')
  6502. except IOError:
  6503. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6504. return
  6505. try:
  6506. saved_d = json.load(saved_f, object_hook=dict2obj)
  6507. except:
  6508. self.inform.emit(
  6509. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6510. f.close()
  6511. return
  6512. saved_f.close()
  6513. if 'version' in saved_d:
  6514. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6515. else:
  6516. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6517. if quit:
  6518. t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  6519. t.start()
  6520. # using Alfe's answer from here:
  6521. # https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python
  6522. def check_project_file_size(self, delay, filename):
  6523. next_time = time.time() + delay
  6524. while True:
  6525. time.sleep(max(0, next_time - time.time()))
  6526. try:
  6527. statinfo = os.stat(filename)
  6528. if statinfo:
  6529. self.app_quit.emit()
  6530. except Exception:
  6531. traceback.print_exc()
  6532. # in production code you might want to have this instead of course:
  6533. # logger.exception("Problem while executing repetitive task.")
  6534. # skip tasks if we are behind schedule:
  6535. next_time += (time.time() - next_time) // delay * delay + delay
  6536. def on_options_app2project(self):
  6537. """
  6538. Callback for Options->Transfer Options->App=>Project. Copies options
  6539. from application defaults to project defaults.
  6540. :return: None
  6541. """
  6542. self.report_usage("on_options_app2project")
  6543. self.defaults_read_form()
  6544. self.options.update(self.defaults)
  6545. self.options_write_form()
  6546. def on_options_project2app(self):
  6547. """
  6548. Callback for Options->Transfer Options->Project=>App. Copies options
  6549. from project defaults to application defaults.
  6550. :return: None
  6551. """
  6552. self.report_usage("on_options_project2app")
  6553. self.options_read_form()
  6554. self.defaults.update(self.options)
  6555. self.defaults_write_form()
  6556. def on_options_project2object(self):
  6557. """
  6558. Callback for Options->Transfer Options->Project=>Object. Copies options
  6559. from project defaults to the currently selected object.
  6560. :return: None
  6561. """
  6562. self.report_usage("on_options_project2object")
  6563. self.options_read_form()
  6564. obj = self.collection.get_active()
  6565. if obj is None:
  6566. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6567. return
  6568. for option in self.options:
  6569. if option.find(obj.kind + "_") == 0:
  6570. oname = option[len(obj.kind) + 1:]
  6571. obj.options[oname] = self.options[option]
  6572. obj.to_form() # Update UI
  6573. def on_options_object2project(self):
  6574. """
  6575. Callback for Options->Transfer Options->Object=>Project. Copies options
  6576. from the currently selected object to project defaults.
  6577. :return: None
  6578. """
  6579. self.report_usage("on_options_object2project")
  6580. obj = self.collection.get_active()
  6581. if obj is None:
  6582. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6583. return
  6584. obj.read_form()
  6585. for option in obj.options:
  6586. if option in ['name']: # TODO: Handle this better...
  6587. continue
  6588. self.options[obj.kind + "_" + option] = obj.options[option]
  6589. self.options_write_form()
  6590. def on_options_object2app(self):
  6591. """
  6592. Callback for Options->Transfer Options->Object=>App. Copies options
  6593. from the currently selected object to application defaults.
  6594. :return: None
  6595. """
  6596. self.report_usage("on_options_object2app")
  6597. obj = self.collection.get_active()
  6598. if obj is None:
  6599. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6600. return
  6601. obj.read_form()
  6602. for option in obj.options:
  6603. if option in ['name']: # TODO: Handle this better...
  6604. continue
  6605. self.defaults[obj.kind + "_" + option] = obj.options[option]
  6606. self.defaults_write_form()
  6607. def on_options_app2object(self):
  6608. """
  6609. Callback for Options->Transfer Options->App=>Object. Copies options
  6610. from application defaults to the currently selected object.
  6611. :return: None
  6612. """
  6613. self.report_usage("on_options_app2object")
  6614. self.defaults_read_form()
  6615. obj = self.collection.get_active()
  6616. if obj is None:
  6617. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6618. return
  6619. for option in self.defaults:
  6620. if option.find(obj.kind + "_") == 0:
  6621. oname = option[len(obj.kind) + 1:]
  6622. obj.options[oname] = self.defaults[option]
  6623. obj.to_form() # Update UI
  6624. # end of file