FlatCAMApp.py 355 KB

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